Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(chats): clear a chat's messages without deleting the chat

Yudhi Armyndharis4eccf25487af
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c53d9396d..84be638ad 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **A chat's messages can be cleared without deleting the chat:**
+ `DELETE /api/sessions/:id/chats/:chatId/messages`. Available in all five SDKs as
+ `chats.clearMessages`. Like `chats/archive`, `success: false` is a defined outcome — an unknown
+ chat on whatsapp-web.js, or on Baileys a chat with no known history to key the change to.
+
- **Chats can be archived and unarchived:** `POST /api/sessions/:id/chats/archive` with
`{ chatId, archive }`, alongside the existing read/unread/delete chat operations. Available in all
five SDKs as `chats.archive`.
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index e2e08f3a2..6fd9ac216 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -712,6 +712,31 @@ Returns HTTP `200`, matching the OpenAPI contract.
**Errors:** `400` validation, or session not started · `401` · `403` · `404` session not found
+#### DELETE /api/sessions/:id/chats/:chatId/messages
+
+Delete every message in a chat, keeping the chat itself in the list.
+
+**Auth:** API key (OPERATOR) · **Scope:** session-scoped
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| `id` | string | Session UUID |
+| `chatId` | string | Engine-native JID, e.g. `[email protected]`. URL-encode it if your client does not. |
+
+**Response** `200`
+
+```json
+{ "success": true }
+```
+
+> **`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.
+
+**Errors:** `400` session not ready · `401` missing/invalid API key · `404` session not found
+
#### POST /api/sessions/:id/chats/archive
Archive or unarchive a chat.
diff --git a/docs/07-api-collection.md b/docs/07-api-collection.md
index b3d2d9f1f..f2ae59977 100644
--- a/docs/07-api-collection.md
+++ b/docs/07-api-collection.md
@@ -193,6 +193,15 @@ curl -X POST "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/chats/unre
-d '{ "chatId": "[email protected]" }'
```
+#### DELETE /api/sessions/:id/chats/:chatId/messages
+
+Delete every message in a chat, keeping the chat.
+
+```bash
+curl -X DELETE "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/chats/[email protected]/messages" \
+ -H "X-API-Key: $API_KEY"
+```
+
#### POST /api/sessions/:id/chats/archive
Archive or unarchive a chat.
diff --git a/docs/18-sdk-design.md b/docs/18-sdk-design.md
index 91427b1d7..abb672920 100644
--- a/docs/18-sdk-design.md
+++ b/docs/18-sdk-design.md
@@ -33,7 +33,7 @@ All five SDKs expose the same fluent surface:
| `contacts` | list, get, check, profilePicture, profilePictures, phone, block, unblock |
| `groups` | list, get, create, joinGroup, add/remove/promote/demoteParticipants, setSubject, setDescription, getGroupSettings, updateGroupSettings, leave, inviteCode, revokeInviteCode |
| `webhooks` | list, get, create, update, delete, test |
-| `chats` | list, markRead, markUnread, archive, delete, sendState |
+| `chats` | list, markRead, markUnread, archive, clearMessages, delete, sendState |
| `labels` | list, get, forChat, addToChat, removeFromChat *(WhatsApp Business)* |
| `channels` | list, get, messages, subscribe, unsubscribe *(Newsletters)* |
| `catalog` | info, products, product, sendProduct, sendCatalog *(WhatsApp Business)* |
diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.md
index e994dd3fa..02f1c8843 100644
--- a/docs/29-engine-capability-matrix.md
+++ b/docs/29-engine-capability-matrix.md
@@ -168,8 +168,8 @@ These are hand-maintained and had drifted from the source before this pass; they
from `engine-capability-matrix.ts` rather than adjusted by hand. Re-derive them the same way when
adding a method, instead of incrementing the previous figure.
-- **84** interface methods, **168** adapter-cells (84 × 2 engines).
-- **151** supported cells; **17** not-available cells across **16** methods.
+- **85** interface methods, **170** adapter-cells (85 × 2 engines).
+- **153** supported cells; **17** not-available cells across **16** methods.
- Of the 17 not-available cells: **2 adapter-gaps** (fixable) + **15 library-limitations** + **0 uncertain**.
- **0 phantom-support rows** — every `not-available` row throws at the adapter boundary.
diff --git a/openapi.json b/openapi.json
index c3dd4a042..5dc68f7b7 100644
--- a/openapi.json
+++ b/openapi.json
@@ -905,6 +905,46 @@
]
}
},
+ "/api/sessions/{id}/chats/{chatId}/messages": {
+ "delete": {
+ "operationId": "SessionController_clearChatMessages",
+ "parameters": [
+ {
+ "name": "id",
+ "required": true,
+ "in": "path",
+ "description": "Session ID",
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "chatId",
+ "required": true,
+ "in": "path",
+ "description": "Chat JID, e.g. [email protected] (URL-encode the '@')",
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Returns `{ success }`. `false` means the engine declined to act — an unknown chat, or on the Baileys engine a chat with no known history, since the change is keyed to its last message."
+ },
+ "400": {
+ "description": "Session not ready"
+ },
+ "404": {
+ "description": "Session not found"
+ }
+ },
+ "summary": "Delete every message in a chat, keeping the chat itself",
+ "tags": [
+ "sessions"
+ ]
+ }
+ },
"/api/sessions/{id}/chats/archive": {
"post": {
"operationId": "SessionController_archiveChat",
diff --git a/sdk/README.md b/sdk/README.md
index 48a759552..b15873206 100644
--- a/sdk/README.md
+++ b/sdk/README.md
@@ -29,7 +29,7 @@ All five SDKs expose the same fluent resource surface:
| `contacts` | list, get, check, profilePicture, profilePictures, phone, block, unblock |
| `groups` | list, get, create, joinGroup, add/remove/promote/demoteParticipants, setSubject, setDescription, get/updateGroupSettings, leave, inviteCode, revokeInviteCode |
| `webhooks` | list, get, create, update, delete, test |
-| `chats` | list, markRead, markUnread, archive, delete, sendState |
+| `chats` | list, markRead, markUnread, archive, clearMessages, delete, sendState |
| `labels` | list, get, forChat, addToChat, removeFromChat _(WhatsApp Business)_ |
| `channels` | list, get, messages, subscribe, unsubscribe _(Newsletters)_ |
| `catalog` | info, products, product, sendProduct, sendCatalog _(WhatsApp Business)_ |
diff --git a/sdk/go/chats.go b/sdk/go/chats.go
index 28cb6bdf7..dbaec170b 100644
--- a/sdk/go/chats.go
+++ b/sdk/go/chats.go
@@ -38,6 +38,18 @@ func (s *ChatsService) Archive(ctx context.Context, sessionID string, body Archi
return s.post(ctx, sessionID, "/archive", body)
}
+// ClearMessages deletes every message in a chat, keeping the chat itself. A
+// false Success means the engine declined — an unknown chat, or on Baileys a
+// chat with no known history.
+func (s *ChatsService) ClearMessages(ctx context.Context, sessionID, chatID string) (*SuccessResult, error) {
+ var out SuccessResult
+ path := s.base(sessionID) + "/" + pathEscape(chatID) + "/messages"
+ if err := s.client.do(ctx, "DELETE", path, nil, nil, &out); err != nil {
+ return nil, err
+ }
+ return &out, nil
+}
+
// SendState sends a typing/recording/paused state.
func (s *ChatsService) SendState(ctx context.Context, sessionID string, body SendChatStateRequest) (*SuccessResult, error) {
return s.post(ctx, sessionID, "/typing", body)
diff --git a/sdk/go/routing_test.go b/sdk/go/routing_test.go
index ac6fa61e1..9d74c4203 100644
--- a/sdk/go/routing_test.go
+++ b/sdk/go/routing_test.go
@@ -86,6 +86,7 @@ func TestRouting(t *testing.T) {
{"Chats.List", func(c *Client) { c.Chats.List(ctx, "s1", nil) }, "GET", "/api/sessions/s1/chats"},
{"Chats.MarkRead", func(c *Client) { c.Chats.MarkRead(ctx, "s1", MarkChatRequest{}) }, "POST", "/api/sessions/s1/chats/read"},
{"Chats.MarkUnread", func(c *Client) { c.Chats.MarkUnread(ctx, "s1", MarkChatRequest{}) }, "POST", "/api/sessions/s1/chats/unread"},
+ {"Chats.ClearMessages", func(c *Client) { c.Chats.ClearMessages(ctx, "s1", "c1") }, "DELETE", "/api/sessions/s1/chats/c1/messages"},
{"Chats.Archive", func(c *Client) { c.Chats.Archive(ctx, "s1", ArchiveChatRequest{}) }, "POST", "/api/sessions/s1/chats/archive"},
{"Chats.Delete", func(c *Client) { c.Chats.Delete(ctx, "s1", DeleteChatRequest{}) }, "POST", "/api/sessions/s1/chats/delete"},
{"Chats.SendState", func(c *Client) { c.Chats.SendState(ctx, "s1", SendChatStateRequest{}) }, "POST", "/api/sessions/s1/chats/typing"},
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/ChatsResource.java b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/ChatsResource.java
index e285e07c5..df435f8a9 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/ChatsResource.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/ChatsResource.java
@@ -50,6 +50,16 @@ public final class ChatsResource {
HttpMethod.POST, "/api/sessions/" + encodeSegment(sessionId) + "/chats/unread", null, body, SuccessResult.class);
}
+ /** Delete every message in a chat, keeping the chat itself. */
+ public SuccessResult clearMessages(String sessionId, String chatId) {
+ return client.request(
+ HttpMethod.DELETE,
+ "/api/sessions/" + encodeSegment(sessionId) + "/chats/" + encodeSegment(chatId) + "/messages",
+ null,
+ null,
+ SuccessResult.class);
+ }
+
/**
* Archive or unarchive a chat. A false success means the engine declined — on Baileys a chat
* with no known history cannot be archived.
diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/ChatsResourceTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/ChatsResourceTest.java
index d5da91bcd..86d5df896 100644
--- a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/ChatsResourceTest.java
+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/ChatsResourceTest.java
@@ -61,6 +61,14 @@ class ChatsResourceTest {
assertTrue(tx.lastRequest().body().contains("[email protected]"));
}
+ @Test
+ void clearMessagesDeletesTheSubResource() {
+ tx.respond(200, "{\"success\":true}");
+ client.chats.clearMessages("s", "[email protected]");
+ assertEquals("http://h/api/sessions/s/chats/[email protected]/messages", tx.lastRequest().url());
+ assertEquals(HttpMethod.DELETE, tx.lastRequest().method());
+ }
+
@Test
void archiveSendsBody() {
tx.respond(200, "{\"success\":true}");
diff --git a/sdk/javascript/src/resources/chats.ts b/sdk/javascript/src/resources/chats.ts
index 8c4948479..fbd49f0a3 100644
--- a/sdk/javascript/src/resources/chats.ts
+++ b/sdk/javascript/src/resources/chats.ts
@@ -66,6 +66,17 @@ export class ChatsResource {
});
}
+ /**
+ * Delete every message in a chat, keeping the chat itself. `success: false` means the engine
+ * declined — an unknown chat, or on Baileys a chat with no known history.
+ */
+ clearMessages(sessionId: string, chatId: string): Promise<SuccessResult> {
+ return this.client.request<SuccessResult>({
+ method: 'DELETE',
+ path: `/api/sessions/${encodeSegment(sessionId)}/chats/${encodeSegment(chatId)}/messages`,
+ });
+ }
+
/** Delete a chat from the chat list. */
delete(sessionId: string, body: DeleteChatRequest): Promise<SuccessResult> {
return this.client.request<SuccessResult>({
diff --git a/sdk/javascript/test/resources.test.ts b/sdk/javascript/test/resources.test.ts
index dcaead26d..725487d20 100644
--- a/sdk/javascript/test/resources.test.ts
+++ b/sdk/javascript/test/resources.test.ts
@@ -272,6 +272,15 @@ describe('ChatsResource — exact paths', () => {
});
});
+describe('ChatsResource.clearMessages', () => {
+ it('DELETEs the chat messages sub-resource', async () => {
+ const t = new MockTransport().on('DELETE', /\/chats\/.+\/messages$/, { body: { success: true } });
+ await client(t).chats.clearMessages('s', '[email protected]');
+ expect(t.lastCall!.method).toBe('DELETE');
+ expect(t.lastCall!.url).toBe('http://x/api/sessions/s/chats/[email protected]/messages');
+ });
+});
+
describe('ChatsResource.archive', () => {
it('posts chatId and the archive flag', async () => {
const t = new MockTransport().on('POST', /\/chats\/archive$/, { body: { success: true } });
diff --git a/sdk/php/src/Resources/ChatsResource.php b/sdk/php/src/Resources/ChatsResource.php
index 1ce46f4fa..cc6250716 100644
--- a/sdk/php/src/Resources/ChatsResource.php
+++ b/sdk/php/src/Resources/ChatsResource.php
@@ -45,6 +45,16 @@ class ChatsResource
return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/chats/unread", [], $body);
}
+ /**
+ * Delete every message in a chat, keeping the chat itself.
+ *
+ * @return array<string,mixed>
+ */
+ public function clearMessages(string $sessionId, string $chatId): array
+ {
+ return $this->http->request('DELETE', "/api/sessions/{$this->http->encodeSegment($sessionId)}/chats/{$this->http->encodeSegment($chatId)}/messages") ?? [];
+ }
+
/**
* Archive or unarchive a chat. A false `success` means the engine declined — on Baileys a chat
* with no known history cannot be archived.
diff --git a/sdk/php/tests/ResourcesTest.php b/sdk/php/tests/ResourcesTest.php
index bc18ff3c0..8de131ea6 100644
--- a/sdk/php/tests/ResourcesTest.php
+++ b/sdk/php/tests/ResourcesTest.php
@@ -238,6 +238,16 @@ class ResourcesTest extends TestCase
$this->assertStringContainsString('/chats/typing', $backend->calls()[4]['url']);
}
+ public function testChatsClearMessages(): void
+ {
+ $backend = new MockBackend();
+ $backend->on(200, ['success' => true]);
+ $client = $backend->makeClient();
+ $client->chats->clearMessages('s', '[email protected]');
+ $this->assertSame('DELETE', $backend->lastCall()['method']);
+ $this->assertSame('/api/sessions/s/chats/[email protected]/messages', $backend->lastCall()['path']);
+ }
+
public function testChatsArchive(): void
{
$backend = new MockBackend();
diff --git a/sdk/python/openwa/resources/chats.py b/sdk/python/openwa/resources/chats.py
index 102fc4c47..ecf0733b9 100644
--- a/sdk/python/openwa/resources/chats.py
+++ b/sdk/python/openwa/resources/chats.py
@@ -44,6 +44,12 @@ class ChatsResource:
"""Archive or unarchive a chat. success=False means the engine declined."""
return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/chats/archive", body=body)
+ def clear_messages(self, session_id: str, chat_id: str) -> SuccessResult:
+ """Delete every message in a chat, keeping the chat. success=False means the engine declined."""
+ return self._http.request(
+ "DELETE", f"/api/sessions/{quote_segment(session_id)}/chats/{quote_segment(chat_id)}/messages"
+ )
+
def delete(self, session_id: str, body: DeleteChatRequest) -> SuccessResult:
return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/chats/delete", body=body)
diff --git a/sdk/python/tests/test_sdk.py b/sdk/python/tests/test_sdk.py
index 907bcc0a5..49115923b 100644
--- a/sdk/python/tests/test_sdk.py
+++ b/sdk/python/tests/test_sdk.py
@@ -555,6 +555,12 @@ class TestChatsAndHealth:
client.chats.send_state("s", {"chatId": "[email protected]", "state": "typing"})
assert "/chats/typing" in backend.calls[-1].url
+ def test_chats_clear_messages(self):
+ backend = MockBackend().on("DELETE", "/messages", body={"success": True})
+ make_client(backend).chats.clear_messages("s", "[email protected]")
+ assert backend.last_call.method == "DELETE"
+ assert backend.last_call.url == "http://localhost:2785/api/sessions/s/chats/[email protected]/messages"
+
def test_chats_archive(self):
backend = MockBackend().on("POST", "/chats/archive", body={"success": True})
make_client(backend).chats.archive("s", {"chatId": "[email protected]", "archive": True})
diff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.ts
index 16faf46be..55a77bd30 100644
--- a/src/engine/adapters/baileys-contacts.ts
+++ b/src/engine/adapters/baileys-contacts.ts
@@ -122,6 +122,19 @@ export class BaileysContacts {
return true;
}
+ async clearChatMessages(chatId: string): Promise<boolean> {
+ this.host.ensureReady();
+ const last = this.host.lastMessage(chatId);
+ if (!last) {
+ return false; // Baileys' clear needs the last message; can't synthesize it
+ }
+ await this.sock().chatModify(
+ { clear: true, lastMessages: [{ key: last.key, messageTimestamp: last.timestamp }] },
+ chatId,
+ );
+ return true;
+ }
+
async archiveChat(chatId: string, archive: boolean): Promise<boolean> {
this.host.ensureReady();
const last = this.host.lastMessage(chatId);
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 4799c7932..0356a4849 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -3714,6 +3714,28 @@ describe('BaileysAdapter sendSeen + markUnread + deleteChat', () => {
expect(fakeSock.chatModify).not.toHaveBeenCalled();
});
+ it('clearChatMessages clears via chatModify with the last message', async () => {
+ const adapter = await readyWithMessage();
+ expect(await adapter.clearChatMessages('[email protected]')).toBe(true);
+ expect(fakeSock.chatModify).toHaveBeenCalledWith(
+ {
+ clear: true,
+ lastMessages: [
+ { key: { remoteJid: '[email protected]', fromMe: false, id: 'M1' }, messageTimestamp: 1700000020 },
+ ],
+ },
+ );
+ });
+
+ it('clearChatMessages returns false for a chat with no known history', async () => {
+ const adapter = newAdapter();
+ await adapter.initialize({});
+ fakeSock.fire('connection.update', { connection: 'open' });
+ expect(await adapter.clearChatMessages('[email protected]')).toBe(false);
+ expect(fakeSock.chatModify).not.toHaveBeenCalled();
+ });
+
it.each([true, false])('archiveChat(%s) modifies the chat with the last message', async archive => {
const adapter = await readyWithMessage();
const ok = await adapter.archiveChat('[email protected]', archive);
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index aa25a84bf..c9e09064b 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -480,6 +480,10 @@ export class BaileysAdapter implements IWhatsAppEngine {
return this.contacts.archiveChat(chatId, archive);
}
+ async clearChatMessages(chatId: string): Promise<boolean> {
+ return this.contacts.clearChatMessages(chatId);
+ }
+
// ----- Gated: not supported by this minimal slice (no store) -----
/* eslint-disable @typescript-eslint/no-unused-vars */
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index 86c62bfe5..65565670d 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -744,6 +744,25 @@ describe('WhatsAppWebJsAdapter channel-JID guard (#554 — wwebjs Channel lacks
});
});
+ describe('clearChatMessages', () => {
+ it('clears via Chat.clearMessages and returns its result', async () => {
+ const clearMessages = jest.fn().mockResolvedValue(true);
+ const getChatById = jest.fn().mockResolvedValue({ clearMessages });
+ await expect(readyAdapter({ getChatById }).clearChatMessages(USER)).resolves.toBe(true);
+ expect(clearMessages).toHaveBeenCalled();
+ });
+
+ it('returns false for an unknown chat (getChatById resolves undefined) instead of a TypeError', async () => {
+ const getChatById = jest.fn().mockResolvedValue(undefined);
+ await expect(readyAdapter({ getChatById }).clearChatMessages(USER)).resolves.toBe(false);
+ });
+
+ it('reports false instead of throwing when the engine call fails', async () => {
+ const getChatById = jest.fn().mockRejectedValue(new Error('Evaluation failed'));
+ await expect(readyAdapter({ getChatById }).clearChatMessages(USER)).resolves.toBe(false);
+ });
+ });
+
describe('archiveChat', () => {
it('archives via Client.archiveChat, not Chat.archive (which resolves void)', async () => {
const archiveChat = jest.fn().mockResolvedValue(true);
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index ae6a3360d..9135ac9ca 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -1577,6 +1577,10 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
return this.chats.archiveChat(chatId, archive);
}
+ clearChatMessages(chatId: string): Promise<boolean> {
+ return this.chats.clearChatMessages(chatId);
+ }
+
markUnread(chatId: string): Promise<boolean> {
return this.chats.markUnread(chatId);
}
diff --git a/src/engine/adapters/wwebjs-chats.ts b/src/engine/adapters/wwebjs-chats.ts
index 49b7864fb..dd1fab050 100644
--- a/src/engine/adapters/wwebjs-chats.ts
+++ b/src/engine/adapters/wwebjs-chats.ts
@@ -68,6 +68,20 @@ export class WwebjsChats {
}
}
+ async clearChatMessages(chatId: string): Promise<boolean> {
+ this.host.ensureReady();
+ try {
+ // An unknown chat needs no special case: getChatById resolves undefined for one, and the
+ // resulting TypeError lands in the catch below as the same `false` the injected helper
+ // returns for a chat it cannot find. Same shape as sendSeen/archiveChat above.
+ const chat = await this.client().getChatById(chatId);
+ return await chat.clearMessages();
+ } catch (error) {
+ this.host.logger.error(`Error clearing messages in chat ${chatId}`, String(error));
+ return false;
+ }
+ }
+
async archiveChat(chatId: string, archive: boolean): Promise<boolean> {
this.host.ensureReady();
try {
diff --git a/src/engine/engine-capability-matrix.ts b/src/engine/engine-capability-matrix.ts
index 5e05eb03a..451aa6f50 100644
--- a/src/engine/engine-capability-matrix.ts
+++ b/src/engine/engine-capability-matrix.ts
@@ -70,6 +70,12 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {
},
blockContact: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
checkNumberExists: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
+ clearChatMessages: {
+ wwjs: { status: 'supported' },
+ baileys: { status: 'supported' },
+ evidence:
+ 'wwjs Chat.clearMessages() → boolean (index.d.ts:1896); the injected sendClearChat returns false for an unknown chat (Injected/Utils.js:1192-1199); baileys chatModify({clear:true,lastMessages}, jid) (Types/Chat.d.ts:75-78) — same last-message requirement as archiveChat, so a chat with no known history resolves false',
+ },
createGroup: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
deleteChat: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
deleteMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index 463ae847d..6ed0c6cec 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -786,6 +786,12 @@ export interface IWhatsAppEngine {
* history cannot be archived at all. Same shape as deleteChat/markUnread, which share that limit.
*/
archiveChat(chatId: string, archive: boolean): Promise<boolean>;
+ /**
+ * Delete every message in a chat while keeping the chat itself in the list. Resolves false when
+ * the engine cannot act — an unknown chat on whatsapp-web.js, or (as with archiveChat) a chat
+ * with no known history on Baileys, whose clear is keyed to the last message.
+ */
+ clearChatMessages(chatId: string): Promise<boolean>;
/**
* Send a typing/recording presence indicator to a chat, or clear it (`paused`).
* Engine-agnostic and best-effort: engines without a presence concept should no-op.
diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.ts
index 8b5a60e05..11aad87e4 100644
--- a/src/modules/session/session.controller.ts
+++ b/src/modules/session/session.controller.ts
@@ -361,6 +361,28 @@ export class SessionController {
return { success };
}
+ @Delete(':id/chats/:chatId/messages')
+ @RequireRole(ApiKeyRole.OPERATOR)
+ @HttpCode(HttpStatus.OK)
+ @ApiOperation({ summary: 'Delete every message in a chat, keeping the chat itself' })
+ @ApiParam({ name: 'id', description: 'Session ID' })
+ @ApiParam({ name: 'chatId', description: "Chat JID, e.g. [email protected] (URL-encode the '@')" })
+ @ApiResponse({
+ status: 200,
+ description:
+ 'Returns `{ success }`. `false` means the engine declined to act — an unknown chat, or on the ' +
+ 'Baileys engine a chat with no known history, since the change is keyed to its last message.',
+ })
+ @ApiResponse({ status: 400, description: 'Session not ready' })
+ @ApiResponse({ status: 404, description: 'Session not found' })
+ async clearChatMessages(
+ @Param('id', ParseUUIDPipe) id: string,
+ @Param('chatId') chatId: string,
+ ): Promise<{ success: boolean }> {
+ const success = await this.sessionService.clearChatMessages(id, chatId);
+ return { success };
+ }
+
@Post(':id/chats/archive')
@RequireRole(ApiKeyRole.OPERATOR)
@HttpCode(HttpStatus.OK)
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 318af498e..251532261 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -356,6 +356,21 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
return engine.markUnread(chatId);
}
+ /**
+ * 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.
+ */
+ async clearChatMessages(id: string, chatId: string): Promise<boolean> {
+ await this.findOne(id); // Verify session exists
+ const engine = this.engines.get(id);
+
+ if (!engine) {
+ throw new BadRequestException('Session is not started');
+ }
+
+ return engine.clearChatMessages(chatId);
+ }
+
/**
* Archive or unarchive a chat. Resolves false when the engine could not act — on Baileys a chat
* with no known history has no last message to key the app-state modification to. That is a