Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): remove stored messages when a chat is cleared or deleted

Yudhi Armyndharis774cc67e508c
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 36dcc9395..a7d49a42a 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -1025,6 +1025,8 @@ Delete every message in a chat, keeping the chat itself in the list.
{ "success": true }
```
+On success the gateway also removes its stored copies of the chat's messages (rows, inline and archived media, search entries) and emits `message:deleted` for each. Changes made on the phone are not mirrored.
+
> **`success: false` is a real outcome**, as with `chats/archive`: an unknown chat on
> whatsapp-web.js, or on Baileys a chat with no known history — the clear is an app-state
> modification keyed to the chat's last message.
@@ -1194,6 +1196,8 @@ Delete a chat from the chat list (e.g. a group you have left).
Returns HTTP `200`, matching the OpenAPI contract.
+On success the gateway also removes its stored copies of the chat's messages (rows, inline and archived media, search entries) and emits `message:deleted` for each. Changes made on the phone are not mirrored.
+
**Errors:** `400` validation, or session not started · `401` · `403` · `404` session not found · `409` the session is not connected (engine exists but is not `ready`) · `503` WhatsApp did not answer within the request budget, or the engine’s browser page died — the change may or may not have been applied
#### POST /api/sessions/:sessionId/chats/typing
diff --git a/docs/27-plugin-search-providers.md b/docs/27-plugin-search-providers.md
index 6c4ec289b..9529d03c0 100644
--- a/docs/27-plugin-search-providers.md
+++ b/docs/27-plugin-search-providers.md
@@ -115,6 +115,10 @@ ctx.registerHook('message:deleted', async hookCtx => {
});
```
+Clearing a chat's messages (`DELETE /api/sessions/:sessionId/chats/:chatId/messages`) or deleting a chat
+(`POST /api/sessions/:sessionId/chats/delete`) also emits `message:deleted` for every stored row it removes, so
+the same handler keeps your index in step.
+
**Backfill is the plugin's responsibility.** The hook fires only for live traffic. A plugin installed on
a deployment with existing message history must perform its own one-time backfill (read the `messages`
table via `ctx.engine.getChatHistory` or a direct query, and index) at `onEnable`. The built-in DB-FTS
diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.ts
index d35aaa16a..6a976605a 100644
--- a/src/modules/session/session.controller.ts
+++ b/src/modules/session/session.controller.ts
@@ -691,7 +691,12 @@ export class SessionController {
@Delete(':sessionId/chats/:chatId/messages')
@RequireRole(ApiKeyRole.OPERATOR)
@HttpCode(HttpStatus.OK)
- @ApiOperation({ summary: 'Delete every message in a chat, keeping the chat itself' })
+ @ApiOperation({
+ summary: 'Delete every message in a chat, keeping the chat itself',
+ description:
+ "On success the gateway also removes its stored copies of the chat's messages (rows, inline and archived " +
+ 'media, search entries) and emits `message:deleted` for each. Changes made on the phone are not mirrored.',
+ })
@ApiParam({ name: 'sessionId', description: 'Session ID' })
@ApiParam({ name: 'chatId', description: "Chat JID, e.g. [email protected] (URL-encode the '@')" })
@ApiResponse({
@@ -824,7 +829,12 @@ export class SessionController {
@Post(':sessionId/chats/delete')
@RequireRole(ApiKeyRole.OPERATOR)
@HttpCode(HttpStatus.OK)
- @ApiOperation({ summary: 'Delete a chat from the chat list (e.g. a group you have left)' })
+ @ApiOperation({
+ summary: 'Delete a chat from the chat list (e.g. a group you have left)',
+ description:
+ "On success the gateway also removes its stored copies of the chat's messages (rows, inline and archived " +
+ 'media, search entries) and emits `message:deleted` for each. Changes made on the phone are not mirrored.',
+ })
@ApiParam({ name: 'sessionId', description: 'Session ID' })
@ApiResponse({ status: 200, description: 'Chat deleted successfully', 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 2937e3e02..b009f17d1 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -3,7 +3,7 @@ import { SessionRestrictionStore } from './session-restriction-store.service';
import { PresenceStore } from './presence-store.service';
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken, getDataSourceToken } from '@nestjs/typeorm';
-import { Repository, DataSource, In, IsNull, Not, QueryFailedError } from 'typeorm';
+import { Repository, DataSource, In, IsNull, LessThanOrEqual, Not, QueryFailedError } from 'typeorm';
import {
NotFoundException,
ConflictException,
@@ -181,6 +181,7 @@ describe('SessionService', () => {
sendSeen: jest.fn().mockResolvedValue(true),
markUnread: jest.fn().mockResolvedValue(true),
deleteChat: jest.fn().mockResolvedValue(true),
+ clearChatMessages: jest.fn().mockResolvedValue(true),
sendChatState: jest.fn().mockResolvedValue(undefined),
setOnlinePresence: jest.fn().mockResolvedValue(undefined),
resolveContactPhone: jest.fn().mockResolvedValue('628111222333'),
@@ -237,6 +238,8 @@ describe('SessionService', () => {
remember: jest.fn().mockResolvedValue(undefined),
getCached: jest.fn().mockReturnValue(undefined),
lidsForPhone: jest.fn().mockReturnValue([]),
+ findPhoneForLid: jest.fn().mockResolvedValue(null),
+ findLidsForPhone: jest.fn().mockResolvedValue([]),
};
statusStore = {
@@ -7211,6 +7214,162 @@ describe('SessionService', () => {
});
});
+ // ── stored copies of a cleared or deleted chat ────────────────────
+
+ describe('clearChatMessages / deleteChat: stored message removal', () => {
+ const rows = (n: number, from = 0) =>
+ Array.from({ length: n }, (_, i) => ({
+ id: `row-${from + i}`,
+ waMessageId: `wa-${from + i}`,
+ chatId: '[email protected]',
+ sessionId: 'sess-uuid-1',
+ }));
+ const deletedHooks = (): unknown[][] =>
+ ((hookManager.execute as jest.Mock).mock.calls as unknown[][]).filter(([e]) => e === 'message:deleted');
+
+ beforeEach(async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ messageRepository.delete = jest.fn().mockResolvedValue({ affected: 1 });
+ await service.start('sess-uuid-1');
+ (hookManager.execute as jest.Mock).mockClear();
+ });
+
+ it.each([
+ ['clearChatMessages', (id: string, chat: string) => service.clearChatMessages(id, chat)],
+ ['deleteChat', (id: string, chat: string) => service.deleteChat(id, chat)],
+ ] as const)('%s removes the rows of every id form of the chat and emits message:deleted', async (_, run) => {
+ (lidMappingStore.findLidsForPhone as jest.Mock).mockResolvedValue(['999']);
+ (messageRepository.find as jest.Mock).mockResolvedValueOnce(rows(2));
+
+ await expect(run('sess-uuid-1', '[email protected]')).resolves.toBe(true);
+
+ const [[{ where }]] = (messageRepository.find as jest.Mock).mock.calls as [[{ where: Record<string, unknown> }]];
+ expect(where).toEqual({
+ sessionId: 'sess-uuid-1',
+ chatId: In(['[email protected]', '[email protected]', '999@lid']),
+ createdAt: LessThanOrEqual(expect.any(Date)),
+ });
+ expect(messageRepository.delete).toHaveBeenCalledWith({ id: In(['row-0', 'row-1']) });
+ expect(deletedHooks()).toEqual([
+ ['message:deleted', { sessionId: 'sess-uuid-1', message: rows(1)[0] }, expect.anything()],
+ ['message:deleted', { sessionId: 'sess-uuid-1', message: rows(1, 1)[0] }, expect.anything()],
+ ]);
+ });
+
+ it('a group chat removes only its literal id', async () => {
+ await service.clearChatMessages('sess-uuid-1', '[email protected]');
+
+ const [[{ where }]] = (messageRepository.find as jest.Mock).mock.calls as [[{ where: Record<string, unknown> }]];
+ expect(where).toMatchObject({ sessionId: 'sess-uuid-1', chatId: In(['[email protected]']) });
+ expect(lidMappingStore.findLidsForPhone).not.toHaveBeenCalled();
+ });
+
+ // A busy chat keeps storing messages while the batches run. Those arrived after the clear and
+ // still exist on WhatsApp, so every batch is bounded by a cutoff taken before the engine call.
+ it.each([
+ ['clearChatMessages', 'clearChatMessages', (id: string, chat: string) => service.clearChatMessages(id, chat)],
+ ['deleteChat', 'deleteChat', (id: string, chat: string) => service.deleteChat(id, chat)],
+ ] as const)('%s keeps messages stored after the engine call', async (_, method, run) => {
+ let engineCalledAt = 0;
+ mockEngine[method].mockImplementationOnce(async () => {
+ engineCalledAt = Date.now();
+ await new Promise(resolve => setTimeout(resolve, 5));
+ return true;
+ });
+ (messageRepository.find as jest.Mock).mockResolvedValueOnce(rows(500)).mockResolvedValueOnce(rows(3, 500));
+
+ await run('sess-uuid-1', '[email protected]');
+
+ const calls = (messageRepository.find as jest.Mock).mock.calls as [{ where: { createdAt: unknown } }][];
+ expect(calls).toHaveLength(2);
+ const bounds = calls.map(([{ where }]) => where.createdAt as { value: Date });
+ for (const bound of bounds) {
+ expect(bound).toEqual(LessThanOrEqual(expect.any(Date)));
+ expect(bound.value.getTime()).toBeLessThanOrEqual(engineCalledAt);
+ }
+ expect(bounds[1].value).toBe(bounds[0].value);
+ });
+
+ // SQLite stores createdAt as whole seconds and compares it as text against the bound parameter,
+ // so a millisecond cutoff would also match a row stored later in the cutoff's own second.
+ 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);
+ });
+
+ afterAll(async () => {
+ await db.destroy();
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ it("keeps a row stored in the cutoff's own second and removes the ones before it", async () => {
+ const seed = async (waMessageId: string, createdAt: string): Promise<void> => {
+ await messages.insert({ sessionId: 'sess-uuid-1', chatId: '[email protected]', from: 'a', to: 'b', waMessageId });
+ await messages.update({ waMessageId }, { createdAt: () => `'${createdAt}'` });
+ };
+ await seed('before', '2026-09-29 13:39:00');
+ Object.assign(service as unknown as Record<string, unknown>, { messageRepository: messages });
+ // Only the clock is frozen, so the cutoff lands mid-second; the driver still needs real timers.
+ jest.useFakeTimers({
+ now: Date.parse('2026-09-29T13:39:01.500Z'),
+ doNotFake: ['nextTick', 'queueMicrotask', 'setImmediate', 'clearImmediate', 'setTimeout', 'clearTimeout'],
+ });
+ mockEngine.clearChatMessages.mockImplementationOnce(async () => {
+ await seed('after', '2026-09-29 13:39:01');
+ return true;
+ });
+
+ await expect(service.clearChatMessages('sess-uuid-1', '[email protected]')).resolves.toBe(true);
+
+ expect((await messages.find()).map(row => row.waMessageId)).toEqual(['after']);
+ });
+ });
+
+ it('removes in batches until a short one', async () => {
+ (messageRepository.find as jest.Mock).mockResolvedValueOnce(rows(500)).mockResolvedValueOnce(rows(3, 500));
+
+ await service.deleteChat('sess-uuid-1', '[email protected]');
+
+ expect(messageRepository.find).toHaveBeenCalledTimes(2);
+ expect(messageRepository.delete).toHaveBeenCalledTimes(2);
+ expect(deletedHooks()).toHaveLength(503);
+ });
+
+ it('keeps the stored rows when the engine declines or fails', async () => {
+ mockEngine.clearChatMessages.mockResolvedValueOnce(false);
+ await expect(service.clearChatMessages('sess-uuid-1', '[email protected]')).resolves.toBe(false);
+
+ mockEngine.deleteChat.mockRejectedValueOnce(new Error('timed out'));
+ await expect(service.deleteChat('sess-uuid-1', '[email protected]')).rejects.toThrow('timed out');
+
+ expect(messageRepository.find).not.toHaveBeenCalled();
+ expect(messageRepository.delete).not.toHaveBeenCalled();
+ expect(deletedHooks()).toHaveLength(0);
+ });
+
+ it('a failed removal after the engine succeeded is logged and the call still succeeds', async () => {
+ (messageRepository.find as jest.Mock).mockRejectedValueOnce(new Error('db down'));
+ const logError = jest.spyOn((service as unknown as { logger: { error: jest.Mock } }).logger, 'error');
+
+ await expect(service.clearChatMessages('sess-uuid-1', '[email protected]')).resolves.toBe(true);
+
+ expect(logError).toHaveBeenCalledWith(
+ expect.any(String),
+ 'db down',
+ expect.objectContaining({ action: 'chat_local_purge_failed' }),
+ );
+ });
+ });
+
// ── sendChatState (typing/recording/paused) ───────────────────────
describe('sendChatState', () => {
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 7d121cf24..bee147319 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -12,7 +12,17 @@ import {
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { InjectRepository, InjectDataSource } from '@nestjs/typeorm';
-import { Repository, In, Not, IsNull, LessThan, DataSource, FindManyOptions, FindOptionsWhere } from 'typeorm';
+import {
+ Repository,
+ In,
+ Not,
+ IsNull,
+ LessThan,
+ LessThanOrEqual,
+ DataSource,
+ FindManyOptions,
+ FindOptionsWhere,
+} from 'typeorm';
import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
import { setTimeout } from 'node:timers/promises';
import { EngineTransportError } from '../../common/errors/engine-transport.error';
@@ -39,6 +49,9 @@ import { resolveFeatureFlags } from '../../config/feature-flags';
import { IWhatsAppEngine, ChatSummary, ChatState } from '../../engine/interfaces/whatsapp-engine.interface';
import { createLogger } from '../../common/services/logger.service';
import { HookManager } from '../../core/hooks';
+import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
+import { resolveJidCandidates } from '../../engine/identity/jid-candidates';
+import { Message } from '../message/entities/message.entity';
import { SessionStoppedException } from './session-engine-controls';
// Type-only: the module binds this class to PLUGIN_SESSION_PORT with a `useExisting` alias, which
// TypeScript does not check, so `implements` is what keeps the two in step.
@@ -133,6 +146,8 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
constructor(
@InjectRepository(Session, 'data')
private readonly sessionRepository: Repository<Session>,
+ @InjectRepository(Message, 'data')
+ private readonly messageRepository: Repository<Message>,
@InjectDataSource('data')
private readonly dataSource: DataSource,
private readonly engineRegistry: EngineRegistry,
@@ -142,6 +157,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
private readonly presence: PresenceStore,
private readonly hookManager: HookManager,
private readonly engineLifecycle: SessionEngineLifecycle,
+ private readonly lidMappingStore: LidMappingStoreService,
@Optional()
private readonly configService?: ConfigService,
// Trailing @Optional, like configService: the running app always provides it, while the
@@ -857,12 +873,16 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
/**
* 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 known history to key the change to.
+ * On success the gateway's stored copies of the chat's messages are removed too.
*/
async clearChatMessages(id: string, chatId: string): Promise<boolean> {
await this.findOne(id); // Verify session exists
const engine = this.requireEngine(id);
- return engine.clearChatMessages(chatId);
+ const cutoff = new Date();
+ const ok = await engine.clearChatMessages(chatId);
+ if (ok) await this.purgeStoredChat(id, chatId, cutoff);
+ return ok;
}
/**
@@ -900,11 +920,61 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
return engine.pinChat(chatId, pin);
}
+ /** Delete a chat. On success the gateway's stored copies of its messages are removed too. */
async deleteChat(id: string, chatId: string): Promise<boolean> {
await this.findOne(id); // Verify session exists
const engine = this.requireEngine(id);
- return engine.deleteChat(chatId);
+ const cutoff = new Date();
+ const ok = await engine.deleteChat(chatId);
+ if (ok) await this.purgeStoredChat(id, chatId, cutoff);
+ return ok;
+ }
+
+ /**
+ * Remove the stored rows of a chat the engine just cleared or deleted, under every id form of the
+ * same chat (the GET messages filter's rules), and emit `message:deleted` per row so search
+ * providers drop them. The FTS index follows through its delete trigger, archived media through
+ * the orphan sweep. Runs only after the engine succeeded; a failure here is logged, not thrown:
+ * WhatsApp already applied the change, and repeating the call finishes the purge.
+ *
+ * Only rows stored before the second `cutoff` (taken before the engine call) falls in go: a busy
+ * chat keeps receiving messages while the batches run, and those arrived after the clear and still
+ * exist on WhatsApp. The bound stops short of that second because SQLite stores createdAt as whole
+ * seconds and compares it as text against a millisecond parameter, so a row stored later in the
+ * same second would match. A pre-clear row from that second stays until a repeat call.
+ */
+ private async purgeStoredChat(sessionId: string, chatId: string, cutoff: Date): Promise<void> {
+ const BATCH = 500;
+ const bound = new Date(Math.floor(cutoff.getTime() / 1000) * 1000 - 1);
+ try {
+ const expanded = await resolveJidCandidates(chatId, {
+ resolveLid: lid => this.lidMappingStore.findPhoneForLid(lid),
+ lidsForPhone: phone => this.lidMappingStore.findLidsForPhone(phone),
+ });
+ const chatIds = [...new Set([chatId, ...expanded])];
+ for (;;) {
+ const rows = await this.messageRepository.find({
+ where: { sessionId, chatId: In(chatIds), createdAt: LessThanOrEqual(bound) },
+ select: { id: true, waMessageId: true, chatId: true, sessionId: true },
+ take: BATCH,
+ });
+ if (rows.length === 0) return;
+ await this.messageRepository.delete({ id: In(rows.map(row => row.id)) });
+ for (const message of rows) {
+ void this.hookManager
+ .execute('message:deleted', { sessionId, message }, { sessionId, source: 'SessionService' })
+ .catch(() => undefined);
+ }
+ if (rows.length < BATCH) return;
+ }
+ } catch (error) {
+ this.logger.error(
+ 'Failed to remove stored messages of a cleared chat',
+ error instanceof Error ? error.message : String(error),
+ { sessionId, action: 'chat_local_purge_failed' },
+ );
+ }
}
async sendChatState(id: string, chatId: string, state: ChatState): Promise<void> {