Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(engine): add chat mute/unmute on both engines

Yudhi Armyndharis6dc482ac59e9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 48067f45e..129036fdf 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- `POST /sessions/:id/chats/mute` mutes a chat until an epoch-milliseconds timestamp or unmutes it with an explicit `null`, on both engines; unlike `chats/archive` it has no declined outcome, since the change is not keyed to the chat's last message.
- `engine-inventory-parity.spec.ts` fails when a `docs/29` exposure or event mark no longer matches the adapters: a symbol marked as used must appear in adapter code rather than only in a comment, and an event marked consumed must have a listener behind it.
- `docs/29-engine-capability-matrix.md` (`docs/29`) now covers all 152 Baileys socket methods, all 81 whatsapp-web.js Client methods, all 34 + 31 library events and all five install-time patches, each mapped to the interface method that uses it or marked unexposed.
- An onboarding modal the "What's new" probe does not recognise is now logged once with its heading and confirm-button labels (`onboarding_dialog_unrecognized`), so it can be covered via `WWEBJS_ONBOARDING_CONTINUE_LABELS` before WhatsApp unlinks the companion. Refs #1072.
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 24ae88e0d..d59eed1cd 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -889,6 +889,58 @@ Archive or unarchive a chat.
**Errors:** `400` session not ready · `401` missing/invalid API key · `404` session not found
+#### POST /api/sessions/:id/chats/mute
+
+Mute a chat's notifications until a given moment, or unmute it.
+
+**Auth:** API key (OPERATOR) · **Scope:** session-scoped
+
+**Path parameters**
+
+| Name | Type | Description |
+| ---- | ------ | ------------ |
+| `id` | string | Session UUID |
+
+**Request body** — `MuteChatDto`
+
+| Field | Type | Required | Constraints | Description |
+| ----------- | -------------- | -------- | ------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
+| `chatId` | string | Yes | `@IsString`; `@IsNotEmpty`; `@Matches(/^[^\s@]+@[^\s@]+$/)` (localpart@host, no whitespace) | Engine-native JID, e.g. `[email protected]` |
+| `muteUntil` | number \| null | Yes | `@IsInt`; `@Min(1)` when not `null` | Epoch **milliseconds** the mute expires at, or `null` to unmute |
+
+```json
+{ "chatId": "[email protected]", "muteUntil": 1800000000000 }
+```
+
+```json
+{ "chatId": "[email protected]", "muteUntil": null }
+```
+
+**Response** `200`
+
+```json
+{ "success": true }
+```
+
+> **`muteUntil` is required, and `null` is not the same as omitting it.** The two plausible readings
+> of a missing field — unmute, or mute forever — are opposites, so the endpoint rejects the omission
+> with a `400` instead of guessing. Send `null` to unmute. To mute indefinitely, send a far-future
+> timestamp: neither engine exposes a portable "forever" value (whatsapp-web.js uses `-1` internally,
+> Baileys has none), so the API keeps one well-defined shape.
+
+> **Milliseconds, not seconds.** This was measured against a live WhatsApp account rather than read
+> off the protocol: the app-state field is the unsuffixed `MuteAction.muteEndTimestamp` while the same
+> proto spells other millisecond fields `…Ms`, which reads as seconds and is wrong. A seconds-scale
+> value is an instant in 1970, so the mute expires the moment it is set — and the request still
+> answers `200`, because nothing in the chain rejects a timestamp in the past.
+
+> **Unlike `chats/archive`, there is no declined outcome.** The mute change is not keyed to the chat's
+> last message on either engine, so a chat with no known history mutes like any other. The response is
+> always `{ "success": true }` or an error.
+
+**Errors:** `400` session not ready, or invalid `chatId`/`muteUntil` · `401` missing/invalid API key ·
+`404` session not found · `503` WhatsApp did not confirm within the request budget
+
#### POST /api/sessions/:id/chats/delete
Delete a chat from the chat list (e.g. a group you have left).
diff --git a/docs/07-api-collection.md b/docs/07-api-collection.md
index 628f4ed7b..a338d53a3 100644
--- a/docs/07-api-collection.md
+++ b/docs/07-api-collection.md
@@ -212,6 +212,16 @@ curl -X POST "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/chats/arch
-d '{"chatId":"[email protected]","archive":true}'
```
+#### POST /api/sessions/:id/chats/mute
+
+Mute a chat until an epoch-**milliseconds** timestamp, or send `"muteUntil":null` to unmute (OPERATOR).
+
+```bash
+curl -X POST "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/chats/mute" \
+ -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
+ -d '{"chatId":"[email protected]","muteUntil":1800000000000}'
+```
+
#### POST /api/sessions/:id/chats/delete
Delete a chat from the chat list (OPERATOR).
diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.md
index a189110b4..9c6ecb11a 100644
--- a/docs/29-engine-capability-matrix.md
+++ b/docs/29-engine-capability-matrix.md
@@ -3,7 +3,7 @@
Three-way comparison of every capability: the **Baileys library** (`@whiskeysockets/baileys`
7.0.0-rc13), the **whatsapp-web.js library** (1.34.7), and what **OpenWA actually exposes** through
its adapter layer and REST API — including which "supported" cells only work because OpenWA patches
-the installed library. Coverage is total: all 105 `IWhatsAppEngine` methods (29.4), **all 152
+the installed library. Coverage is total: all 106 `IWhatsAppEngine` methods (29.4), **all 152
Baileys + 81 whatsapp-web.js library methods** (29.5), all 34 + 31 library events (29.5.4), and all
5 install-time patches (29.3). If it exists upstream or in OpenWA, it has a row here.
@@ -24,7 +24,7 @@ Statuses used in the tables:
Two complementary views:
-- **29.4 — the OpenWA contract view.** Rows are the 105 `IWhatsAppEngine` methods; use it to see
+- **29.4 — the OpenWA contract view.** Rows are the 106 `IWhatsAppEngine` methods; use it to see
what a REST caller gets per engine. Source of truth: `src/engine/engine-capability-matrix.ts`
(per-cell `evidence` strings cite the exact library `file:symbol` inspected).
- **29.5 — the full engine inventory.** Rows are **every method the installed libraries expose**,
@@ -36,14 +36,14 @@ Two complementary views:
## 29.2 Adapter architecture
OpenWA never calls a WhatsApp library directly from a controller. Every session owns one engine
-instance behind the neutral `IWhatsAppEngine` interface (105 methods +
+instance behind the neutral `IWhatsAppEngine` interface (106 methods +
`EngineEventCallbacks`), and all modules go through it:
```mermaid
flowchart LR
subgraph OpenWA["OpenWA"]
API["REST API controllers"] --> SVC["Modules / services"]
- SVC --> IF["IWhatsAppEngine - 105 methods"]
+ SVC --> IF["IWhatsAppEngine - 106 methods"]
IF --> WA["WwebjsAdapter"]
IF --> BA["BaileysAdapter"]
SVC --> STORE["OpenWA-side stores"]
@@ -156,7 +156,7 @@ Rows that are ✅ on **both** engines where one side is patch-dependent: `initia
rests on the column-wide 🔧¹ (wwjs) and 🔧⁵ (baileys) — no row runs on stock library code on both
sides.
-## 29.4 Full capability matrix — the OpenWA contract view (105 methods)
+## 29.4 Full capability matrix — the OpenWA contract view (106 methods)
Legend recap: **✅** supported · **✅🔧ⁿ** supported via OpenWA patch `🔧ⁿ` (29.3) ·
**❌ gap** adapter-gap · **❌ lib** library-limitation. Column headers carry the engine-wide
@@ -220,6 +220,7 @@ session runs; ⚠️ depends on the session engine; ❌ 501 on both.
| `clearChatMessages` | ✅ | ✅ | ✅ |
| `deleteChat` | ✅ | ✅ | ✅ |
| `markUnread` | ✅ | ✅ | ✅ |
+| `muteChat` | ✅ | ✅ | ✅ |
### 29.4.5 Contacts
@@ -334,9 +335,9 @@ answers 501.
| `subscribeToPresence` | ✅ | ❌ lib | ⚠️ baileys only |
| `rejectCall` | ✅ | ✅ | ✅ |
-**Totals:** 105 methods → 210 adapter cells: **188 ✅, 22 ❌** (2 adapter-gaps, 20
-library-limitations, 0 uncertain) across 21 methods. From the REST caller's side: **86** methods
-work on any engine (84 fully supported + 2 store-backed status reads), **9** are Baileys-only,
+**Totals:** 106 methods → 212 adapter cells: **190 ✅, 22 ❌** (2 adapter-gaps, 20
+library-limitations, 0 uncertain) across 21 methods. From the REST caller's side: **87** methods
+work on any engine (85 fully supported + 2 store-backed status reads), **9** are Baileys-only,
**9** are wwjs-only (the 2 store-backed rows excluded), **1** (`sendCatalog`) is 501 on both.
## 29.5 Full engine method inventory — every library method, mapped to OpenWA
@@ -547,7 +548,7 @@ with zero OpenWA surface. Baileys-only; whatsapp-web.js has no community API at
| --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `appPatch` | 🔩 plumbing |
| `assertSessions` | 🔩 plumbing |
-| `chatModify` | ✅ `upsertContact`, `markUnread`, `clearChatMessages`, `archiveChat`, `deleteChat`, `deleteMessage`, `starMessage` |
+| `chatModify` | ✅ `upsertContact`, `markUnread`, `clearChatMessages`, `archiveChat`, `muteChat`, `deleteChat`, `deleteMessage`, `starMessage` |
| `cleanDirtyBits` | 🔩 plumbing |
| `createParticipantNodes` | 🔩 plumbing |
| `digestKeyBundle` | 🔩 plumbing |
@@ -611,10 +612,10 @@ with zero OpenWA surface. Baileys-only; whatsapp-web.js has no community API at
| `getChatById` | ✅ `muteChannel`, `sendSeen`, `clearChatMessages`, `markUnread`, `deleteChat`, `sendChatState`, `getGroups`, `getGroupInfo`, `addParticipants`, `leaveGroup`, `setGroupSubject`, `setGroupDescription`, `getGroupInviteCode`, `revokeGroupInviteCode`, `getChatsByLabel`, `getChatLabels`, `replyToMessage`, `forwardMessage`, `reactToMessage`, `getMessageReactions`, `getChatHistory`, `deleteMessage`, `editMessage` |
| `getChats` | ✅ `getChats`, `getGroups` |
| `markChatUnread` | ❌ **not exposed** |
-| `muteChat` | ❌ **not exposed** |
+| `muteChat` | ✅ `muteChat` |
| `pinChat` | ❌ **not exposed** |
| `unarchiveChat` | ✅ `archiveChat` |
-| `unmuteChat` | ❌ **not exposed** |
+| `unmuteChat` | ✅ `muteChat` |
| `unpinChat` | ❌ **not exposed** |
**Groups** (7)
@@ -711,14 +712,13 @@ The highest-value backlog: capabilities with first-class symbols on **both** eng
new `IWhatsAppEngine` method wires both adapters at once. All cross-checked against the installed
`.d.ts` files.
-| Capability | Baileys symbol | wwjs symbol | Note |
-| -------------------------- | -------------------------------------------------------- | ----------------------------------- | --------------------------------------------------------------------- |
-| Chat mute / unmute | `chatModify({mute})` (`Types/Chat.d.ts:72`) | `muteChat` / `unmuteChat` | the adapter already drives `chatModify` for archive/clear/star/delete |
-| Chat pin / unpin | `chatModify({pin})` (`Types/Chat.d.ts:69`) | `pinChat` / `unpinChat` | chat-level pin — distinct from `pinMessage` (message-level) |
-| Create call link | `createCallLink` (`Socket/chats.d.ts:17`) | `createCallLink` (`index.d.ts:342`) | identical shape on both |
-| Delete own profile picture | `removeProfilePicture(ownJid)` (`Socket/groups.d.ts:83`) | `deleteProfilePicture` | the Baileys symbol is already wired for `deleteGroupPicture` |
-| Channel admin demote | `newsletterDemote` (`Socket/newsletter.d.ts:25`) | `demoteChannelAdmin` | pair with the ❌-exposed invite flows below |
-| Channel ownership transfer | `newsletterChangeOwner` (`Socket/newsletter.d.ts:24`) | `transferChannelOwnership` | |
+| Capability | Baileys symbol | wwjs symbol | Note |
+| -------------------------- | -------------------------------------------------------- | ----------------------------------- | ------------------------------------------------------------ |
+| Chat pin / unpin | `chatModify({pin})` (`Types/Chat.d.ts:69`) | `pinChat` / `unpinChat` | chat-level pin — distinct from `pinMessage` (message-level) |
+| Create call link | `createCallLink` (`Socket/chats.d.ts:17`) | `createCallLink` (`index.d.ts:342`) | identical shape on both |
+| Delete own profile picture | `removeProfilePicture(ownJid)` (`Socket/groups.d.ts:83`) | `deleteProfilePicture` | the Baileys symbol is already wired for `deleteGroupPicture` |
+| Channel admin demote | `newsletterDemote` (`Socket/newsletter.d.ts:25`) | `demoteChannelAdmin` | pair with the ❌-exposed invite flows below |
+| Channel ownership transfer | `newsletterChangeOwner` (`Socket/newsletter.d.ts:24`) | `transferChannelOwnership` | |
Near-misses (both libraries have the area, but the symbol sets only partially overlap — still
worth an interface method): **channel admin invites** (wwjs
@@ -856,24 +856,24 @@ adapter boundary — none silently stubs.
Recomputed from `engine-capability-matrix.ts`, `upstream-surface.snapshot.json`, and a scan of the
adapter sources — re-derive the same way when anything changes:
-- **105** interface methods → **210** adapter cells: **188 ✅** / **22 ❌** (2 adapter-gaps, 20
+- **106** interface methods → **212** adapter cells: **190 ✅** / **22 ❌** (2 adapter-gaps, 20
library-limitations, 0 uncertain), spanning **21** methods.
-- Of the 188 ✅ cells, **6 wwjs cells carry an explicit patch dependency** (4 × 🔧² status send,
+- Of the 190 ✅ cells, **6 wwjs cells carry an explicit patch dependency** (4 × 🔧² status send,
1 × 🔧³ channel link preview, 1 × 🔧⁴ ready-sync) and the whole wwjs column additionally
depends on 🔧¹, the whole Baileys column on 🔧⁵ — so every row rests on a patch on each side,
even though no row carries a row-level mark on both.
-- REST caller's view: **86** engine-neutral (84 + 2 store-backed status reads), **9** Baileys-only,
+- REST caller's view: **87** engine-neutral (85 + 2 store-backed status reads), **9** Baileys-only,
**9** wwjs-only, **1** unavailable on both (`sendCatalog`).
- Full engine inventory (29.5), split by the exposure legend rather than lumped: Baileys **152**
socket methods — 46 wired into interface methods, 5 internal wiring, 29 plumbing, **72 ❌ not
- exposed** (incl. the whole 23-method community cluster); wwjs **81** Client methods — 41 wired,
- 2 internal wiring, 1 class plumbing, **37 ❌ not exposed** (29 real capabilities + 8
+ exposed** (incl. the whole 23-method community cluster); wwjs **81** Client methods — 43 wired,
+ 2 internal wiring, 1 class plumbing, **35 ❌ not exposed** (27 real capabilities + 8
session/transport settings that are not WhatsApp capabilities). The backlog is the ❌ rows minus
those 8 settings; 🔩 plumbing is correctly never exposed.
- Events: Baileys **34** (15 consumed / 19 dropped), wwjs **31** (16 consumed / 15 dropped).
-- **6** capabilities are supported by **both** libraries and missing only in OpenWA (29.5.3) — the
- cheapest backlog: chat mute, chat pin, create-call-link, delete-own-profile-picture, channel
- admin demote, channel ownership transfer.
+- **5** capabilities are supported by **both** libraries and missing only in OpenWA (29.5.3) — the
+ cheapest backlog: chat pin, create-call-link, delete-own-profile-picture, channel admin demote,
+ channel ownership transfer. (Chat mute/unmute was the sixth; it is now wired — see `muteChat`.)
- **5** install-time patches (4 whatsapp-web.js + 1 Baileys), all exact and self-disabling.
- **0 phantom-support rows** — every `not-available` cell throws at the adapter boundary.
- Remaining adapter-gaps (fixable in this repo, ranked): **#1** `getChannelMessages` (Baileys —
diff --git a/openapi.json b/openapi.json
index b2025f48b..96256b079 100644
--- a/openapi.json
+++ b/openapi.json
@@ -1311,6 +1311,53 @@
]
}
},
+ "/api/sessions/{id}/chats/mute": {
+ "post": {
+ "operationId": "SessionController_muteChat",
+ "parameters": [
+ {
+ "name": "id",
+ "required": true,
+ "in": "path",
+ "description": "Session ID",
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/MuteChatDto"
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Returns `{ success: true }`. Unlike the archive route there is no declined outcome: the mute change is not keyed to the chat's last message on either engine, so a chat with no known history mutes like any other."
+ },
+ "400": {
+ "description": "Session not ready, or an invalid chatId / muteUntil"
+ },
+ "404": {
+ "description": "Session not found"
+ },
+ "409": {
+ "description": "The session is not connected — an engine exists for it but is not `ready`: disconnected, reconnecting, or still initializing, so the request never reached WhatsApp. Wait for `ready` and retry. A session that was never started answers `400` instead, and the session lifecycle routes answer `409` for a conflicting state rather than this. One window answers this while the session still reads `ready`: WhatsApp Web periodically reloads its own page and the engine re-injects into it — for those few seconds the answer is a `409` naming the reload; retry shortly."
+ },
+ "503": {
+ "description": "WhatsApp did not answer within the request budget. The change may or may not have been applied — the gateway stopped waiting for a confirmation that never came."
+ }
+ },
+ "summary": "Mute or unmute a chat",
+ "tags": [
+ "sessions"
+ ]
+ }
+ },
"/api/sessions/{id}/chats/delete": {
"post": {
"operationId": "SessionController_deleteChat",
@@ -9793,6 +9840,26 @@
"archive"
]
},
+ "MuteChatDto": {
+ "type": "object",
+ "properties": {
+ "chatId": {
+ "type": "string",
+ "description": "Chat ID in the active engine's native format (e.g. [email protected] on whatsapp-web.js)",
+ "example": "[email protected]"
+ },
+ "muteUntil": {
+ "type": "number",
+ "description": "Absolute epoch-MILLISECONDS timestamp at which the mute expires, or `null` to unmute now. Required — omitting it is rejected rather than guessed, because the two plausible readings (unmute vs mute forever) are opposites. To mute indefinitely, send a far-future timestamp. Milliseconds, not seconds: a seconds-scale value is an instant in 1970, so the mute expires immediately while the request still answers 200.",
+ "example": 1800000000000,
+ "nullable": true
+ }
+ },
+ "required": [
+ "chatId",
+ "muteUntil"
+ ]
+ },
"DeleteChatDto": {
"type": "object",
"properties": {
diff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.ts
index 2e5e44d2d..52d9ff95d 100644
--- a/src/engine/adapters/baileys-contacts.ts
+++ b/src/engine/adapters/baileys-contacts.ts
@@ -229,6 +229,13 @@ export class BaileysContacts {
return true;
}
+ async muteChat(chatId: string, muteUntil: number | null): Promise<void> {
+ this.host.ensureReady();
+ // Deliberately no lastMessage lookup: the `mute` member of ChatModification carries no
+ // `lastMessages`, unlike archive/clear/delete, so a chat with no known history mutes fine.
+ await this.confirmed(this.sock().chatModify({ mute: muteUntil }, this.host.toEngineJid(chatId)), 'the mute change');
+ }
+
async deleteChat(chatId: string): Promise<boolean> {
this.host.ensureReady();
const last = this.host.lastMessage(chatId);
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index f19d60f56..faede3ee4 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -549,6 +549,10 @@ export class BaileysAdapter implements IWhatsAppEngine {
return this.contacts.deleteChat(chatId);
}
+ async muteChat(chatId: string, muteUntil: number | null): Promise<void> {
+ return this.contacts.muteChat(chatId, muteUntil);
+ }
+
async archiveChat(chatId: string, archive: boolean): Promise<boolean> {
return this.contacts.archiveChat(chatId, archive);
}
diff --git a/src/engine/adapters/chat-mute.spec.ts b/src/engine/adapters/chat-mute.spec.ts
new file mode 100644
index 000000000..341e255fb
--- /dev/null
+++ b/src/engine/adapters/chat-mute.spec.ts
@@ -0,0 +1,115 @@
+import { WwebjsChats } from './wwebjs-chats';
+import { BaileysContacts, type BaileysContactsHost } from './baileys-contacts';
+import { createLogger } from '../../common/services/logger.service';
+import { type WwebjsEngineHost } from './wwebjs-host';
+import { type WwebjsMessaging } from './wwebjs-messaging';
+import { EngineTransportError } from '../../common/errors/engine-transport.error';
+import type { Client } from 'whatsapp-web.js';
+import type { WASocket } from '@whiskeysockets/baileys';
+
+/**
+ * Chat mute/unmute across both engines — the first of the §29.5.3 "supported by BOTH libraries,
+ * missing only in OpenWA" backlog.
+ *
+ * `muteUntil` is an absolute epoch-MILLISECONDS timestamp, `null` unmutes. Milliseconds is a
+ * measured fact, not a reading of the proto: `MuteAction.muteEndTimestamp` is unsuffixed while the
+ * same file spells other millisecond fields `…Ms`, which suggests seconds and is wrong. Sent live
+ * against a real Baileys session, an epoch-SECONDS value left the chat unmuted — that instant had
+ * already passed in 1970 — and the same instant in milliseconds muted it to the expected minute.
+ *
+ * The behaviour worth pinning is the one that separates mute from its neighbours: `archive`,
+ * `clear` and `delete` are app-state modifications keyed to the chat's LAST MESSAGE, so Baileys
+ * cannot apply them to a chat with no known history and those methods resolve false. The `mute`
+ * modification carries no `lastMessages` at all (Types/Chat.d.ts ChatModification union), so it has
+ * no such limit — and a test is the only thing that stops someone copying the archive body and
+ * reintroducing the guard.
+ */
+
+const logger = createLogger('chat-mute.spec');
+const MUTE_UNTIL = 1_800_000_000_000; // epoch MILLISECONDS (2027-01-15)
+
+describe('WwebjsChats.muteChat', () => {
+ function makeChats(): { chats: WwebjsChats; client: { [k: string]: jest.Mock } } {
+ const client = {
+ muteChat: jest.fn().mockResolvedValue({ isMuted: true, muteExpiration: MUTE_UNTIL }),
+ unmuteChat: jest.fn().mockResolvedValue({ isMuted: false, muteExpiration: 0 }),
+ };
+ const host = {
+ ensureReady: jest.fn(),
+ getClient: () => client as unknown as Client,
+ logger,
+ } as unknown as WwebjsEngineHost;
+ return { chats: new WwebjsChats(host, {} as unknown as WwebjsMessaging), client };
+ }
+
+ it('a timestamp mutes until exactly that instant', async () => {
+ const { chats, client } = makeChats();
+ await chats.muteChat('[email protected]', MUTE_UNTIL);
+ expect(client.unmuteChat).not.toHaveBeenCalled();
+ expect(client.muteChat).toHaveBeenCalledTimes(1);
+ const [chatId, unmuteDate] = client.muteChat.mock.calls[0] as [string, Date];
+ expect(chatId).toBe('[email protected]');
+ // The Date must carry the exact instant asked for; wwjs floors it to seconds on the page side.
+ expect(unmuteDate.getTime()).toBe(MUTE_UNTIL);
+ });
+
+ it('null unmutes', async () => {
+ const { chats, client } = makeChats();
+ await chats.muteChat('[email protected]', null);
+ expect(client.unmuteChat).toHaveBeenCalledWith('[email protected]');
+ expect(client.muteChat).not.toHaveBeenCalled();
+ });
+
+ it('propagates a failure — the caller asked for this state, so a swallow would lie', async () => {
+ const { chats, client } = makeChats();
+ client.muteChat.mockRejectedValue(new Error('page died'));
+ await expect(chats.muteChat('[email protected]', MUTE_UNTIL)).rejects.toThrow('page died');
+ });
+});
+
+describe('BaileysContacts.muteChat', () => {
+ const never = (): Promise<never> => new Promise<never>(() => undefined);
+
+ function makeContacts(
+ sock: Record<string, jest.Mock>,
+ opts: { lastMessage?: unknown; budgetMs?: number } = {},
+ ): BaileysContacts {
+ const host = {
+ ensureReady: () => undefined,
+ getSocket: () => sock as unknown as WASocket,
+ logger,
+ normalizedSelfJid: () => '[email protected]',
+ listContacts: () => [],
+ findContact: () => null,
+ resolvePhone: () => null,
+ listChats: () => [],
+ lastMessage: () => opts.lastMessage ?? null,
+ toEngineJid: (j: string) => j.replace('@c.us', '@s.whatsapp.net'),
+ } as unknown as BaileysContactsHost;
+ return new BaileysContacts(host, opts.budgetMs ?? 500);
+ }
+
+ it('a timestamp writes the mute app-state patch for that chat', async () => {
+ const chatModify = jest.fn().mockResolvedValue(undefined);
+ await makeContacts({ chatModify }).muteChat('[email protected]', MUTE_UNTIL);
+ expect(chatModify).toHaveBeenCalledWith({ mute: MUTE_UNTIL }, '[email protected]');
+ });
+
+ it('null writes the unmute patch', async () => {
+ const chatModify = jest.fn().mockResolvedValue(undefined);
+ await makeContacts({ chatModify }).muteChat('[email protected]', null);
+ expect(chatModify).toHaveBeenCalledWith({ mute: null }, '[email protected]');
+ });
+
+ it('works on a chat with NO known history, unlike archive/clear/delete', async () => {
+ const chatModify = jest.fn().mockResolvedValue(undefined);
+ const contacts = makeContacts({ chatModify }, { lastMessage: null });
+ await expect(contacts.muteChat('[email protected]', MUTE_UNTIL)).resolves.toBeUndefined();
+ expect(chatModify).toHaveBeenCalledTimes(1);
+ });
+
+ it('reports an unconfirmed write rather than resolving on a silent socket', async () => {
+ const contacts = makeContacts({ chatModify: jest.fn(never) }, { budgetMs: 15 });
+ await expect(contacts.muteChat('[email protected]', MUTE_UNTIL)).rejects.toBeInstanceOf(EngineTransportError);
+ });
+});
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 099acf797..2c26cdaf6 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -2123,6 +2123,10 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
return this.chats.sendSeen(chatId);
}
+ muteChat(chatId: string, muteUntil: number | null): Promise<void> {
+ return this.chats.muteChat(chatId, muteUntil);
+ }
+
archiveChat(chatId: string, archive: boolean): Promise<boolean> {
return this.chats.archiveChat(chatId, archive);
}
diff --git a/src/engine/adapters/wwebjs-chats.ts b/src/engine/adapters/wwebjs-chats.ts
index 3bd1ade4a..02dcee7d3 100644
--- a/src/engine/adapters/wwebjs-chats.ts
+++ b/src/engine/adapters/wwebjs-chats.ts
@@ -119,6 +119,17 @@ export class WwebjsChats {
}
}
+ async muteChat(chatId: string, muteUntil: number | null): Promise<void> {
+ this.host.ensureReady();
+ if (muteUntil === null) {
+ await this.client().unmuteChat(chatId);
+ return;
+ }
+ // muteUntil is epoch milliseconds, which is what Date wants; Client.muteChat floors it to the
+ // seconds its page-side call expects. The Baileys side takes the same milliseconds unmodified.
+ await this.client().muteChat(chatId, new Date(muteUntil));
+ }
+
async markUnread(chatId: string): Promise<boolean> {
this.host.ensureReady();
if (isChannelJid(chatId)) {
diff --git a/src/engine/engine-capability-matrix.ts b/src/engine/engine-capability-matrix.ts
index 6c4ab70e5..ff25df4c1 100644
--- a/src/engine/engine-capability-matrix.ts
+++ b/src/engine/engine-capability-matrix.ts
@@ -147,6 +147,12 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {
createChannel: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
deleteChannel: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
muteChannel: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
+ muteChat: {
+ wwjs: { status: 'supported' },
+ baileys: { status: 'supported' },
+ evidence:
+ 'baileys chatModify({mute: <epoch milliseconds> | null}) (ChatModification, Types/Chat.d.ts) → MuteAction.muteEndTimestamp (Utils/chat-utils.js:417-425); wwjs Client.muteChat(chatId, unmuteDate)/unmuteChat(chatId) (index.d.ts:182,331), which floors getTime()/1000 before the page write (Client.js:2092)',
+ },
getGroupJoinInfo: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
getGroupMembershipRequests: {
wwjs: { status: 'supported' },
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index 73a75b097..3ebdeb56d 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -1082,6 +1082,24 @@ 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>;
+ /**
+ * Mute or unmute a chat's notifications. `muteUntil` is an absolute epoch-MILLISECONDS timestamp
+ * the mute expires at; `null` unmutes now. To mute indefinitely, pass a far-future timestamp —
+ * neither engine exposes a portable "forever" sentinel (whatsapp-web.js uses -1 internally,
+ * Baileys has none), so the contract keeps a single well-defined shape instead.
+ *
+ * Milliseconds is measured, not inferred. WhatsApp's app-state `MuteAction.muteEndTimestamp` is
+ * unsuffixed while the proto spells other millisecond fields `…Ms`, which reads as seconds and is
+ * wrong: sending an epoch-seconds value live left the chat unmuted (the instant had already
+ * passed in 1970), and the same instant sent in milliseconds muted it to the expected minute.
+ * Getting this backwards is silent — the send still answers 200 and the mute simply never applies,
+ * or lands tens of thousands of years out and reads as permanent.
+ *
+ * Unlike archiveChat/clearChatMessages/deleteChat this has no "engine declined" outcome: the
+ * Baileys `mute` app-state modification carries no `lastMessages`, so a chat with no known
+ * history mutes like any other. That is why it resolves void rather than boolean.
+ */
+ muteChat(chatId: string, muteUntil: number | null): Promise<void>;
/**
* 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
diff --git a/src/modules/session/dto/index.ts b/src/modules/session/dto/index.ts
index 3521dc185..b46b564af 100644
--- a/src/modules/session/dto/index.ts
+++ b/src/modules/session/dto/index.ts
@@ -3,6 +3,7 @@ export * from './session-config.dto';
export * from './session-response.dto';
export * from './mark-chat-read.dto';
export * from './archive-chat.dto';
+export * from './mute-chat.dto';
export * from './delete-chat.dto';
export * from './send-chat-state.dto';
export * from './request-pairing-code.dto';
diff --git a/src/modules/session/dto/mute-chat.dto.ts b/src/modules/session/dto/mute-chat.dto.ts
new file mode 100644
index 000000000..b9d49bd69
--- /dev/null
+++ b/src/modules/session/dto/mute-chat.dto.ts
@@ -0,0 +1,35 @@
+import { ApiProperty } from '@nestjs/swagger';
+import { IsInt, IsNotEmpty, IsString, Matches, Min, ValidateIf } from 'class-validator';
+
+export class MuteChatDto {
+ @ApiProperty({
+ description: "Chat ID in the active engine's native format (e.g. [email protected] on whatsapp-web.js)",
+ example: '[email protected]',
+ })
+ @IsString()
+ @IsNotEmpty()
+ // Engine-neutral structural check (localpart@host, no whitespace) so a different engine's JID scheme
+ // (e.g. Baileys `…@s.whatsapp.net`) is accepted too; the adapter validates/normalises for its engine.
+ @Matches(/^[^\s@]+@[^\s@]+$/, {
+ message: 'chatId must be a valid chat JID in the form localpart@host',
+ })
+ chatId!: string;
+
+ @ApiProperty({
+ description:
+ 'Absolute epoch-MILLISECONDS timestamp at which the mute expires, or `null` to unmute now. ' +
+ 'Required — omitting it is rejected rather than guessed, because the two plausible readings ' +
+ '(unmute vs mute forever) are opposites. To mute indefinitely, send a far-future timestamp. ' +
+ 'Milliseconds, not seconds: a seconds-scale value is an instant in 1970, so the mute expires ' +
+ 'immediately while the request still answers 200.',
+ example: 1800000000000,
+ type: Number,
+ nullable: true,
+ })
+ // `null` is a real instruction (unmute), so it skips the numeric checks rather than failing them.
+ // A missing field is NOT null, so it still falls through to @IsInt and is rejected with a 400.
+ @ValidateIf((o: MuteChatDto) => o.muteUntil !== null)
+ @IsInt()
+ @Min(1)
+ muteUntil!: number | null;
+}
diff --git a/src/modules/session/session.controller.spec.ts b/src/modules/session/session.controller.spec.ts
index b1e1d0904..d0bf93737 100644
--- a/src/modules/session/session.controller.spec.ts
+++ b/src/modules/session/session.controller.spec.ts
@@ -157,3 +157,34 @@ describe('SessionController — logout() audit + error forwarding contract', ()
expect(auditService.logInfo).not.toHaveBeenCalled();
});
});
+
+// Chat mute carries a nullable argument, which is the part worth pinning: `null` is the unmute
+// instruction, so a controller that coalesced it away (`?? undefined`, `|| 0`) would silently turn
+// every unmute into a mute-until-the-epoch. Both directions are asserted.
+describe('SessionController — muteChat', () => {
+ let sessionService: { muteChat: jest.Mock };
+ let auditService: { logInfo: jest.Mock };
+ let controller: SessionController;
+
+ beforeEach(() => {
+ sessionService = { muteChat: jest.fn().mockResolvedValue(undefined) };
+ auditService = { logInfo: jest.fn().mockResolvedValue(undefined) };
+ controller = new SessionControllerClass(
+ sessionService as unknown as SessionService,
+ auditService as unknown as AuditService,
+ );
+ });
+
+ it('forwards the expiry second to the service', async () => {
+ const result = await controller.muteChat('sess-uuid-1', { chatId: '[email protected]', muteUntil: 1_800_000_000 });
+
+ expect(sessionService.muteChat).toHaveBeenCalledWith('sess-uuid-1', '[email protected]', 1_800_000_000);
+ expect(result).toEqual({ success: true });
+ });
+
+ it('forwards a null expiry as null — that is the unmute instruction, not a missing value', async () => {
+ await controller.muteChat('sess-uuid-1', { chatId: '[email protected]', muteUntil: null });
+
+ expect(sessionService.muteChat).toHaveBeenCalledWith('sess-uuid-1', '[email protected]', null);
+ });
+});
diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.ts
index 9fdeef0a6..f7eb0751a 100644
--- a/src/modules/session/session.controller.ts
+++ b/src/modules/session/session.controller.ts
@@ -25,6 +25,7 @@ import {
SetOwnPresenceDto,
ChatPresenceResponseDto,
ArchiveChatDto,
+ MuteChatDto,
DeleteChatDto,
SendChatStateDto,
RequestPairingCodeDto,
@@ -608,6 +609,32 @@ export class SessionController {
return { success };
}
+ @Post(':id/chats/mute')
+ @RequireRole(ApiKeyRole.OPERATOR)
+ @HttpCode(HttpStatus.OK)
+ @ApiOperation({ summary: 'Mute or unmute a chat' })
+ @ApiParam({ name: 'id', description: 'Session ID' })
+ @ApiResponse({
+ status: 200,
+ description:
+ 'Returns `{ success: true }`. Unlike the archive route there is no declined outcome: the mute ' +
+ "change is not keyed to the chat's last message on either engine, so a chat with no known " +
+ 'history mutes like any other.',
+ })
+ @ApiResponse({ status: 400, description: 'Session not ready, or an invalid chatId / muteUntil' })
+ @ApiResponse({ status: 404, description: 'Session not found' })
+ @ApiResponse({
+ status: 503,
+ description:
+ 'WhatsApp did not answer within the request budget. The change may or may not have been applied — ' +
+ 'the gateway stopped waiting for a confirmation that never came.',
+ })
+ @ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })
+ async muteChat(@Param('id', ParseUUIDPipe) id: string, @Body() dto: MuteChatDto): Promise<{ success: boolean }> {
+ await this.sessionService.muteChat(id, dto.chatId, dto.muteUntil);
+ return { success: true };
+ }
+
@Post(':id/chats/delete')
@RequireRole(ApiKeyRole.OPERATOR)
@HttpCode(HttpStatus.OK)
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index afe4b0e00..0b01bad35 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -595,6 +595,22 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
return engine.archiveChat(chatId, archive);
}
+ /**
+ * Mute a chat until `muteUntil` (absolute epoch milliseconds), or unmute it with `null`. Unlike
+ * archiveChat there is no "engine declined" outcome — the Baileys mute patch is not keyed to the
+ * chat's last message — so this resolves void and a failure surfaces as an error.
+ */
+ async muteChat(id: string, chatId: string, muteUntil: number | null): Promise<void> {
+ await this.findOne(id); // Verify session exists
+ const engine = this.engines.get(id);
+
+ if (!engine) {
+ throw new BadRequestException('Session is not started');
+ }
+
+ return engine.muteChat(chatId, muteUntil);
+ }
+
async deleteChat(id: string, chatId: string): Promise<boolean> {
await this.findOne(id); // Verify session exists
const engine = this.engines.get(id);