Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): list chats with a saved state right after a restart
Yudhi Armyndharisd16dbc582cce
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 8fb34b745..fb12e145d 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -493,7 +493,7 @@ is the instant the mute ends in epoch milliseconds (`0` = indefinite), the sameSorted by `timestamp` DESC (most recent first) then paginated. `timestamp` is an epoch number (seconds). `kind` is the user-facing chat discriminator — one of `individual|group|channel|status|broadcast|unknown`; `isGroup` is retained for back-compat (true only for `kind: "group"`).-On the Baileys engine the list is rebuilt from live traffic after a restart: groups come back at once, and a 1:1 chat when its next message arrives. See `docs/29-engine-capability-matrix.md` §29.7 (`getChats` after a restart).+On the Baileys engine the list is rebuilt after a restart: groups and chats with a persisted archive, pin or mute state come back at once, and any other 1:1 chat when its next message arrives. See `docs/29-engine-capability-matrix.md` §29.7 (`getChats` after a restart).**Errors:** `400` session not started · `401` · `403` · `404` session not found · `409` session not connected (also answered for a few seconds while WhatsApp Web reloads its page and the engine re-injects) · `503` page connection died mid-read, or the command timed outdiff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.mdindex a0b683c25..a3e5d8ffb 100644--- a/docs/29-engine-capability-matrix.md+++ b/docs/29-engine-capability-matrix.md@@ -944,11 +944,12 @@ adapter boundary — none silently stubs.- **`getChats` after a restart (baileys).** Baileys keeps no chat list of its own, and WhatsAppskips history sync on every connect after the first link, so a new engine (a process restart, asession stop and start, or a reconnect the gateway runs itself, as for `deleteStatus` above) starts- with an empty one. `GET /chats` then lists the groups, re-fetched on every connect, and each 1:1- chat as its next message arrives; a quiet chat stays out of the list until then. Rows rebuilt this- way carry timestamp `0` and no `lastMessage` until a message arrives. A chat's archive, pin and mute- state is persisted and shows as soon as the chat is listed. The transient reconnects Baileys runs on- its own keep the list. whatsapp-web.js reads WhatsApp Web's own chat list and is unaffected.+ with an empty one. `GET /chats` then lists the groups, re-fetched on every connect, and every chat+ with a persisted archive, pin or mute state (bounded by `BAILEYS_CHAT_STATE_CACHE_MAX`); any other+ 1:1 chat comes back when its next message arrives and stays out of the list until then. Rows+ rebuilt this way carry timestamp `0` and no `lastMessage` until a message arrives. The transient+ reconnects Baileys runs on its own keep the list. whatsapp-web.js reads WhatsApp Web's own chat+ list and is unaffected.- **`getContactStatus` / `getContactStatuses` (wwjs).** `Status.type` is the `text|image|video`union — audio/other story types collapse to `text`.- **`archiveChat` / `clearChatMessages` / `deleteChat` / `sendSeen` / `markUnread` (baileys).** Thediff --git a/src/engine/adapters/baileys-chat-state-store.service.spec.ts b/src/engine/adapters/baileys-chat-state-store.service.spec.tsindex 067f08c9c..0d4dc6d16 100644--- a/src/engine/adapters/baileys-chat-state-store.service.spec.ts+++ b/src/engine/adapters/baileys-chat-state-store.service.spec.ts@@ -121,6 +121,20 @@ describe('ChatStateStoreService', () => {});});+ it("lists the chat ids of one session's cached states", async () => {+ const svc = svcWith(+ makeRepo([+ { sessionId: 's', chatId: 'a', archived: true },+ { sessionId: 's', chatId: 'b', pinned: true },+ { sessionId: 't', chatId: 'c', pinned: true },+ ]),+ );+ await svc.reload();+ expect(svc.chatIds('s').sort()).toEqual(['a', 'b']);+ await svc.forget('s', ['a']);+ expect(svc.chatIds('s')).toEqual(['b']);+ });+it('returns undefined for an unknown chat', () => {expect(svcWith(makeRepo()).get('s', 'nope')).toBeUndefined();});diff --git a/src/engine/adapters/baileys-chat-state-store.service.ts b/src/engine/adapters/baileys-chat-state-store.service.tsindex 9aa4ad4d1..d9229338f 100644--- a/src/engine/adapters/baileys-chat-state-store.service.ts+++ b/src/engine/adapters/baileys-chat-state-store.service.ts@@ -32,6 +32,8 @@ export type ChatStateValue = {export interface ChatStateStore {/** Sync read from the in-memory mirror; undefined = no persisted state for this chat (defaults apply). */get(sessionId: string, chatId: string): ChatStateValue | undefined;+ /** The chat ids the in-memory mirror holds a state for in one session (bounded by the cache cap). */+ chatIds(sessionId: string): string[];/*** Write-through, last-write-wins: merge the patch into the stored state and persist. With `create`* false, a patch that only restates defaults writes nothing for a chat with no row (an update that@@ -199,6 +201,11 @@ export class ChatStateStoreService implements ChatStateStore, OnModuleInit {return undefined;}+ chatIds(sessionId: string): string[] {+ const prefix = `${sessionId}${SEP}`;+ return [...this.states.keys()].filter(k => k.startsWith(prefix)).map(k => k.slice(prefix.length));+ }+/*** Serialized per chat: the caller does not await, so two patches for an uncached chat would otherwise* both merge onto the same pre-change row and the later full-row write would drop the earlier patch.diff --git a/src/engine/adapters/baileys-session-store.spec.ts b/src/engine/adapters/baileys-session-store.spec.tsindex 906f35449..c65577d48 100644--- a/src/engine/adapters/baileys-session-store.spec.ts+++ b/src/engine/adapters/baileys-session-store.spec.ts@@ -18,6 +18,9 @@ class FakeChatStateStore implements ChatStateStore {get(s: string, c: string): ChatStateValue | undefined {return this.rows.get(this.key(s, c));}+ chatIds(s: string): string[] {+ return [...this.rows.keys()].filter(k => k.startsWith(`${s}\u0000`)).map(k => k.slice(s.length + 1));+ }remember(s: string, c: string, patch: Partial<ChatStateValue>, create = true): Promise<void> {// Same bookkeeping as the real store: a new row observes only what the patch carries, and a patch// that may not create one writes nothing when it only restates defaults.@@ -1115,6 +1118,28 @@ describe('BaileysSessionStore', () => {expect(fake.rows.size).toBe(0);});+ it('lists a chat with a persisted state after a restart, before its next message', () => {+ fake.rows.set(K(PHONE), { muteEndTime: null, archived: false, pinned: true });+ fake.rows.set(K('[email protected]'), { muteEndTime: -1, archived: false, pinned: false });+ fake.rows.set('other\[email protected]', { muteEndTime: -1, archived: false, pinned: false });+ const s = newStore();+ s.upsertContacts([{ id: PHONE, name: 'Alice' }]);+ s.upsertChats([{ id: '[email protected]', name: 'Bob', conversationTimestamp: 70 }]);+ expect(s.listChats()).toEqual([+ expect.objectContaining({ id: '[email protected]', name: 'Bob', timestamp: 70, muted: true }),+ expect.objectContaining({ id: '[email protected]', name: 'Alice', timestamp: 0, pinned: true }),+ ]);+ s.removeChats([PHONE]);+ expect(s.listChats().map(c => c.id)).toEqual(['[email protected]']);+ });++ it('lists a persisted state filed under a lid once, under the phone', () => {+ fake.rows.set(K(LID), { muteEndTime: null, archived: true, pinned: false });+ const s = newStore();+ s.addLidMappings([{ lid: LID, pn: PHONE }]);+ expect(s.listChats()).toEqual([expect.objectContaining({ id: '[email protected]', archived: true })]);+ });+it('finds the disappearing timer a lid-keyed chat record carries from the @c.us id', () => {const s = new BaileysSessionStore();s.upsertChats([{ id: LID, ephemeralExpiration: 86400 }]);diff --git a/src/engine/adapters/baileys-session-store.ts b/src/engine/adapters/baileys-session-store.tsindex 4e03d397a..70188d6f1 100644--- a/src/engine/adapters/baileys-session-store.ts+++ b/src/engine/adapters/baileys-session-store.ts@@ -170,9 +170,10 @@ function mergeContactTwins(a: ContactTwin, b: ContactTwin): ContactTwin {* and `messaging-history.set` arrives only on the first link: once the account has synced, WhatsApp* skips history sync on every later connect (see BaileysHistory.hydrateNames). A new engine (a process* restart, a session stop and start, a reconnect the gateway runs itself) therefore starts with no- * chats: the groups hydrateNames re-fetches on every open come back at once, and a 1:1 chat comes back- * with its next message, since Baileys emits `chats.update` for every real message. Mute, archive and- * pin survive through the ChatStateStore. Contacts are rebuilt from the address-book snapshot instead.+ * chats: the groups hydrateNames re-fetches on every open come back at once, a chat with a persisted+ * mute, archive or pin (ChatStateStore) is listed from that row, and any other 1:1 chat comes back with+ * its next message, since Baileys emits `chats.update` for every real message. Contacts are rebuilt+ * from the address-book snapshot instead.** Every map is LRU-bounded (`BAILEYS_SESSION_STORE_MAX_ENTRIES`, default 5000 per map, 0 = unbounded)* because contacts/chats/lastMessages/lidToPn all grow from peer-controlled traffic — without a cap a@@ -610,6 +611,14 @@ export class BaileysSessionStore {const id = this.toNeutralJid(c.id!);byId.set(id, [...(byId.get(id) ?? []), c]);}+ // A new engine starts with no chats (see the class comment), but a chat with a persisted state is+ // known to exist: a deleted chat loses its row. So it is listed before its next message arrives.+ if (this.chatStateStore && this.sessionId) {+ for (const chatId of this.chatStateStore.chatIds(this.sessionId)) {+ const id = this.toNeutralJid(chatId);+ if (!byId.has(id)) byId.set(id, [{ id: chatId }]);+ }+ }return [...byId].map(([id, records]) => this.toNeutralChat(id, records, previews.get(id), lidIndex));}diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 2334def8e..0d6f47863 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -4912,6 +4912,7 @@ describe('BaileysAdapter store-backed ops', () => {describe('persisted chat states', () => {const chatStateStore = {get: jest.fn(),+ chatIds: jest.fn((): string[] => []),remember: jest.fn().mockResolvedValue(undefined),fold: jest.fn().mockResolvedValue(undefined),reload: jest.fn().mockResolvedValue(undefined),@@ -4937,6 +4938,16 @@ describe('BaileysAdapter store-backed ops', () => {// Another node may have written rows while it held the session (takeover).const makeSocket = (): jest.Mock => jest.requireMock<{ default: jest.Mock }>('@whiskeysockets/baileys').default;+ it('lists a chat that has one on a new engine, before its next message', async () => {+ chatStateStore.chatIds.mockReturnValueOnce(['[email protected]']);+ chatStateStore.get.mockImplementation((_s: string, chatId: string) =>+ chatId === '[email protected]' ? { muteEndTime: null, archived: false, pinned: true } : undefined,+ );+ const adapter = await linked();+ expect(await adapter.getChats()).toEqual([expect.objectContaining({ id: '[email protected]', pinned: true })]);+ chatStateStore.get.mockReset();+ });+it('re-reads them on start, before the socket opens', async () => {makeSocket().mockClear();let opened = false;