Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(baileys): drop a deleted chat from the chat list

Yudhi Armyndharis09be17507f8e
diff --git a/docs/05-database-design.md b/docs/05-database-design.md
index 88763fdab..49a8eb14d 100644
--- a/docs/05-database-design.md
+++ b/docs/05-database-design.md
@@ -664,7 +664,7 @@ The data connection also owns:
- **`integration_delivery_failures`** — DLQ-of-record for both inbound (ingress) and outbound (provider egress) delivery failures (`src/modules/integration/entities/integration-delivery-failure.entity.ts`).
- **`baileys_stored_messages`** — Baileys engine message store — the serialized WAMessage proto (`src/engine/adapters/baileys-stored-message.entity.ts`); present only when the Baileys engine is used. (Credentials live on the filesystem, not here.)
- **`lid_mappings`** — LID↔phone-number identity mappings (`src/engine/identity/lid-mapping.entity.ts`).
-- **`chat_states`** (engine): per-session mute, archive and pin state of each Baileys chat (`src/engine/adapters/baileys-chat-state.entity.ts`), keyed `(sessionId, chatId)`. WhatsApp does not re-deliver that state, so it is kept in backups.
+- **`chat_states`** (engine): per-session mute, archive and pin state of each Baileys chat (`src/engine/adapters/baileys-chat-state.entity.ts`), keyed `(sessionId, chatId)`. WhatsApp does not re-deliver that state, so it is kept in backups. A chat deleted on the phone or through the API loses its row, so a later message starts it clean.
Additionally, the `AddMessagesFts` migration creates the full-text-search structures over `messages` (a FTS5 virtual table on SQLite, a generated `body_ts` `tsvector` column plus GIN index on PostgreSQL) that back the `/search` endpoint.
diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.md
index 453f78220..386ea4c05 100644
--- a/docs/29-engine-capability-matrix.md
+++ b/docs/29-engine-capability-matrix.md
@@ -814,7 +814,7 @@ OpenWA consumes events by normalizing them into `EngineEventCallbacks`; anything
| `messaging-history.set` | ✅ | | `messaging-history.status` | ❌ |
| `chats.upsert` | ✅ | | `newsletter-participants.update` | ❌ |
| `chats.update` | ✅ | | `newsletter-settings.update` | ❌ |
-| `chats.delete` | ❌ | | `newsletter.reaction` | ❌ |
+| `chats.delete` | ✅ | | `newsletter.reaction` | ❌ |
| `contacts.upsert` | ✅ | | `newsletter.view` | ❌ |
| `contacts.update` | ✅ | | `settings.update` | ❌ |
| `groups.update` | ✅ | | `blocklist.set` | ❌ |
diff --git a/src/engine/adapters/baileys-chat-state-store.service.spec.ts b/src/engine/adapters/baileys-chat-state-store.service.spec.ts
index c3fdff5c3..7b2be4224 100644
--- a/src/engine/adapters/baileys-chat-state-store.service.spec.ts
+++ b/src/engine/adapters/baileys-chat-state-store.service.spec.ts
@@ -26,8 +26,9 @@ function makeRepo(initial: Partial<ChatState>[] = []) {
rows.set(KEY(v.sessionId, v.chatId), { ...rows.get(KEY(v.sessionId, v.chatId)), ...v });
return Promise.resolve(undefined);
}),
- delete: jest.fn(({ sessionId }: { sessionId: string }) => {
- for (const [k, r] of rows) if (r.sessionId === sessionId) rows.delete(k);
+ delete: jest.fn(({ sessionId, chatId }: { sessionId: string; chatId?: string }) => {
+ for (const [k, r] of rows)
+ if (r.sessionId === sessionId && (chatId === undefined || r.chatId === chatId)) rows.delete(k);
return Promise.resolve(undefined);
}),
};
@@ -172,6 +173,28 @@ describe('ChatStateStoreService', () => {
expect(repo.findOne).toHaveBeenCalledTimes(3); // 't' is still skipped
});
+ it('forget drops the named chats of one session from the table and the cache, after their pending writes', async () => {
+ const repo = makeRepo([
+ { sessionId: 's', chatId: 'd', pinned: true },
+ { sessionId: 't', chatId: 'c', pinned: true },
+ ]);
+ const svc = svcWith(repo);
+ await svc.reload();
+ const pending = svc.remember('s', 'c', { archived: true }); // not awaited, as the session store calls it
+ await svc.forget('s', ['c', 'd']);
+ await pending;
+ expect([...repo.rows.keys()]).toEqual([KEY('t', 'c')]);
+ expect(svc.get('s', 'c')).toBeUndefined();
+ expect(svc.get('s', 'd')).toBeUndefined();
+ expect(svc.get('t', 'c')).toEqual(expect.objectContaining({ pinned: true }));
+ });
+
+ it('forget swallows a repo error', async () => {
+ const repo = makeRepo();
+ repo.delete.mockRejectedValueOnce(new Error('SQLITE_BUSY'));
+ await expect(svcWith(repo).forget('s', ['c'])).resolves.toBeUndefined();
+ });
+
it('keeps both of two concurrent patches for a chat that is not cached yet', async () => {
const repo = makeRepo();
const svc = svcWith(repo);
diff --git a/src/engine/adapters/baileys-chat-state-store.service.ts b/src/engine/adapters/baileys-chat-state-store.service.ts
index 1b45d48c4..bfb0b70e6 100644
--- a/src/engine/adapters/baileys-chat-state-store.service.ts
+++ b/src/engine/adapters/baileys-chat-state-store.service.ts
@@ -23,6 +23,8 @@ export interface ChatStateStore {
reload(): Promise<void>;
/** Forget every chat state of one session (an unlink: the next account to link it starts clean). */
clearSession(sessionId: string): Promise<void>;
+ /** Forget the named chats of one session (a deleted chat: one a later message re-creates starts clean). */
+ forget(sessionId: string, chatIds: string[]): Promise<void>;
/** Re-read a session's chats known to have no row (a start: another node may have written them since). */
forgetAbsent(sessionId: string): void;
}
@@ -174,6 +176,28 @@ export class ChatStateStoreService implements ChatStateStore, OnModuleInit {
}
}
+ /** Queued behind each chat's pending writes, so a patch still in flight cannot re-create the row. */
+ async forget(sessionId: string, chatIds: string[]): Promise<void> {
+ await Promise.all(
+ chatIds.map(chatId => {
+ const k = this.key(sessionId, chatId);
+ return new Promise<void>(resolve =>
+ this.writes.enqueue(k, async () => {
+ try {
+ await this.repo.delete({ sessionId, chatId });
+ } catch (err) {
+ this.logger.warn(
+ `Failed to forget chat state for ${chatId}: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ }
+ this.states.delete(k);
+ resolve();
+ }),
+ );
+ }),
+ );
+ }
+
forgetAbsent(sessionId: string): void {
const prefix = `${sessionId}${SEP}`;
for (const k of [...this.absent]) {
diff --git a/src/engine/adapters/baileys-lifecycle.ts b/src/engine/adapters/baileys-lifecycle.ts
index 1249499a6..863075903 100644
--- a/src/engine/adapters/baileys-lifecycle.ts
+++ b/src/engine/adapters/baileys-lifecycle.ts
@@ -140,6 +140,8 @@ export interface BaileysLifecycleHost {
upsertContacts: BaileysSessionStore['upsertContacts'];
/** Persist chat records pushed by the socket (chats.upsert/update, messaging-history.set). */
upsertChats: BaileysSessionStore['upsertChats'];
+ /** Drop chats the socket reports deleted (chats.delete). */
+ removeChats: BaileysSessionStore['removeChats'];
/** Learn lid<->phone mappings pushed by the socket (messaging-history.set, lid-mapping.update). */
addLidMappings: BaileysSessionStore['addLidMappings'];
handleMessagesUpsert: BaileysEvents['handleMessagesUpsert'];
@@ -312,7 +314,7 @@ export class BaileysLifecycle {
}
// An internal reconnect (transient drop) overwrites this.sock WITHOUT going through
- // disconnect/logout/destroy, so the previous socket's WebSocket and the 16 ev listeners we
+ // disconnect/logout/destroy, so the previous socket's WebSocket and the 17 ev listeners we
// register below would leak on every reconnect. Tear the prior socket down first. Detach OUR
// connection.update listener BEFORE end(): Baileys' own end() synchronously emits a synthetic
// connection.update {connection:'close'}, which — if still wired — would re-enter
@@ -328,6 +330,7 @@ export class BaileysLifecycle {
previous.ev.removeAllListeners('contacts.update');
previous.ev.removeAllListeners('chats.upsert');
previous.ev.removeAllListeners('chats.update');
+ previous.ev.removeAllListeners('chats.delete');
previous.ev.removeAllListeners('messaging-history.set');
previous.ev.removeAllListeners('lid-mapping.update');
previous.ev.removeAllListeners('group-participants.update');
@@ -466,6 +469,14 @@ export class BaileysLifecycle {
});
this.host.upsertChats(updates);
});
+ sock.ev.on('chats.delete', ids => {
+ this.host.logger.debug('Baileys chats event', {
+ action: 'baileys_chats',
+ event: 'delete',
+ count: ids?.length ?? 0,
+ });
+ this.host.removeChats(ids);
+ });
sock.ev.on('group-participants.update', event => this.host.handleGroupParticipantsUpdate(event));
sock.ev.on('groups.update', updates => this.host.handleGroupsUpdate(updates));
sock.ev.on('groups.upsert', groups => this.host.handleGroupsUpsert(groups));
diff --git a/src/engine/adapters/baileys-session-store.spec.ts b/src/engine/adapters/baileys-session-store.spec.ts
index d95a7eabd..893e5116d 100644
--- a/src/engine/adapters/baileys-session-store.spec.ts
+++ b/src/engine/adapters/baileys-session-store.spec.ts
@@ -23,6 +23,10 @@ class FakeChatStateStore implements ChatStateStore {
clearSession(): Promise<void> {
return Promise.resolve();
}
+ forget(s: string, chatIds: string[]): Promise<void> {
+ for (const c of chatIds) this.rows.delete(this.key(s, c));
+ return Promise.resolve();
+ }
forgetAbsent(): void {}
}
@@ -641,6 +645,24 @@ describe('BaileysSessionStore', () => {
expect(store.listChats()[0].lastMessage).toBe('edited');
});
+ it('removes a deleted chat, its preview and its chat state under every spelling', () => {
+ const fake = new FakeChatStateStore();
+ const s = new BaileysSessionStore(undefined, 'sess-1', fake);
+ s.upsertChats([{ id: LID, name: 'Alice', pinned: 7 }]);
+ s.recordKeyLidMappings({ remoteJid: LID, remoteJidAlt: PHONE });
+ s.recordMessage(msg(LID, 'IN', 100));
+ s.upsertChats([{ id: '[email protected]', name: 'Team' }]);
+ // Baileys names the deleted chat by the id its app-state index carries, here the phone twin.
+ s.removeChats([PHONE]);
+ expect(s.listChats()).toEqual([expect.objectContaining({ id: '[email protected]' })]);
+ expect(s.lastMessage('[email protected]')).toBeNull();
+ expect(s.lastInboundMessage('[email protected]')).toBeNull();
+ expect(fake.rows.size).toBe(0);
+ // A later message re-creates the chat without the pin the deleted one carried.
+ s.upsertChats([{ id: LID }]);
+ expect(s.listChats().find(c => c.id === '[email protected]')).toEqual(expect.objectContaining({ pinned: false }));
+ });
+
it('finds the lid twin through the persisted table as well', () => {
const lidStore = {
getCached: jest.fn(() => undefined),
diff --git a/src/engine/adapters/baileys-session-store.ts b/src/engine/adapters/baileys-session-store.ts
index 0fa483690..139fa6b9a 100644
--- a/src/engine/adapters/baileys-session-store.ts
+++ b/src/engine/adapters/baileys-session-store.ts
@@ -61,6 +61,10 @@ class LruMap<K, V> {
return this.map.has(key);
}
+ delete(key: K): void {
+ this.drop(key);
+ }
+
get(key: K): V | undefined {
if (!this.map.has(key)) {
return undefined;
@@ -292,6 +296,25 @@ export class BaileysSessionStore {
}
}
+ /**
+ * Drop chats Baileys reports deleted (`chats.delete`: an API delete replayed locally, or one made on
+ * the phone), with their preview and last inbound message, under every spelling: the id comes from
+ * the app-state index, which need not be the twin the chat or its messages are keyed under. The
+ * persisted mute/archive/pin goes too: a chat a later message re-creates is a new chat on WhatsApp,
+ * and the row would otherwise lay the deleted chat's state over it.
+ */
+ removeChats(ids: string[] = []): void {
+ const keys = new Set(ids.flatMap(id => this.chatTwins(id)));
+ for (const key of keys) {
+ this.chats.delete(key);
+ this.lastMessages.delete(key);
+ this.lastInbound.delete(key);
+ }
+ if (keys.size && this.chatStateStore && this.sessionId) {
+ void this.chatStateStore.forget(this.sessionId, [...keys]);
+ }
+ }
+
addLidMappings(mappings: { lid?: string; pn?: string }[] = []): void {
for (const m of mappings) {
if (m.lid && m.pn) {
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 562eb2f28..8156ac5a4 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -1409,6 +1409,17 @@ describe('BaileysAdapter reconnect socket teardown (no leak)', () => {
expect(adapter.getStatus()).not.toBe(EngineStatus.FAILED);
});
+ it('detaches the chat listeners of the previous socket on an internal reconnect', async () => {
+ await initWithRealTimers();
+ jest.useFakeTimers();
+ fireRecoverableClose();
+ await jest.runAllTimersAsync();
+ // The fake hands back the same socket, so a listener the teardown missed would now be doubled.
+ for (const event of ['chats.upsert', 'chats.update', 'chats.delete']) {
+ expect(fakeSock.emitter.listenerCount(event)).toBe(1);
+ }
+ });
+
it('tearing down the previous socket does not trigger a spurious second reconnect', async () => {
const adapter = await initWithRealTimers();
jest.useFakeTimers();
@@ -4606,6 +4617,7 @@ describe('BaileysAdapter store-backed ops', () => {
remember: jest.fn().mockResolvedValue(undefined),
reload: jest.fn().mockResolvedValue(undefined),
clearSession: jest.fn(),
+ forget: jest.fn().mockResolvedValue(undefined),
forgetAbsent: jest.fn(),
};
const linked = async (onDisconnected = jest.fn()): Promise<BaileysAdapter> => {
@@ -6265,6 +6277,15 @@ describe('BaileysAdapter sendSeen + markUnread + deleteChat', () => {
});
});
+ it('drops a chat Baileys reports deleted from the listing', async () => {
+ const adapter = await readyWithMessage();
+ fakeSock.fire('chats.upsert', [{ id: '[email protected]' }]);
+ expect(await adapter.getChats()).toHaveLength(1);
+ fakeSock.fire('chats.delete', ['[email protected]']);
+ expect(await adapter.getChats()).toEqual([]);
+ expect(await adapter.deleteChat('[email protected]')).toBe(false);
+ });
+
it('clearChatMessages returns false for a chat with no known history', async () => {
const adapter = newAdapter();
await adapter.initialize({});
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index cf2637e63..3e435bfe7 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -169,6 +169,7 @@ export class BaileysAdapter implements IWhatsAppEngine {
lastInboundMessage: chatId => this.sessionStore.lastInboundMessage(chatId),
upsertContacts: records => this.sessionStore.upsertContacts(records),
upsertChats: records => this.sessionStore.upsertChats(records),
+ removeChats: ids => this.sessionStore.removeChats(ids),
extractEphemeralDuration: msg => this.sessionStore.extractEphemeralDuration(msg),
getOnHistoryMessages: () => this.callbacks.onHistoryMessages,
authPath: this.authPath,