Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(engine): add chat pin/unpin on both engines
Yudhi Armyndharis1a70d4741ac9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 129036fdf..363284d59 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/pin` pins a chat to the top of the list or unpins it, on both engines; `success: false` reports WhatsApp's three-pin cap, which only the whatsapp-web.js engine can observe.- `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.diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex d59eed1cd..945132130 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -941,6 +941,49 @@ Mute a chat's notifications until a given moment, or unmute it.**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/pin++Pin a chat to the top of the chat list, or unpin it. Chat-level — distinct from+`messages/pin`, which pins a message inside a chat.++**Auth:** API key (OPERATOR) · **Scope:** session-scoped++**Path parameters**++| Name | Type | Description |+| ---- | ------ | ------------ |+| `id` | string | Session UUID |++**Request body** — `PinChatDto`++| Field | Type | Required | Constraints | Description |+| -------- | ------- | -------- | ------------------------------------------------------------------------------------------- | --------------------------------------------- |+| `chatId` | string | Yes | `@IsString`; `@IsNotEmpty`; `@Matches(/^[^\s@]+@[^\s@]+$/)` (localpart@host, no whitespace) | Engine-native JID, e.g. `[email protected]` |+| `pin` | boolean | Yes | `@IsBoolean` (strict — the string `"false"` is rejected, not coerced to `true`) | `true` to pin, `false` to unpin |++```json+{ "chatId": "[email protected]", "pin": true }+```++**Response** `200`++```json+{ "success": true }+```++> **`success: false` means WhatsApp refused the pin, and only a pin can be refused.** WhatsApp allows+> at most **three** pinned chats. On the whatsapp-web.js engine a fourth pin returns `success: false`+> without changing anything. Unpinning always succeeds.++> **The Baileys engine cannot see that cap.** It writes an app-state patch and WhatsApp reports+> nothing back, so it answers `success: true` for every accepted request — including a fourth pin+> that WhatsApp may then decline on its own. Treat `true` on that engine as "the request was sent",+> not "the chat is pinned". Unlike `chats/archive` the patch is not keyed to the chat's last message,+> so a chat with no known history pins normally.++**Errors:** `400` session not ready · `401` missing/invalid API key · `404` session not found ·+`503` WhatsApp did not confirm within the request budget+#### POST /api/sessions/:id/chats/deleteDelete 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.mdindex a338d53a3..bf6471287 100644--- a/docs/07-api-collection.md+++ b/docs/07-api-collection.md@@ -222,6 +222,16 @@ curl -X POST "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/chats/mute-d '{"chatId":"[email protected]","muteUntil":1800000000000}'```+#### POST /api/sessions/:id/chats/pin++Pin a chat to the top of the list, or unpin it (OPERATOR). WhatsApp allows at most three pinned chats.++```bash+curl -X POST "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/chats/pin" \+ -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \+ -d '{"chatId":"[email protected]","pin":true}'+```+#### POST /api/sessions/:id/chats/deleteDelete a chat from the chat list (OPERATOR).diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.mdindex 9c6ecb11a..930b5c1bc 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** throughits adapter layer and REST API — including which "supported" cells only work because OpenWA patches-the installed library. Coverage is total: all 106 `IWhatsAppEngine` methods (29.4), **all 152+the installed library. Coverage is total: all 107 `IWhatsAppEngine` methods (29.4), **all 152Baileys + 81 whatsapp-web.js library methods** (29.5), all 34 + 31 library events (29.5.4), and all5 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 106 `IWhatsAppEngine` methods; use it to see+- **29.4 — the OpenWA contract view.** Rows are the 107 `IWhatsAppEngine` methods; use it to seewhat 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 architectureOpenWA never calls a WhatsApp library directly from a controller. Every session owns one engine-instance behind the neutral `IWhatsAppEngine` interface (106 methods ++instance behind the neutral `IWhatsAppEngine` interface (107 methods +`EngineEventCallbacks`), and all modules go through it:```mermaidflowchart LRsubgraph OpenWA["OpenWA"]API["REST API controllers"] --> SVC["Modules / services"]- SVC --> IF["IWhatsAppEngine - 106 methods"]+ SVC --> IF["IWhatsAppEngine - 107 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: `initiarests on the column-wide 🔧¹ (wwjs) and 🔧⁵ (baileys) — no row runs on stock library code on bothsides.-## 29.4 Full capability matrix — the OpenWA contract view (106 methods)+## 29.4 Full capability matrix — the OpenWA contract view (107 methods)Legend recap: **✅** supported · **✅🔧ⁿ** supported via OpenWA patch `🔧ⁿ` (29.3) ·**❌ gap** adapter-gap · **❌ lib** library-limitation. Column headers carry the engine-wide@@ -221,6 +221,7 @@ session runs; ⚠️ depends on the session engine; ❌ 501 on both.| `deleteChat` | ✅ | ✅ | ✅ || `markUnread` | ✅ | ✅ | ✅ || `muteChat` | ✅ | ✅ | ✅ |+| `pinChat` | ✅ | ✅ | ✅ |### 29.4.5 Contacts@@ -335,9 +336,9 @@ answers 501.| `subscribeToPresence` | ✅ | ❌ lib | ⚠️ baileys only || `rejectCall` | ✅ | ✅ | ✅ |-**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,+**Totals:** 107 methods → 214 adapter cells: **192 ✅, 22 ❌** (2 adapter-gaps, 20+library-limitations, 0 uncertain) across 21 methods. From the REST caller's side: **88** methods+work on any engine (86 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@@ -548,7 +549,7 @@ with zero OpenWA surface. Baileys-only; whatsapp-web.js has no community API at| --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `appPatch` | 🔩 plumbing || `assertSessions` | 🔩 plumbing |-| `chatModify` | ✅ `upsertContact`, `markUnread`, `clearChatMessages`, `archiveChat`, `muteChat`, `deleteChat`, `deleteMessage`, `starMessage` |+| `chatModify` | ✅ `upsertContact`, `markUnread`, `clearChatMessages`, `archiveChat`, `muteChat`, `pinChat`, `deleteChat`, `deleteMessage`, `starMessage` || `cleanDirtyBits` | 🔩 plumbing || `createParticipantNodes` | 🔩 plumbing || `digestKeyBundle` | 🔩 plumbing |@@ -613,10 +614,10 @@ with zero OpenWA surface. Baileys-only; whatsapp-web.js has no community API at| `getChats` | ✅ `getChats`, `getGroups` || `markChatUnread` | ❌ **not exposed** || `muteChat` | ✅ `muteChat` |-| `pinChat` | ❌ **not exposed** |+| `pinChat` | ✅ `pinChat` || `unarchiveChat` | ✅ `archiveChat` || `unmuteChat` | ✅ `muteChat` |-| `unpinChat` | ❌ **not exposed** |+| `unpinChat` | ✅ `pinChat` |**Groups** (7)@@ -714,7 +715,6 @@ new `IWhatsAppEngine` method wires both adapters at once. All cross-checked agai| 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 |@@ -856,24 +856,25 @@ adapter boundary — none silently stubs.Recomputed from `engine-capability-matrix.ts`, `upstream-surface.snapshot.json`, and a scan of theadapter sources — re-derive the same way when anything changes:-- **106** interface methods → **212** adapter cells: **190 ✅** / **22 ❌** (2 adapter-gaps, 20+- **107** interface methods → **214** adapter cells: **192 ✅** / **22 ❌** (2 adapter-gaps, 20library-limitations, 0 uncertain), spanning **21** methods.-- Of the 190 ✅ cells, **6 wwjs cells carry an explicit patch dependency** (4 × 🔧² status send,+- Of the 192 ✅ cells, **6 wwjs cells carry an explicit patch dependency** (4 × 🔧² status send,1 × 🔧³ channel link preview, 1 × 🔧⁴ ready-sync) and the whole wwjs column additionallydepends 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: **87** engine-neutral (85 + 2 store-backed status reads), **9** Baileys-only,+- REST caller's view: **88** engine-neutral (86 + 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 — 43 wired,- 2 internal wiring, 1 class plumbing, **35 ❌ not exposed** (27 real capabilities + 8+ exposed** (incl. the whole 23-method community cluster); wwjs **81** Client methods — 45 wired,+ 2 internal wiring, 1 class plumbing, **33 ❌ not exposed** (25 real capabilities + 8session/transport settings that are not WhatsApp capabilities). The backlog is the ❌ rows minusthose 8 settings; 🔩 plumbing is correctly never exposed.- Events: Baileys **34** (15 consumed / 19 dropped), wwjs **31** (16 consumed / 15 dropped).-- **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`.)+- **4** capabilities are supported by **both** libraries and missing only in OpenWA (29.5.3) — the+ cheapest backlog: create-call-link, delete-own-profile-picture, channel admin demote, channel+ ownership transfer. (Chat mute/unmute and chat pin/unpin were two of the six; both are now wired —+ see `muteChat` and `pinChat`.)- **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.jsonindex 96256b079..6f17d80de 100644--- a/openapi.json+++ b/openapi.json@@ -1358,6 +1358,53 @@]}},+ "/api/sessions/{id}/chats/pin": {+ "post": {+ "operationId": "SessionController_pinChat",+ "parameters": [+ {+ "name": "id",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PinChatDto"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Returns `{ success }`. `false` means the engine declined, and only a pin can: WhatsApp allows at most three pinned chats and the whatsapp-web.js engine reports the refusal. Unpinning always succeeds, and the Baileys engine always reports success because it cannot observe the cap."+ },+ "400": {+ "description": "Session not ready"+ },+ "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": "Pin or unpin a chat at the top of the chat list",+ "tags": [+ "sessions"+ ]+ }+ },"/api/sessions/{id}/chats/delete": {"post": {"operationId": "SessionController_deleteChat",@@ -9860,6 +9907,24 @@"muteUntil"]},+ "PinChatDto": {+ "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]"+ },+ "pin": {+ "type": "boolean",+ "description": "true to pin the chat to the top of the list, false to unpin it."+ }+ },+ "required": [+ "chatId",+ "pin"+ ]+ },"DeleteChatDto": {"type": "object","properties": {diff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.tsindex 52d9ff95d..a56bdba9d 100644--- a/src/engine/adapters/baileys-contacts.ts+++ b/src/engine/adapters/baileys-contacts.ts@@ -236,6 +236,16 @@ export class BaileysContacts {await this.confirmed(this.sock().chatModify({ mute: muteUntil }, this.host.toEngineJid(chatId)), 'the mute change');}+ async pinChat(chatId: string, pin: boolean): Promise<boolean> {+ this.host.ensureReady();+ // No lastMessage lookup: the `pin` member of ChatModification carries no `lastMessages`, unlike+ // archive/clear/delete, so a chat with no known history pins fine. Always true — Baileys writes+ // the app-state patch and reports nothing back, so it has no equivalent of the whatsapp-web.js+ // three-pin refusal to surface.+ await this.confirmed(this.sock().chatModify({ pin }, this.host.toEngineJid(chatId)), 'the pin change');+ return true;+ }+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.tsindex faede3ee4..aef88ea2b 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -553,6 +553,10 @@ export class BaileysAdapter implements IWhatsAppEngine {return this.contacts.muteChat(chatId, muteUntil);}+ async pinChat(chatId: string, pin: boolean): Promise<boolean> {+ return this.contacts.pinChat(chatId, pin);+ }+async archiveChat(chatId: string, archive: boolean): Promise<boolean> {return this.contacts.archiveChat(chatId, archive);}diff --git a/src/engine/adapters/chat-pin.spec.ts b/src/engine/adapters/chat-pin.spec.tsnew file mode 100644index 000000000..7034ca422--- /dev/null+++ b/src/engine/adapters/chat-pin.spec.ts@@ -0,0 +1,115 @@+import type { WASocket } from '@whiskeysockets/baileys';+import type { Client } from 'whatsapp-web.js';+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';++/**+ * Chat pin/unpin — the second of the §29.5.3 "supported by BOTH libraries, missing only in OpenWA"+ * backlog. Chat-level, distinct from `pinMessage`, which pins a message inside a chat.+ *+ * The whole difficulty is the return value, and it is the same trap `archiveChat` already carries:+ * whatsapp-web.js's `pinChat`/`unpinChat` resolve the chat's NEW PIN STATE, not a success flag+ * (`Client.js:2046-2084`). `unpinChat` therefore returns `false` on every successful unpin — both+ * on its early-out for an already-unpinned chat and after actually unpinning. Forwarding that+ * verbatim would report every successful unpin as "the engine declined".+ *+ * But `pinChat`'s `false` is NOT noise: WhatsApp allows at most three pinned chats+ * (`MAX_PIN_COUNT = 3`), and the page returns `false` without pinning when that is already met.+ * That is a real refusal a caller needs to see. So the two directions are asymmetric, and only the+ * pin direction can decline.+ *+ * Baileys has no refusal signal at all — `chatModify({pin})` writes a `pinAction` app-state patch+ * and that is the end of it — and, like `mute` and unlike `archive`, the patch carries no+ * `lastMessages`, so a chat with no known history pins fine.+ */++const logger = createLogger('chat-pin.spec');++describe('WwebjsChats.pinChat', () => {+ function makeChats(): { chats: WwebjsChats; client: { [k: string]: jest.Mock } } {+ const client = {+ pinChat: jest.fn().mockResolvedValue(true),+ unpinChat: jest.fn().mockResolvedValue(false),+ };+ 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('pinning a chat calls pinChat and reports success', async () => {+ const { chats, client } = makeChats();+ await expect(chats.pinChat('[email protected]', true)).resolves.toBe(true);+ expect(client.pinChat).toHaveBeenCalledWith('[email protected]');+ expect(client.unpinChat).not.toHaveBeenCalled();+ });++ // The pin limit is the one case where whatsapp-web.js's return value carries real information.+ it('reports false when WhatsApp refuses the pin because three chats are already pinned', async () => {+ const { chats, client } = makeChats();+ client.pinChat.mockResolvedValue(false);+ await expect(chats.pinChat('[email protected]', true)).resolves.toBe(false);+ });++ // The archiveChat trap, in the pin direction: unpinChat resolves the NEW pin state, which is+ // false for every successful unpin. Forwarding it would report success as refusal.+ it('unpinning reports success even though unpinChat resolves false', async () => {+ const { chats, client } = makeChats();+ await expect(chats.pinChat('[email protected]', false)).resolves.toBe(true);+ expect(client.unpinChat).toHaveBeenCalledWith('[email protected]');+ expect(client.pinChat).not.toHaveBeenCalled();+ });+});++describe('BaileysContacts.pinChat', () => {+ 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('pinning writes the pin app-state patch for that chat', async () => {+ const chatModify = jest.fn().mockResolvedValue(undefined);+ await expect(makeContacts({ chatModify }).pinChat('[email protected]', true)).resolves.toBe(true);+ expect(chatModify).toHaveBeenCalledWith({ pin: true }, '[email protected]');+ });++ it('unpinning writes the same patch with pin false', async () => {+ const chatModify = jest.fn().mockResolvedValue(undefined);+ await expect(makeContacts({ chatModify }).pinChat('[email protected]', false)).resolves.toBe(true);+ expect(chatModify).toHaveBeenCalledWith({ pin: false }, '[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.pinChat('[email protected]', true)).resolves.toBe(true);+ 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.pinChat('[email protected]', true)).rejects.toBeInstanceOf(EngineTransportError);+ });+});diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex 2c26cdaf6..e9bde9fea 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -2127,6 +2127,10 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginreturn this.chats.muteChat(chatId, muteUntil);}+ pinChat(chatId: string, pin: boolean): Promise<boolean> {+ return this.chats.pinChat(chatId, pin);+ }+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.tsindex 02dcee7d3..61a49ff95 100644--- a/src/engine/adapters/wwebjs-chats.ts+++ b/src/engine/adapters/wwebjs-chats.ts@@ -130,6 +130,22 @@ export class WwebjsChats {await this.client().muteChat(chatId, new Date(muteUntil));}+ async pinChat(chatId: string, pin: boolean): Promise<boolean> {+ this.host.ensureReady();+ if (!pin) {+ // unpinChat resolves the chat's NEW pin state, which is `false` for every successful unpin —+ // both on its early-out for an already-unpinned chat and after actually unpinning+ // (Client.js:2073-2084). Forwarding it would report every success as a refusal, the same trap+ // archiveChat documents. Discard it: an unpin that did not throw succeeded.+ await this.client().unpinChat(chatId);+ return true;+ }+ // In this direction the return value IS information. WhatsApp caps pinned chats at three+ // (MAX_PIN_COUNT, Client.js:2054-2063) and the page returns false without pinning once that is+ // met, so a false here is a real refusal the caller needs to see.+ return await this.client().pinChat(chatId);+ }+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.tsindex ff25df4c1..cdfa66993 100644--- a/src/engine/engine-capability-matrix.ts+++ b/src/engine/engine-capability-matrix.ts@@ -248,6 +248,12 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {leaveGroup: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },logout: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },markUnread: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ pinChat: {+ wwjs: { status: 'supported' },+ baileys: { status: 'supported' },+ evidence:+ 'baileys chatModify({pin: boolean}) (ChatModification, Types/Chat.d.ts:69) -> pinAction indexed by [pin_v1, jid] (Utils/chat-utils.js:487-499); wwjs Client.pinChat/unpinChat (index.d.ts:49,52), which resolve the NEW pin state and enforce MAX_PIN_COUNT = 3 page-side (Client.js:2046-2084)',+ },pinMessage: {wwjs: { status: 'supported' },baileys: { status: 'supported' },diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex 3ebdeb56d..86f5bbba7 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -1082,6 +1082,17 @@ 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>;+ /**+ * Pin or unpin a chat at the top of the chat list. Chat-level — distinct from `pinMessage`, which+ * pins a message inside a chat.+ *+ * Resolves false only when the engine DECLINED, and only one direction can: WhatsApp allows at+ * most three pinned chats, and whatsapp-web.js reports the refusal rather than silently dropping+ * it. Unpinning always resolves true, and Baileys always resolves true in both directions — it+ * writes an app-state patch and WhatsApp reports nothing back, so it cannot see the cap. Unlike+ * archiveChat the patch carries no `lastMessages`, so a chat with no known history pins fine.+ */+ pinChat(chatId: string, pin: 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 —diff --git a/src/modules/session/dto/index.ts b/src/modules/session/dto/index.tsindex b46b564af..07352eafd 100644--- a/src/modules/session/dto/index.ts+++ b/src/modules/session/dto/index.ts@@ -4,6 +4,7 @@ export * from './session-response.dto';export * from './mark-chat-read.dto';export * from './archive-chat.dto';export * from './mute-chat.dto';+export * from './pin-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/pin-chat.dto.ts b/src/modules/session/dto/pin-chat.dto.tsnew file mode 100644index 000000000..8e02499ae--- /dev/null+++ b/src/modules/session/dto/pin-chat.dto.ts@@ -0,0 +1,25 @@+import { ApiProperty } from '@nestjs/swagger';+import { IsBoolean, IsNotEmpty, IsString, Matches } from 'class-validator';+import { ToStrictBoolean } from '../../../common/utils/strict-boolean';++export class PinChatDto {+ @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: 'true to pin the chat to the top of the list, false to unpin it.' })+ // Read strictly: under the pipe's implicit conversion the string "false" would become boolean+ // true, pinning a chat the caller asked to release.+ @ToStrictBoolean()+ @IsBoolean()+ pin!: boolean;+}diff --git a/src/modules/session/session.controller.spec.ts b/src/modules/session/session.controller.spec.tsindex d0bf93737..8feb2159f 100644--- a/src/modules/session/session.controller.spec.ts+++ b/src/modules/session/session.controller.spec.ts@@ -188,3 +188,42 @@ describe('SessionController — muteChat', () => {expect(sessionService.muteChat).toHaveBeenCalledWith('sess-uuid-1', '[email protected]', null);});});++// The pin route forwards a boolean the engine can refuse. The value worth pinning is that the+// engine's `false` reaches the caller: WhatsApp caps pinned chats at three, and a controller that+// hard-coded `{ success: true }` would report a refused pin as done.+describe('SessionController — pinChat', () => {+ let sessionService: { pinChat: jest.Mock };+ let auditService: { logInfo: jest.Mock };+ let controller: SessionController;++ beforeEach(() => {+ sessionService = { pinChat: jest.fn().mockResolvedValue(true) };+ auditService = { logInfo: jest.fn().mockResolvedValue(undefined) };+ controller = new SessionControllerClass(+ sessionService as unknown as SessionService,+ auditService as unknown as AuditService,+ );+ });++ it('forwards the chat id and the pin flag', async () => {+ const result = await controller.pinChat('sess-uuid-1', { chatId: '[email protected]', pin: true });++ expect(sessionService.pinChat).toHaveBeenCalledWith('sess-uuid-1', '[email protected]', true);+ expect(result).toEqual({ success: true });+ });++ it('surfaces a refused pin as success:false rather than reporting it done', async () => {+ sessionService.pinChat.mockResolvedValue(false);++ await expect(controller.pinChat('sess-uuid-1', { chatId: '[email protected]', pin: true })).resolves.toEqual({+ success: false,+ });+ });++ it('forwards an unpin as pin:false', async () => {+ await controller.pinChat('sess-uuid-1', { chatId: '[email protected]', pin: false });++ expect(sessionService.pinChat).toHaveBeenCalledWith('sess-uuid-1', '[email protected]', false);+ });+});diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.tsindex f7eb0751a..d2c67d9ed 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -26,6 +26,7 @@ import {ChatPresenceResponseDto,ArchiveChatDto,MuteChatDto,+ PinChatDto,DeleteChatDto,SendChatStateDto,RequestPairingCodeDto,@@ -635,6 +636,32 @@ export class SessionController {return { success: true };}+ @Post(':id/chats/pin')+ @RequireRole(ApiKeyRole.OPERATOR)+ @HttpCode(HttpStatus.OK)+ @ApiOperation({ summary: 'Pin or unpin a chat at the top of the chat list' })+ @ApiParam({ name: 'id', description: 'Session ID' })+ @ApiResponse({+ status: 200,+ description:+ 'Returns `{ success }`. `false` means the engine declined, and only a pin can: WhatsApp allows ' ++ 'at most three pinned chats and the whatsapp-web.js engine reports the refusal. Unpinning always ' ++ 'succeeds, and the Baileys engine always reports success because it cannot observe the cap.',+ })+ @ApiResponse({ status: 400, description: 'Session not ready' })+ @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 pinChat(@Param('id', ParseUUIDPipe) id: string, @Body() dto: PinChatDto): Promise<{ success: boolean }> {+ const success = await this.sessionService.pinChat(id, dto.chatId, dto.pin);+ return { success };+ }+@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.tsindex 0b01bad35..28580f1a0 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -611,6 +611,21 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatreturn engine.muteChat(chatId, muteUntil);}+ /**+ * Pin or unpin a chat. Resolves false only when the engine declined — whatsapp-web.js reports+ * WhatsApp's three-pin cap; Baileys cannot see it and always resolves true.+ */+ async pinChat(id: string, chatId: string, pin: boolean): 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.pinChat(chatId, pin);+ }+async deleteChat(id: string, chatId: string): Promise<boolean> {await this.findOne(id); // Verify session existsconst engine = this.engines.get(id);