Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(chats): archive and unarchive a chat on both engines
Yudhi Armyndharis9be63e209508
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6f73bbae0..c53d9396d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- **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`.++ `success: false` is a real outcome rather than an error: on the Baileys engine the archive is an+ app-state modification keyed to the chat's **last message**, so a chat with no known history+ cannot be archived — the same limitation `chats/delete` and `chats/unread` already carry there.+ whatsapp-web.js uses `Client.archiveChat`/`unarchiveChat`, which report the new state, rather than+ `Chat.archive()`, which resolves nothing.++ No webhook fires for your own archive: Baileys emits no event for a change the account itself made,+ and whatsapp-web.js's `chat_archived` event is not wired. A `chat.archived` event covering+ remote-device archives is left as follow-up work — it needs event wiring on both engines and is a+ separate change from this endpoint.+- **Messages can be starred and unstarred:** `POST /api/sessions/:sessionId/messages/star` with`{ chatId, messageId, star }`. Starring is private to the account, has no group-adminrestriction, and never expires. Available in all five SDKs as `messages.star`.diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 7274da0dd..e2e08f3a2 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -712,6 +712,46 @@ Returns HTTP `200`, matching the OpenAPI contract.**Errors:** `400` validation, or session not started · `401` · `403` · `404` session not found+#### POST /api/sessions/:id/chats/archive++Archive or unarchive a chat.++**Auth:** API key (OPERATOR) · **Scope:** session-scoped++**Path parameters**++| Name | Type | Description |+| --- | --- | --- |+| `id` | string | Session UUID |++**Request body** — `ArchiveChatDto`++| Field | Type | Required | Constraints | Description |+| --- | --- | --- | --- | --- |+| `chatId` | string | Yes | `@IsString`; `@IsNotEmpty`; `@Matches(/^[^\s@]+@[^\s@]+$/)` (localpart@host, no whitespace) | Engine-native JID, e.g. `[email protected]` |+| `archive` | boolean | Yes | `@IsBoolean` (strict — the string `"false"` is rejected, not coerced to `true`) | `true` to archive, `false` to unarchive |++```json+{ "chatId": "[email protected]", "archive": true }+```++**Response** `200`++```json+{ "success": true }+```++> **`success: false` is a real outcome here, not an error.** On the Baileys engine the archive is an+> app-state modification keyed to the chat's **last message**, so a chat with no known history+> cannot be archived at all — the same limitation `chats/delete` and `chats/unread` already carry on+> that engine. Rather than fail with a 500, the endpoint reports `success: false`.++> **No `chat.archived` webhook fires for your own archive.** Baileys emits no event for a change the+> account itself made (remote-device archives arrive later via chat-update diffing), and+> whatsapp-web.js's `chat_archived` event is not wired. Treat the HTTP response as the outcome.++**Errors:** `400` session not ready · `401` missing/invalid API key · `404` session not found+#### 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 468e4cab3..b3d2d9f1f 100644--- a/docs/07-api-collection.md+++ b/docs/07-api-collection.md@@ -193,6 +193,16 @@ curl -X POST "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/chats/unre-d '{ "chatId": "[email protected]" }'```+#### POST /api/sessions/:id/chats/archive++Archive or unarchive a chat.++```bash+curl -X POST "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/chats/archive" \+ -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \+ -d '{"chatId":"[email protected]","archive":true}'+```+#### POST /api/sessions/:id/chats/deleteDelete a chat from the chat list (OPERATOR).diff --git a/docs/18-sdk-design.md b/docs/18-sdk-design.mdindex 0f581d411..91427b1d7 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, delete, sendState |+| `chats` | list, markRead, markUnread, archive, 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.mdindex 79c1929ca..e994dd3fa 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; theyfrom `engine-capability-matrix.ts` rather than adjusted by hand. Re-derive them the same way whenadding a method, instead of incrementing the previous figure.-- **83** interface methods, **166** adapter-cells (83 × 2 engines).-- **149** supported cells; **17** not-available cells across **16** methods.+- **84** interface methods, **168** adapter-cells (84 × 2 engines).+- **151** 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.jsonindex 6e8c6e54f..c3dd4a042 100644--- a/openapi.json+++ b/openapi.json@@ -905,6 +905,47 @@]}},+ "/api/sessions/{id}/chats/archive": {+ "post": {+ "operationId": "SessionController_archiveChat",+ "parameters": [+ {+ "name": "id",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ArchiveChatDto"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Returns `{ success }`. `false` means the engine declined to act — on the Baileys engine a chat with no known history cannot be archived, since the change is keyed to its last message."+ },+ "400": {+ "description": "Session not ready"+ },+ "404": {+ "description": "Session not found"+ }+ },+ "summary": "Archive or unarchive a chat",+ "tags": [+ "sessions"+ ]+ }+ },"/api/sessions/{id}/chats/delete": {"post": {"operationId": "SessionController_deleteChat",@@ -6636,6 +6677,24 @@"chatId"]},+ "ArchiveChatDto": {+ "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]"+ },+ "archive": {+ "type": "boolean",+ "description": "true to archive, false to unarchive."+ }+ },+ "required": [+ "chatId",+ "archive"+ ]+ },"DeleteChatDto": {"type": "object","properties": {diff --git a/sdk/README.md b/sdk/README.mdindex 1cb4a8ab9..48a759552 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, delete, sendState |+| `chats` | list, markRead, markUnread, archive, 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.goindex 08b438aa8..28cb6bdf7 100644--- a/sdk/go/chats.go+++ b/sdk/go/chats.go@@ -32,6 +32,12 @@ func (s *ChatsService) Delete(ctx context.Context, sessionID string, body Deletereturn s.post(ctx, sessionID, "/delete", body)}+// Archive archives or unarchives a chat. A false Success means the engine+// declined — on Baileys a chat with no known history cannot be archived.+func (s *ChatsService) Archive(ctx context.Context, sessionID string, body ArchiveChatRequest) (*SuccessResult, error) {+ return s.post(ctx, sessionID, "/archive", body)+}+// 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.goindex 3f0b589eb..ac6fa61e1 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.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/go/types_chat.go b/sdk/go/types_chat.goindex e8a37bc2f..b59eab14f 100644--- a/sdk/go/types_chat.go+++ b/sdk/go/types_chat.go@@ -29,6 +29,12 @@ type DeleteChatRequest struct {ChatID string `json:"chatId"`}+// ArchiveChatRequest archives or unarchives a chat.+type ArchiveChatRequest struct {+ ChatID string `json:"chatId"`+ Archive bool `json:"archive"`+}+// ListChatsQuery paginates the chat list.type ListChatsQuery struct {Limit *intdiff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ArchiveChatRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ArchiveChatRequest.javanew file mode 100644index 000000000..ffb9a118a--- /dev/null+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ArchiveChatRequest.java@@ -0,0 +1,28 @@+package com.rmyndharis.openwa.model;++/** Request body for archiving or unarchiving a chat. */+public record ArchiveChatRequest(String chatId, Boolean archive) {+ public static Builder builder() {+ return new Builder();+ }++ public static final class Builder {+ private String chatId;+ private Boolean archive;++ public Builder chatId(String v) {+ this.chatId = v;+ return this;+ }++ /** true to archive, false to unarchive. */+ public Builder archive(Boolean v) {+ this.archive = v;+ return this;+ }++ public ArchiveChatRequest build() {+ return new ArchiveChatRequest(chatId, archive);+ }+ }+}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.javaindex 9be1ad7cc..e285e07c5 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@@ -4,6 +4,7 @@ import static com.rmyndharis.openwa.http.Http.encodeSegment;import com.rmyndharis.openwa.OpenWAClient;import com.rmyndharis.openwa.http.HttpMethod;+import com.rmyndharis.openwa.model.ArchiveChatRequest;import com.rmyndharis.openwa.model.ChatSummary;import com.rmyndharis.openwa.model.DeleteChatRequest;import com.rmyndharis.openwa.model.ListChatsQuery;@@ -49,6 +50,15 @@ public final class ChatsResource {HttpMethod.POST, "/api/sessions/" + encodeSegment(sessionId) + "/chats/unread", null, body, 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.+ */+ public SuccessResult archive(String sessionId, ArchiveChatRequest body) {+ return client.request(+ HttpMethod.POST, "/api/sessions/" + encodeSegment(sessionId) + "/chats/archive", null, body, SuccessResult.class);+ }+/** Delete a chat from the chat list. */public SuccessResult delete(String sessionId, DeleteChatRequest body) {return client.request(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.javaindex 2c78e5525..d5da91bcd 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@@ -7,6 +7,7 @@ import com.rmyndharis.openwa.ClientConfig;import com.rmyndharis.openwa.OpenWAClient;import com.rmyndharis.openwa.http.HttpMethod;import com.rmyndharis.openwa.model.ChatState;+import com.rmyndharis.openwa.model.ArchiveChatRequest;import com.rmyndharis.openwa.model.DeleteChatRequest;import com.rmyndharis.openwa.model.ListChatsQuery;import com.rmyndharis.openwa.model.MarkChatRequest;@@ -60,6 +61,15 @@ class ChatsResourceTest {assertTrue(tx.lastRequest().body().contains("[email protected]"));}+ @Test+ void archiveSendsBody() {+ tx.respond(200, "{\"success\":true}");+ client.chats.archive("s", ArchiveChatRequest.builder().chatId("[email protected]").archive(true).build());+ assertEquals("http://h/api/sessions/s/chats/archive", tx.lastRequest().url());+ assertEquals(HttpMethod.POST, tx.lastRequest().method());+ assertTrue(tx.lastRequest().body().contains("[email protected]"));+ }+@Testvoid deleteSendsBody() {tx.respond(200, "{\"success\":true}");diff --git a/sdk/javascript/src/resources/chats.ts b/sdk/javascript/src/resources/chats.tsindex 49f7ba1f1..8c4948479 100644--- a/sdk/javascript/src/resources/chats.ts+++ b/sdk/javascript/src/resources/chats.ts@@ -10,7 +10,14 @@import { encodeSegment } from '../http.js';import type { OpenWAClient } from '../client.js';-import type { ChatSummary, DeleteChatRequest, MarkChatRequest, SendChatStateRequest, SuccessResult } from '../types.js';+import type {+ ArchiveChatRequest,+ ChatSummary,+ DeleteChatRequest,+ MarkChatRequest,+ SendChatStateRequest,+ SuccessResult,+} from '../types.js';export interface ListChatsQuery {limit?: number;@@ -47,6 +54,18 @@ export class ChatsResource {});}+ /**+ * Archive or unarchive a chat. `success: false` means the engine declined — on Baileys a chat+ * with no known history cannot be archived.+ */+ archive(sessionId: string, body: ArchiveChatRequest): Promise<SuccessResult> {+ return this.client.request<SuccessResult>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/chats/archive`,+ body,+ });+ }+/** Delete a chat from the chat list. */delete(sessionId: string, body: DeleteChatRequest): Promise<SuccessResult> {return this.client.request<SuccessResult>({diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.tsindex d4d8b49e8..032c3c1a2 100644--- a/sdk/javascript/src/types.ts+++ b/sdk/javascript/src/types.ts@@ -188,6 +188,12 @@ export interface PinMessageRequest {durationSeconds?: PinDurationSeconds;}+export interface ArchiveChatRequest {+ chatId: Jid;+ /** true to archive, false to unarchive. */+ archive: boolean;+}+export interface StarMessageRequest {chatId: Jid;messageId: string;diff --git a/sdk/javascript/test/resources.test.ts b/sdk/javascript/test/resources.test.tsindex 888f4a502..dcaead26d 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.archive', () => {+ it('posts chatId and the archive flag', async () => {+ const t = new MockTransport().on('POST', /\/chats\/archive$/, { body: { success: true } });+ await client(t).chats.archive('s', { chatId: '[email protected]', archive: true });+ expect(t.lastCall!.url).toBe('http://x/api/sessions/s/chats/archive');+ expect(t.lastCall!.body).toEqual({ chatId: '[email protected]', archive: true });+ });+});+describe('HealthResource + auth — exact paths', () => {it('health/live/ready and auth validate', async () => {const t = new MockTransport()diff --git a/sdk/php/src/Resources/ChatsResource.php b/sdk/php/src/Resources/ChatsResource.phpindex 343d6f8a3..1ce46f4fa 100644--- a/sdk/php/src/Resources/ChatsResource.php+++ b/sdk/php/src/Resources/ChatsResource.php@@ -45,6 +45,18 @@ class ChatsResourcereturn $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/chats/unread", [], $body);}+ /**+ * Archive or unarchive a chat. A false `success` means the engine declined — on Baileys a chat+ * with no known history cannot be archived.+ *+ * @param array<string,mixed> $body chatId and archive (bool).+ * @return array<string,mixed>+ */+ public function archive(string $sessionId, array $body): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/chats/archive", [], $body) ?? [];+ }+/** @return array<string,mixed> */public function delete(string $sessionId, array $body): array{diff --git a/sdk/php/tests/ResourcesTest.php b/sdk/php/tests/ResourcesTest.phpindex 0954206ca..bc18ff3c0 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 testChatsArchive(): void+ {+ $backend = new MockBackend();+ $backend->on(200, ['success' => true]);+ $client = $backend->makeClient();+ $client->chats->archive('s', ['chatId' => '[email protected]', 'archive' => true]);+ $this->assertSame('/api/sessions/s/chats/archive', $backend->lastCall()['path']);+ $this->assertSame('POST', $backend->lastCall()['method']);+ }+// ── Status (Stories) ──────────────────────────────────────────────public function testStatusSendForwardsRequiredRecipientsAndNestedMedia(): voiddiff --git a/sdk/python/openwa/resources/chats.py b/sdk/python/openwa/resources/chats.pyindex 8aa5c1bae..102fc4c47 100644--- a/sdk/python/openwa/resources/chats.py+++ b/sdk/python/openwa/resources/chats.py@@ -10,6 +10,7 @@ from typing import TYPE_CHECKING, TypedDictfrom .._http import quote_segmentfrom ..types import (+ ArchiveChatRequest,ChatSummary,DeleteChatRequest,MarkChatRequest,@@ -39,6 +40,10 @@ class ChatsResource:def mark_unread(self, session_id: str, body: MarkChatRequest) -> SuccessResult:return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/chats/unread", body=body)+ def archive(self, session_id: str, body: ArchiveChatRequest) -> SuccessResult:+ """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 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/openwa/types.py b/sdk/python/openwa/types.pyindex 1f3681999..20fab5e30 100644--- a/sdk/python/openwa/types.py+++ b/sdk/python/openwa/types.py@@ -638,6 +638,13 @@ class PinMessageRequest(TypedDict, total=False):durationSeconds: int+class ArchiveChatRequest(TypedDict):+ """Archive or unarchive a chat."""++ chatId: str+ archive: bool++class StarMessageRequest(TypedDict):"""Star or unstar a message. Best-effort on whatsapp-web.js."""diff --git a/sdk/python/tests/test_sdk.py b/sdk/python/tests/test_sdk.pyindex 689b418b1..907bcc0a5 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_archive(self):+ backend = MockBackend().on("POST", "/chats/archive", body={"success": True})+ make_client(backend).chats.archive("s", {"chatId": "[email protected]", "archive": True})+ assert backend.last_call.url == "http://localhost:2785/api/sessions/s/chats/archive"+ assert backend.last_call.body == {"chatId": "[email protected]", "archive": True}+def test_health_and_auth(self):backend = MockBackend()backend.on("GET", "/api/health", body={"status": "ok", "version": "0.7.2"})diff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.tsindex ac2b7e7c0..16faf46be 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 archiveChat(chatId: string, archive: boolean): Promise<boolean> {+ this.host.ensureReady();+ const last = this.host.lastMessage(chatId);+ if (!last) {+ return false; // Baileys' archive toggle needs the last message; can't synthesize it+ }+ await this.sock().chatModify(+ { archive, lastMessages: [{ key: last.key, messageTimestamp: last.timestamp }] },+ chatId,+ );+ 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.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 6f671714e..4799c7932 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -3713,6 +3713,31 @@ describe('BaileysAdapter sendSeen + markUnread + deleteChat', () => {expect(await adapter.deleteChat('[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);+ expect(ok).toBe(true);+ expect(fakeSock.chatModify).toHaveBeenCalledWith(+ {+ archive,+ lastMessages: [+ { key: { remoteJid: '[email protected]', fromMe: false, id: 'M1' }, messageTimestamp: 1700000020 },+ ],+ },+ '[email protected]',+ );+ });++ it('archiveChat returns false for a chat with no known history, rather than throwing', async () => {+ // The app-state modification is keyed to the chat's last message; there is nothing to+ // synthesize one from, so this is a defined outcome the endpoint reports as success:false.+ const adapter = newAdapter();+ await adapter.initialize({});+ fakeSock.fire('connection.update', { connection: 'open' });+ expect(await adapter.archiveChat('[email protected]', true)).toBe(false);+ expect(fakeSock.chatModify).not.toHaveBeenCalled();+ });});describe('BaileysAdapter status posting', () => {diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex 3742c755b..aa25a84bf 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -476,6 +476,10 @@ export class BaileysAdapter implements IWhatsAppEngine {return this.contacts.deleteChat(chatId);}+ async archiveChat(chatId: string, archive: boolean): Promise<boolean> {+ return this.contacts.archiveChat(chatId, archive);+ }+// ----- 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.tsindex a191e418b..86c62bfe5 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -744,6 +744,29 @@ describe('WhatsAppWebJsAdapter channel-JID guard (#554 — wwebjs Channel lacks});});+ describe('archiveChat', () => {+ it('archives via Client.archiveChat, not Chat.archive (which resolves void)', async () => {+ const archiveChat = jest.fn().mockResolvedValue(true);+ const unarchiveChat = jest.fn().mockResolvedValue(true);+ await expect(readyAdapter({ archiveChat, unarchiveChat }).archiveChat(USER, true)).resolves.toBe(true);+ expect(archiveChat).toHaveBeenCalledWith(USER);+ expect(unarchiveChat).not.toHaveBeenCalled();+ });++ it('unarchives via Client.unarchiveChat', async () => {+ const archiveChat = jest.fn().mockResolvedValue(true);+ const unarchiveChat = jest.fn().mockResolvedValue(false);+ await expect(readyAdapter({ archiveChat, unarchiveChat }).archiveChat(USER, false)).resolves.toBe(false);+ expect(unarchiveChat).toHaveBeenCalledWith(USER);+ expect(archiveChat).not.toHaveBeenCalled();+ });++ it('reports false instead of throwing when the engine call fails', async () => {+ const archiveChat = jest.fn().mockRejectedValue(new Error('Evaluation failed'));+ await expect(readyAdapter({ archiveChat }).archiveChat(USER, true)).resolves.toBe(false);+ });+ });+describe('getChatLabels', () => {it('returns [] on a newsletter JID instead of throwing (was an unguarded HTTP 500)', async () => {const getChatById = jest.fn();diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex 9fb6ec6cf..ae6a3360d 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -1573,6 +1573,10 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginreturn this.chats.sendSeen(chatId);}+ archiveChat(chatId: string, archive: boolean): Promise<boolean> {+ return this.chats.archiveChat(chatId, archive);+ }+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.tsindex 2fc3d4172..49b7864fb 100644--- a/src/engine/adapters/wwebjs-chats.ts+++ b/src/engine/adapters/wwebjs-chats.ts@@ -68,6 +68,18 @@ export class WwebjsChats {}}+ async archiveChat(chatId: string, archive: boolean): Promise<boolean> {+ this.host.ensureReady();+ try {+ // Client.archiveChat/unarchiveChat, NOT Chat.archive() — the Chat method resolves void, so it+ // gives nothing to report back; the client pair resolves the chat's new pin/archive state.+ return archive ? await this.client().archiveChat(chatId) : await this.client().unarchiveChat(chatId);+ } catch (error) {+ this.host.logger.error(`Error ${archive ? 'archiving' : 'unarchiving'} chat ${chatId}`, String(error));+ return false;+ }+ }+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 5935afa67..5e05eb03a 100644--- a/src/engine/engine-capability-matrix.ts+++ b/src/engine/engine-capability-matrix.ts@@ -62,6 +62,12 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {evidence:"wwjs GroupChat.addParticipants → per-participant {code,message} object, or a reason STRING on batch refusal (index.d.ts:2184; GroupChat.js:78-264) — both mapped at the adapter; baileys groupParticipantsUpdate(jid,pids,'add') → per-jid [{status:'200'|error}] (Socket/groups.js:140-156); per-participant results surface on the HTTP `results` field, a total refusal throws",},+ archiveChat: {+ wwjs: { status: 'supported' },+ baileys: { status: 'supported' },+ evidence:+ "wwjs Client.archiveChat(chatId)/unarchiveChat(chatId) → Promise<boolean> (index.d.ts:46,328) — the CLIENT methods, not Chat.archive(), which resolves void; baileys chatModify({archive,lastMessages}, jid) (Types/Chat.d.ts:63-66) needs the chat's last message, so a chat with no known history resolves false rather than throwing",+ },blockContact: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },checkNumberExists: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },createGroup: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex b183e339d..463ae847d 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -780,6 +780,12 @@ export interface IWhatsAppEngine {sendSeen(chatId: string): Promise<boolean>;markUnread(chatId: string): Promise<boolean>;deleteChat(chatId: string): Promise<boolean>;+ /**+ * Archive or unarchive a chat. Resolves false when the engine cannot act — on Baileys the+ * archive is an app-state modification keyed to the chat's last message, so a chat with no known+ * history cannot be archived at all. Same shape as deleteChat/markUnread, which share that limit.+ */+ archiveChat(chatId: string, archive: boolean): 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/dto/archive-chat.dto.ts b/src/modules/session/dto/archive-chat.dto.tsnew file mode 100644index 000000000..a7c88211f--- /dev/null+++ b/src/modules/session/dto/archive-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 ArchiveChatDto {+ @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 archive, false to unarchive.' })+ // Read strictly: under the pipe's implicit conversion the string "false" would become boolean+ // true, archiving a chat the caller asked to restore.+ @ToStrictBoolean()+ @IsBoolean()+ archive: boolean;+}diff --git a/src/modules/session/dto/index.ts b/src/modules/session/dto/index.tsindex 7a942c78d..fd280f220 100644--- a/src/modules/session/dto/index.ts+++ b/src/modules/session/dto/index.ts@@ -1,6 +1,7 @@export * from './create-session.dto';export * from './session-response.dto';export * from './mark-chat-read.dto';+export * from './archive-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/session.controller.ts b/src/modules/session/session.controller.tsindex 0f19d0126..8b5a60e05 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -6,6 +6,7 @@ import {SessionResponseDto,QRCodeResponseDto,MarkChatReadDto,+ ArchiveChatDto,DeleteChatDto,SendChatStateDto,RequestPairingCodeDto,@@ -360,6 +361,27 @@ export class SessionController {return { success };}+ @Post(':id/chats/archive')+ @RequireRole(ApiKeyRole.OPERATOR)+ @HttpCode(HttpStatus.OK)+ @ApiOperation({ summary: 'Archive or unarchive a chat' })+ @ApiParam({ name: 'id', description: 'Session ID' })+ @ApiResponse({+ status: 200,+ description:+ 'Returns `{ success }`. `false` means the engine declined to act — on the Baileys engine a ' ++ 'chat with no known history cannot be archived, since the change is keyed to its last message.',+ })+ @ApiResponse({ status: 400, description: 'Session not ready' })+ @ApiResponse({ status: 404, description: 'Session not found' })+ async archiveChat(+ @Param('id', ParseUUIDPipe) id: string,+ @Body() dto: ArchiveChatDto,+ ): Promise<{ success: boolean }> {+ const success = await this.sessionService.archiveChat(id, dto.chatId, dto.archive);+ 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 ad4382aed..318af498e 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -356,6 +356,22 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatreturn engine.markUnread(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+ * defined outcome, not an error, so it is reported as `success: false` rather than a 500.+ */+ async archiveChat(id: string, chatId: string, archive: 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.archiveChat(chatId, archive);+ }+async deleteChat(id: string, chatId: string): Promise<boolean> {await this.findOne(id); // Verify session existsconst engine = this.engines.get(id);