Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(labels): create, update and delete labels; list a label's chats
Yudhi Armyndharisc7ebfc0dea20
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b4b65bb5d..ef1a96165 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -24,6 +24,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- **Labels can now be created, renamed, recoloured and deleted** — `PUT` and+ `DELETE /api/sessions/:sessionId/labels/:labelId` — and **listed by chat**:+ `GET /api/sessions/:sessionId/labels/:labelId/chats`. All five SDKs gain the matching methods.++ The two engines split down the middle and neither covers both halves, so this is honest about+ which is which rather than pretending at parity. whatsapp-web.js can read labels and assign them+ but cannot edit one — `index.d.ts` has no create/rename/delete of any kind — so the edits answer+ `501` there. Baileys is the mirror image: it has the writes and no label query whatsoever, so+ listing a label's chats answers `501` on it. Assigning a label to a chat is the only part that+ works everywhere.++ **Creating a label means choosing its id**, which is why the route is `PUT /labels/:labelId` and not+ `POST /labels`. WhatsApp carries one write keyed on the label id, so create and update are the same+ operation and there is no server-assigned id to return — reusing an existing id rewrites that+ label rather than failing, because the protocol has no create-only form. Saying so is better than+ a `POST` that implies a guarantee nothing can keep.++ `color` is WhatsApp's colour **index** (0–19), not the `hexColor` the read routes return. The two+ deliberately do not round-trip: neither engine exposes the mapping, so translating between them+ would be guesswork that silently sets the wrong colour.+- **Presence: see who is online or typing.** `POST /api/sessions/:id/presence/subscribe` startsWhatsApp reporting a chat's presence; `GET /api/sessions/:id/presence/:chatId` serves the latestreport; changes arrive as the new `presence.update` webhook **and** socket event. Exposed in alldiff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex fdca85212..d69842531 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -3240,7 +3240,22 @@ Note: this is the one route in the module that returns a literal `{ success: truLabels are a WhatsApp Business feature: every label route lives under a session and reads/writes the chat-label assignments exposed by the engine. Status routes manage the session's status feed (stories) — reading visible statuses and posting/deleting your own. Read routes require a base API key; all writes require `OPERATOR`.-**Label reads are whatsapp-web.js only.** `GET /labels`, `GET /labels/:labelId` and `GET /labels/chat/:chatId` throw `501` on the Baileys engine, which exposes no label query (the library only has the association *writes*). Adding/removing a chat label works on both engines.+**The two engines split cleanly down the middle here, and neither covers both halves.**++| | whatsapp-web.js | Baileys |+|---|---|---|+| Read labels (`GET /labels`, `/labels/:labelId`, `/labels/chat/:chatId`, `/labels/:labelId/chats`) | ✅ | `501` — exposes no label query at all |+| Edit labels (`PUT`/`DELETE /labels/:labelId`) | `501` — can read and assign, but cannot edit one | ✅ |+| Assign to a chat (`POST`/`DELETE /labels/chat/…`) | ✅ | ✅ |++So a deployment can read labels or edit them, depending on the engine, but not both. Assignment is+the only part that works everywhere. This is a library split, not a gateway one — see+`docs/29-engine-capability-matrix.md` for the symbols behind each cell.++**Creating a label means choosing its id.** WhatsApp carries a single write keyed on the label id, so+create and update are the same operation and there is no server-assigned id to hand back — which is+why the route is `PUT /labels/:labelId` rather than `POST /labels`. Reusing an existing id **rewrites+that label** instead of failing, because the protocol has no create-only form.**Reads are store-backed, not engine-direct.** `GET /status` and `GET /status/:contactId` no longer call the engine — they read from an OpenWA-side store that ingests inbound status/story broadcasts as they arrive (plus a best-effort backfill of currently-active stories on session connect), with a 24h TTL matching WhatsApp's own story expiry. This makes reads **identical on both engines**: `whatsapp-web.js` (which had a native `getBroadcasts()`/`getBroadcastById()` path) and Baileys (which never had one — `fetchStatus` only returns the *about* text, not stories, so the raw engine methods still throw `501` if called directly, they're just no longer on the read path) now return the same shape from the same source. A status older than 24h, or received before the store existed, will not appear.@@ -3292,6 +3307,64 @@ The engine resolves `Label | null`; a `null` is mapped to `404` in the service,**Errors:** `400` session is not started · `401` missing/invalid API key · `404` `Label <labelId> not found` · `501` the Baileys engine does not implement label reads (whatsapp-web.js only)+#### GET /api/sessions/:sessionId/labels/:labelId/chats++Every chat carrying a label.++**Auth:** API key · **Scope:** session-scoped · **Engines:** whatsapp-web.js only++**Response** `200` — a bare array of `ChatSummary`, the same shape `GET /sessions/:id/chats` returns.++**Errors:** `400` session not started · `401` · `404` session not found · `501` Baileys, which has no label query++#### PUT /api/sessions/:sessionId/labels/:labelId++Create or update a label.++**Auth:** API key (OPERATOR) · **Scope:** session-scoped · **Engines:** Baileys only++The label id is **yours to choose** and travels in the path. Whether this creates or updates depends+only on whether that id already exists — reusing one rewrites that label rather than failing.+Omitted fields are left as they are.++**Request body** — `UpsertLabelDto`++| Field | Type | Required | Constraints | Description |+| --- | --- | --- | --- | --- |+| `name` | string | No | 1–100 chars | Omit to keep the current name |+| `color` | number | No | integer 0–19 | WhatsApp's colour **index**, not a hex value |++`color` deliberately does not round-trip with the `hexColor` the read routes return: neither engine+exposes the index-to-hex mapping — whatsapp-web.js passes hex through from the WA Web store and+Baileys only ever speaks in indices — so translating between them here would be guesswork that+silently sets the wrong colour.++```json+{ "name": "VIP customer", "color": 3 }+```++**Response** `200`++```json+{ "success": true }+```++**Errors:** `400` validation, or session not started · `401` · `403` · `404` session not found · `501` whatsapp-web.js, which cannot edit labels++#### DELETE /api/sessions/:sessionId/labels/:labelId++Delete a label. It disappears from every chat it was on.++**Auth:** API key (OPERATOR) · **Scope:** session-scoped · **Engines:** Baileys only++**Response** `200`++```json+{ "success": true }+```++**Errors:** `400` session not started · `401` · `403` · `404` session not found · `501` whatsapp-web.js, which cannot edit labels+#### GET /api/sessions/:sessionId/labels/chat/:chatIdList the labels currently assigned to a specific chat.diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.mdindex 69b262045..473f9c86e 100644--- a/docs/29-engine-capability-matrix.md+++ b/docs/29-engine-capability-matrix.md@@ -144,7 +144,9 @@ _✅ #17 `getProduct` — wired on Baileys (#905); see §Catalog / Products / OrThese are honestly out of reach of a clean adapter wiring because the installed library exposes no first-class symbol. Listed so operators can plan around them rather than file unactionable bugs.-**baileys (10 cells):**+**baileys (11 cells):**++- `getChatsByLabel` — label WRITES only (`Socket/chats.d.ts:69-73`: `addLabel`, `addChatLabel`, `removeChatLabel`); there is no label query of any kind and `Types/Label.d.ts` is types-only. Listing a label's chats needs an app-state cache fed by the label-association sync events, which is its own piece of work. whatsapp-web.js: `Client.getChatsByLabelId`.- `getSubscribedChannels` — no enumerate-newsletters query; all 19 newsletter members of `Socket/newsletter.d.ts` address a single newsletter (by jid, by invite key, or by creating one). Needs a raw WMex/app-state hack.- `getLabels` / `getLabelById` / `getChatLabels` — no label read symbol; only writes (`Types/Label.d.ts` is types-only). Workaround: capture labels from the `messaging-history.set` app-state event into an in-memory cache (relay hack, no on-demand refresh).@@ -154,7 +156,9 @@ These are honestly out of reach of a clean adapter wiring because the installed- `sendCatalog` — no catalog-share message type in `AnyMessageContent` (only single `{product}`).- `votePoll` — no vote-SEND helper at all; the library only decrypts INCOMING votes (`decryptPollVote`). Sending one means hand-building a `proto.Message.PollUpdateMessage` with HMAC-SHA256 vote encryption keyed by the poll creation's `messageSecret`. Supported on whatsapp-web.js.-**wwjs (7 cells):**+**wwjs (9 cells):**++- `upsertLabel` / `deleteLabel` — whatsapp-web.js 1.34.7 can READ labels and assign them, but cannot edit one: `index.d.ts:129-154` exposes `getLabels`, `getLabelById`, `getChatLabels`, `getChatsByLabelId` and `addOrRemoveLabels`, and nothing that creates, renames, recolours or deletes a label. Baileys: one `addLabel` write covering all four.- `subscribeToPresence` — no way to observe another party's presence. `WAWebPresenceChatAction` offers only `sendPresenceAvailable` / `sendPresenceUnavailable` (`index.d.ts:230,233`), which publish the ACCOUNT's own presence, and the library emits no presence event at all. Baileys: `presenceSubscribe` + the `presence.update` event. Reaching it would mean injecting page-level subscriptions against undocumented WA Web modules.- `getCatalog` / `getProducts` / `getProduct` — no catalog API at all (`index.d.ts` 0 hits; `Product` is inbound-only).@@ -170,9 +174,9 @@ 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.-- **92** interface methods, **184** adapter-cells (92 × 2 engines).-- **165** supported cells; **19** not-available cells across **18** methods.-- Of the 19 not-available cells: **2 adapter-gaps** (fixable) + **17 library-limitations** + **0 uncertain**.+- **95** interface methods, **190** adapter-cells (95 × 2 engines).+- **168** supported cells; **22** not-available cells across **21** methods.+- Of the 22 not-available cells: **2 adapter-gaps** (fixable) + **20 library-limitations** + **0 uncertain**.- **0 phantom-support rows** — every `not-available` row throws at the adapter boundary.Note that the drift gate does **not** verify that for whatsapp-web.js. `engine-parity.spec.ts`diff --git a/openapi.json b/openapi.jsonindex 2327233c4..abc0d884f 100644--- a/openapi.json+++ b/openapi.json@@ -4487,6 +4487,135 @@"tags": ["labels"]+ },+ "put": {+ "description": "Baileys only. `PUT` rather than `POST` because the label id is chosen by the caller: WhatsApp carries one `label_edit` write keyed on that id, so whether this creates or updates depends purely on whether the id already exists, and there is no server-assigned id to return.\n\n**Choose an unused id to create.** Reusing one silently rewrites that label rather than failing, because the protocol has no create-only form. Fields left out are left alone.\n\nwhatsapp-web.js can read and assign labels but cannot edit one, and answers `501`.",+ "operationId": "LabelController_upsertLabel",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "labelId",+ "required": true,+ "in": "path",+ "description": "Label ID — caller-chosen",+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/UpsertLabelDto"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Label created or updated"+ },+ "400": {+ "description": "Session not started, or validation failed"+ },+ "501": {+ "description": "The active engine cannot edit labels (whatsapp-web.js)"+ }+ },+ "summary": "Create or update a label",+ "tags": [+ "labels"+ ]+ },+ "delete": {+ "description": "Baileys only. The label disappears from every chat it was on. whatsapp-web.js cannot edit labels and answers `501`.",+ "operationId": "LabelController_deleteLabel",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "labelId",+ "required": true,+ "in": "path",+ "description": "Label ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Label deleted"+ },+ "400": {+ "description": "Session not started"+ },+ "501": {+ "description": "The active engine cannot edit labels (whatsapp-web.js)"+ }+ },+ "summary": "Delete a label",+ "tags": [+ "labels"+ ]+ }+ },+ "/api/sessions/{sessionId}/labels/{labelId}/chats": {+ "get": {+ "description": "whatsapp-web.js only. Baileys exposes label writes but no label query of any kind, so it answers `501`.",+ "operationId": "LabelController_getChatsByLabel",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "labelId",+ "required": true,+ "in": "path",+ "description": "Label ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Chats carrying the label"+ },+ "400": {+ "description": "Session not started"+ },+ "501": {+ "description": "The active engine cannot list chats by label (Baileys)"+ }+ },+ "summary": "Get every chat carrying a label",+ "tags": [+ "labels"+ ]}},"/api/sessions/{sessionId}/labels/chat/{chatId}": {@@ -8533,6 +8662,25 @@}}},+ "UpsertLabelDto": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string",+ "description": "Label name. Omit to leave the current name untouched.",+ "example": "VIP customer",+ "minLength": 1,+ "maxLength": 100+ },+ "color": {+ "type": "number",+ "description": "WhatsApp's colour INDEX (0-19), not a hex value — the read path's `hexColor` cannot be translated back, because neither engine exposes the mapping. Omit to leave the colour alone.",+ "example": 3,+ "minimum": 0,+ "maximum": 19+ }+ }+ },"SendTextStatusDto": {"type": "object","properties": {diff --git a/sdk/go/labels.go b/sdk/go/labels.goindex 3c0a82e06..f9c86ee8a 100644--- a/sdk/go/labels.go+++ b/sdk/go/labels.go@@ -27,6 +27,34 @@ func (s *LabelsService) Get(ctx context.Context, sessionID, labelID string) (*Lareturn &out, nil}+// Chats returns every chat carrying a label.+//+// whatsapp-web.js only — Baileys has label writes but no label query of any kind, and answers 501.+func (s *LabelsService) Chats(ctx context.Context, sessionID, labelID string) ([]ChatSummary, error) {+ var out []ChatSummary+ err := s.client.do(ctx, "GET", s.base(sessionID)+"/"+pathEscape(labelID)+"/chats", nil, nil, &out)+ return out, err+}++// Upsert creates or updates a label. Baileys only; whatsapp-web.js can read and assign labels but+// cannot edit one, and answers 501.+//+// PUT rather than POST because the caller chooses the id: WhatsApp carries one write keyed on it, so+// whether this creates or updates depends purely on whether that id already exists. Pick an unused+// id to create — reusing one rewrites that label rather than failing. Omitted fields are left alone.+func (s *LabelsService) Upsert(ctx context.Context, sessionID, labelID string, body UpsertLabelRequest) (*SuccessResult, error) {+ var out SuccessResult+ err := s.client.do(ctx, "PUT", s.base(sessionID)+"/"+pathEscape(labelID), nil, body, &out)+ return &out, err+}++// Delete removes a label; it disappears from every chat it was on. Baileys only.+func (s *LabelsService) Delete(ctx context.Context, sessionID, labelID string) (*SuccessResult, error) {+ var out SuccessResult+ err := s.client.do(ctx, "DELETE", s.base(sessionID)+"/"+pathEscape(labelID), nil, nil, &out)+ return &out, err+}+// ForChat returns the labels applied to a chat.func (s *LabelsService) ForChat(ctx context.Context, sessionID, chatID string) ([]LabelRecord, error) {var out []LabelRecorddiff --git a/sdk/go/routing_test.go b/sdk/go/routing_test.goindex 23e57ef1d..c5332461d 100644--- a/sdk/go/routing_test.go+++ b/sdk/go/routing_test.go@@ -91,6 +91,9 @@ 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.SubscribePresence", func(c *Client) { c.Chats.SubscribePresence(ctx, "s1", MarkChatRequest{}) }, "POST", "/api/sessions/s1/presence/subscribe"},+ {"Labels.Chats", func(c *Client) { c.Labels.Chats(ctx, "s1", "l1") }, "GET", "/api/sessions/s1/labels/l1/chats"},+ {"Labels.Upsert", func(c *Client) { c.Labels.Upsert(ctx, "s1", "l1", UpsertLabelRequest{}) }, "PUT", "/api/sessions/s1/labels/l1"},+ {"Labels.Delete", func(c *Client) { c.Labels.Delete(ctx, "s1", "l1") }, "DELETE", "/api/sessions/s1/labels/l1"},{"Chats.GetPresence", func(c *Client) { c.Chats.GetPresence(ctx, "s1", "[email protected]") }, "GET", "/api/sessions/s1/presence/[email protected]"},{"Chats.MarkUnread", func(c *Client) { c.Chats.MarkUnread(ctx, "s1", MarkChatRequest{}) }, "POST", "/api/sessions/s1/chats/unread"},{"Chats.ClearMessages", func(c *Client) { c.Chats.ClearMessages(ctx, "s1", "c1") }, "DELETE", "/api/sessions/s1/chats/c1/messages"},diff --git a/sdk/go/types_session.go b/sdk/go/types_session.goindex 5c8a75550..69348ac94 100644--- a/sdk/go/types_session.go+++ b/sdk/go/types_session.go@@ -15,6 +15,17 @@ func (q *ListSessionsQuery) values() url.Values {return v}+// UpsertLabelRequest is a label create-or-update body. The id travels in the path, because WhatsApp+// keys the write on it.+type UpsertLabelRequest struct {+ // Name is left alone when nil.+ Name *string `json:"name,omitempty"`+ // Color is WhatsApp's colour INDEX (0-19), NOT a hex value — it does not round-trip with the+ // HexColor labels are read back with, because neither engine exposes the mapping. Nil leaves the+ // current colour alone.+ Color *int `json:"color,omitempty"`+}+// ParticipantPresence is one participant's presence within a chat.type ParticipantPresence struct {ID string `json:"id"`diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/UpsertLabelRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/UpsertLabelRequest.javanew file mode 100644index 000000000..4a338a3a6--- /dev/null+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/UpsertLabelRequest.java@@ -0,0 +1,11 @@+package com.rmyndharis.openwa.model;++/**+ * A label create-or-update body. The id travels in the path, because WhatsApp keys the write on it.+ *+ * @param name {@code null} leaves the current name alone+ * @param color WhatsApp's colour INDEX (0-19), NOT a hex value — it does not round-trip with the+ * {@code hexColor} labels are read back with, because neither engine exposes the mapping;+ * {@code null} leaves the current colour alone+ */+public record UpsertLabelRequest(String name, Integer color) {}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/LabelsResource.java b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/LabelsResource.javaindex c279c037d..6d9a3e2e2 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/LabelsResource.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/LabelsResource.java@@ -5,7 +5,9 @@ import static com.rmyndharis.openwa.http.Http.encodeSegment;import com.rmyndharis.openwa.OpenWAClient;import com.rmyndharis.openwa.http.HttpMethod;import com.rmyndharis.openwa.model.AddLabelRequest;+import com.rmyndharis.openwa.model.ChatSummary;import com.rmyndharis.openwa.model.LabelRecord;+import com.rmyndharis.openwa.model.UpsertLabelRequest;import com.rmyndharis.openwa.model.SuccessResult;import java.util.List;@@ -37,6 +39,47 @@ public final class LabelsResource {LabelRecord.class);}+ /**+ * Every chat carrying a label. whatsapp-web.js only — Baileys has label writes but no label query+ * of any kind, and answers {@code 501}.+ */+ public List<ChatSummary> chats(String sessionId, String labelId) {+ return client.requestList(+ HttpMethod.GET,+ "/api/sessions/" + encodeSegment(sessionId) + "/labels/" + encodeSegment(labelId) + "/chats",+ null,+ null,+ ChatSummary.class);+ }++ /**+ * Create or update a label. Baileys only; whatsapp-web.js can read and assign labels but cannot+ * edit one, and answers {@code 501}.+ *+ * <p>{@code PUT} rather than {@code POST} because you choose the id: WhatsApp carries one write+ * keyed on it, so whether this creates or updates depends purely on whether that id already+ * exists. Pick an unused id to create — reusing one rewrites that label rather than failing.+ * Omitted fields are left alone.+ */+ public SuccessResult upsert(String sessionId, String labelId, UpsertLabelRequest body) {+ return client.request(+ HttpMethod.PUT,+ "/api/sessions/" + encodeSegment(sessionId) + "/labels/" + encodeSegment(labelId),+ null,+ body,+ SuccessResult.class);+ }++ /** Delete a label; it disappears from every chat it was on. Baileys only. */+ public SuccessResult delete(String sessionId, String labelId) {+ return client.request(+ HttpMethod.DELETE,+ "/api/sessions/" + encodeSegment(sessionId) + "/labels/" + encodeSegment(labelId),+ null,+ null,+ SuccessResult.class);+ }+/** Get the labels currently applied to a chat. */public List<LabelRecord> forChat(String sessionId, String chatId) {return client.requestList(diff --git a/sdk/javascript/src/resources/labels.ts b/sdk/javascript/src/resources/labels.tsindex 229d858ac..0aaf101d7 100644--- a/sdk/javascript/src/resources/labels.ts+++ b/sdk/javascript/src/resources/labels.ts@@ -8,7 +8,7 @@import { encodeSegment } from '../http.js';import type { OpenWAClient } from '../client.js';-import type { AddLabelRequest, LabelRecord, SuccessResult } from '../types.js';+import type { AddLabelRequest, ChatSummary, LabelRecord, SuccessResult, UpsertLabelRequest } from '../types.js';export class LabelsResource {constructor(private readonly client: OpenWAClient) {}@@ -29,6 +29,41 @@ export class LabelsResource {});}+ /**+ * Every chat carrying a label. **whatsapp-web.js only** — Baileys has label writes but no label+ * query of any kind, and answers 501.+ */+ chats(sessionId: string, labelId: string): Promise<ChatSummary[]> {+ return this.client.request<ChatSummary[]>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/labels/${encodeSegment(labelId)}/chats`,+ });+ }++ /**+ * Create or update a label. **Baileys only** — whatsapp-web.js can read and assign labels but+ * cannot edit one, and answers 501.+ *+ * `PUT`, not `POST`, because you choose the id: WhatsApp carries one write keyed on it, so whether+ * this creates or updates depends purely on whether that id already exists. Pick an unused id to+ * create — reusing one rewrites that label rather than failing. Omitted fields are left alone.+ */+ upsert(sessionId: string, labelId: string, body: UpsertLabelRequest): Promise<SuccessResult> {+ return this.client.request<SuccessResult>({+ method: 'PUT',+ path: `/api/sessions/${encodeSegment(sessionId)}/labels/${encodeSegment(labelId)}`,+ body,+ });+ }++ /** Delete a label; it disappears from every chat it was on. **Baileys only.** */+ delete(sessionId: string, labelId: string): Promise<SuccessResult> {+ return this.client.request<SuccessResult>({+ method: 'DELETE',+ path: `/api/sessions/${encodeSegment(sessionId)}/labels/${encodeSegment(labelId)}`,+ });+ }+/** Get the labels currently applied to a chat. */forChat(sessionId: string, chatId: string): Promise<LabelRecord[]> {return this.client.request<LabelRecord[]>({diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.tsindex 52d801e75..45c4de8a3 100644--- a/sdk/javascript/src/types.ts+++ b/sdk/javascript/src/types.ts@@ -99,6 +99,20 @@ export interface ChatPresence {observedAt: string;}+/**+ * A label create-or-update body. The id travels in the path, because WhatsApp keys the write on it.+ */+export interface UpsertLabelRequest {+ /** Leave out to keep the current name. */+ name?: string;+ /**+ * WhatsApp's colour INDEX (0-19), NOT a hex value — it does not round-trip with the `hexColor`+ * labels are read back with, because neither engine exposes the mapping. Leave out to keep the+ * current colour.+ */+ color?: number;+}+export interface CreateSessionRequest {/** Alphanumeric + hyphens, 3–50 chars. */name: string;diff --git a/sdk/php/src/Resources/LabelsResource.php b/sdk/php/src/Resources/LabelsResource.phpindex 639113f14..a7a05ed7e 100644--- a/sdk/php/src/Resources/LabelsResource.php+++ b/sdk/php/src/Resources/LabelsResource.php@@ -33,6 +33,43 @@ class LabelsResourcereturn $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/labels/{$this->http->encodeSegment($labelId)}");}+ /**+ * Every chat carrying a label. whatsapp-web.js only — Baileys has label writes but no label+ * query of any kind, and answers 501.+ *+ * @return array<int,array<string,mixed>>+ */+ public function chats(string $sessionId, string $labelId): array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/labels/{$this->http->encodeSegment($labelId)}/chats") ?? [];+ }++ /**+ * Create or update a label. Baileys only; whatsapp-web.js answers 501.+ *+ * PUT rather than POST because you choose the id: WhatsApp carries one write keyed on it, so+ * whether this creates or updates depends purely on whether that id already exists. Pick an+ * unused id to create — reusing one rewrites that label rather than failing. Omitted fields are+ * left alone.+ *+ * @param array<string,mixed> $body+ * @return array<string,mixed>+ */+ public function upsert(string $sessionId, string $labelId, array $body): array+ {+ return $this->http->request('PUT', "/api/sessions/{$this->http->encodeSegment($sessionId)}/labels/{$this->http->encodeSegment($labelId)}", [], $body);+ }++ /**+ * Delete a label; it disappears from every chat it was on. Baileys only.+ *+ * @return array<string,mixed>+ */+ public function delete(string $sessionId, string $labelId): array+ {+ return $this->http->request('DELETE', "/api/sessions/{$this->http->encodeSegment($sessionId)}/labels/{$this->http->encodeSegment($labelId)}");+ }+/** @return array<int,array<string,mixed>> */public function forChat(string $sessionId, string $chatId): array{diff --git a/sdk/python/openwa/resources/labels.py b/sdk/python/openwa/resources/labels.pyindex f59efbe88..b0b33043f 100644--- a/sdk/python/openwa/resources/labels.py+++ b/sdk/python/openwa/resources/labels.py@@ -10,7 +10,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKINGfrom .._http import quote_segment-from ..types import AddLabelRequest, LabelRecord, SuccessResult+from ..types import AddLabelRequest, ChatSummary, LabelRecord, SuccessResult, UpsertLabelRequestif TYPE_CHECKING:from .._http import HttpExecutor@@ -26,6 +26,34 @@ class LabelsResource:def get(self, session_id: str, label_id: str) -> LabelRecord:return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/labels/{quote_segment(label_id)}")+ def chats(self, session_id: str, label_id: str) -> list[ChatSummary]:+ """Every chat carrying a label.++ whatsapp-web.js only -- Baileys has label writes but no label query of any kind, and+ answers 501.+ """+ return self._http.request(+ "GET", f"/api/sessions/{quote_segment(session_id)}/labels/{quote_segment(label_id)}/chats"+ )++ def upsert(self, session_id: str, label_id: str, body: UpsertLabelRequest) -> SuccessResult:+ """Create or update a label. Baileys only; whatsapp-web.js answers 501.++ PUT rather than POST because you choose the id: WhatsApp carries one write keyed on it, so+ whether this creates or updates depends purely on whether that id already exists. Pick an+ unused id to create -- reusing one rewrites that label rather than failing. Omitted fields+ are left alone.+ """+ return self._http.request(+ "PUT", f"/api/sessions/{quote_segment(session_id)}/labels/{quote_segment(label_id)}", body=body+ )++ def delete(self, session_id: str, label_id: str) -> SuccessResult:+ """Delete a label; it disappears from every chat it was on. Baileys only."""+ return self._http.request(+ "DELETE", f"/api/sessions/{quote_segment(session_id)}/labels/{quote_segment(label_id)}"+ )+def for_chat(self, session_id: str, chat_id: str) -> list[LabelRecord]:return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/labels/chat/{quote_segment(chat_id)}")diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.pyindex 5f0036248..163d2953d 100644--- a/sdk/python/openwa/types.py+++ b/sdk/python/openwa/types.py@@ -62,6 +62,16 @@ class ChatPresence(TypedDict, total=False):observedAt: str+class UpsertLabelRequest(TypedDict, total=False):+ """A label create-or-update body. The id travels in the path -- WhatsApp keys the write on it."""++ # Leave out to keep the current name.+ name: str+ # WhatsApp's colour INDEX (0-19), NOT a hex value -- it does not round-trip with the hexColor+ # labels are read back with, because neither engine exposes the mapping.+ color: int++# ── Session ───────────────────────────────────────────────────────diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 216d8ee45..f2b09eb3b 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -55,6 +55,7 @@ class FakeSock extends EventEmitter {public readMessages = jest.fn().mockResolvedValue(undefined);public chatModify = jest.fn().mockResolvedValue(undefined);public addChatLabel = jest.fn().mockResolvedValue(undefined);+ public addLabel = jest.fn().mockResolvedValue(undefined);public removeChatLabel = jest.fn().mockResolvedValue(undefined);public newsletterMetadata = jest.fn();public getCatalog = jest.fn();@@ -4358,3 +4359,60 @@ describe('BaileysAdapter presence', () => {expect(onPresenceUpdate).not.toHaveBeenCalled();});});++// Create, update and delete are ONE upstream write (a `label_edit` app-state patch keyed on the+// label id), so what distinguishes them is the body — and getting that body wrong silently edits the+// wrong thing rather than failing.+describe('BaileysAdapter label editing', () => {+ beforeEach(() => {+ fakeSock.user = undefined;+ fakeSock.resetEmitter();+ jest.clearAllMocks();+ });++ const readyAdapter = async () => {+ const adapter = newAdapter();+ await adapter.initialize(noopCallbacks({}));+ fakeSock.user = { id: '628999:[email protected]', name: 'Me' };+ fakeSock.fire('connection.update', { connection: 'open' });+ return adapter;+ };++ it('writes name and colour under the caller-chosen id', async () => {+ const adapter = await readyAdapter();++ await adapter.upsertLabel({ id: 'l1', name: 'VIP', color: 3 });++ expect(fakeSock.addLabel).toHaveBeenCalledWith('628999:[email protected]', {+ id: 'l1',+ name: 'VIP',+ color: 3,+ });+ });++ // Colour 0 is a real WhatsApp colour, not "unset" — a falsy check here would make it unsettable.+ it('treats colour 0 as a colour', async () => {+ const adapter = await readyAdapter();++ await adapter.upsertLabel({ id: 'l1', color: 0 });++ const [, body] = fakeSock.addLabel.mock.calls[0] as [string, { color?: number }];+ expect(body.color).toBe(0);+ });++ it('deletes through the same write, with the tombstone flag', async () => {+ const adapter = await readyAdapter();++ await adapter.deleteLabel('l1');++ expect(fakeSock.addLabel).toHaveBeenCalledWith('628999:[email protected]', { id: 'l1', deleted: true });+ });++ // Baileys has label writes but no label query of any kind, so listing a label's chats is refused+ // rather than faked from a partial cache.+ it('refuses to list chats by label, with the method named', async () => {+ const adapter = await readyAdapter();++ await expect(adapter.getChatsByLabel('l1')).rejects.toThrow(/getChatsByLabel/);+ });+});diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex 9f8462a1d..8d106ab43 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -25,6 +25,7 @@ import {IncomingMessage,IWhatsAppEngine,Label,+ LabelInput,LocationInput,MediaInput,MessageReaction,@@ -519,6 +520,14 @@ export class BaileysAdapter implements IWhatsAppEngine {return this.unsupported('getMessageReactions');}+ // Baileys exposes label WRITES only — chats.d.ts:69-73 has addLabel/addChatLabel/removeChatLabel+ // and no query of any kind, and Types/Label.d.ts is types-only. Listing the chats on a label would+ // mean maintaining an app-state cache fed by the label-association sync events, which is a+ // separate piece of work from this one and is tracked as such.+ getChatsByLabel(_labelId: string): Promise<ChatSummary[]> {+ return this.unsupported('getChatsByLabel');+ }+// No vote-send helper exists in Baileys — only decryptPollVote for RECEIVING. Sending one needs a// hand-built proto.Message.PollUpdateMessage with HMAC-SHA256 vote encryption keyed by the poll// creation's messageSecret.@@ -554,6 +563,41 @@ export class BaileysAdapter implements IWhatsAppEngine {this.ensureReady();await this.sock!.removeChatLabel(chatId, labelId);}+ /**+ * Create or update a label.+ *+ * WhatsApp models this as ONE app-state write — a `label_edit` patch indexed by the label id — so+ * create and update are the same operation, distinguished only by whether the id already exists.+ * That is why the id is caller-supplied rather than returned.+ *+ * The `jid` Baileys asks for is unused on this patch: `chatModifyToPatch` builds the index from+ * `['label_edit', id]` and never reads it (Utils/chat-utils.js:579-593). The account's own jid is+ * passed because the call demands one, not because it addresses anything.+ */+ async upsertLabel(label: LabelInput): Promise<void> {+ this.ensureReady();+ // Unset fields are passed through as undefined rather than stripped: the protobuf encoder skips+ // a field that is `!= null` false, exactly as it skips a missing one (WAProto/index.js,+ // LabelEditAction.encode), so an omitted name really does leave the stored name alone. Colour 0+ // is a real WhatsApp colour and survives that check — which is why it must never be tested for+ // truthiness on the way here.+ await this.sock!.addLabel(this.ownJidForAppState(), { id: label.id, name: label.name, color: label.color });+ }++ /** Delete a label. The same `label_edit` write, with the tombstone flag set. */+ async deleteLabel(labelId: string): Promise<void> {+ this.ensureReady();+ await this.sock!.addLabel(this.ownJidForAppState(), { id: labelId, deleted: true });+ }++ /**+ * A jid for the label-edit app-state write, which needs one but never uses it. The account's own+ * id is the honest choice — the write is about this account, not about a conversation.+ */+ private ownJidForAppState(): string {+ return this.sock?.user?.id ?? 'status@broadcast';+ }+getSubscribedChannels(): Promise<Channel[]> {return this.unsupported('getSubscribedChannels');}diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex f76c973d3..1d87db6a3 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -5682,3 +5682,24 @@ describe('WhatsAppWebJsAdapter presence', () => {expect(String(body)).toMatch(/EngineNotSupportedError/);});});++// whatsapp-web.js can READ labels and assign them, but cannot edit one. The split is the whole+// point of this pair of tests: the read it does have must work, and the writes it does not have must+// be refused inline where the parity gate can verify the matrix row.+describe('WhatsAppWebJsAdapter labels', () => {+ const newAdapter = () =>+ new WhatsAppWebJsAdapter({ sessionId: 'sess-1', sessionDataPath: './data/sessions', puppeteer: {} });++ it.each([+ ['upsertLabel', (a: WhatsAppWebJsAdapter) => a.upsertLabel({ id: 'l1', name: 'VIP' })],+ ['deleteLabel', (a: WhatsAppWebJsAdapter) => a.deleteLabel('l1')],+ ])('refuses %s, with the method named', async (name, call) => {+ await expect(call(newAdapter())).rejects.toThrow(new RegExp(name));+ });++ it.each(['upsertLabel', 'deleteLabel'])('declares %s inline, where the parity gate can read it', name => {+ const body = Object.getOwnPropertyDescriptor(WhatsAppWebJsAdapter.prototype, name)?.value as () => unknown;++ expect(String(body)).toMatch(/EngineNotSupportedError/);+ });+});diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex 1a176cc8b..2a0478b91 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -39,6 +39,7 @@ import {PaginatedProducts,ChatSummary,ChatState,+ LabelInput,GroupEvent,IncomingCallEvent,AccountRestriction,@@ -637,6 +638,28 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin* off the prototype, so a throw hidden behind a delegate call is invisible to it and the* `not-available` matrix row would go unverified; inline, the gate checks it.*/+ getChatsByLabel(labelId: string): Promise<ChatSummary[]> {+ return this.labels.getChatsByLabel(labelId);+ }++ /**+ * whatsapp-web.js 1.34.7 can read labels and assign them, but cannot create, rename, recolour or+ * delete one — `index.d.ts` exposes getLabels / getLabelById / getChatLabels / getChatsByLabelId /+ * addOrRemoveLabels and nothing that edits the label itself.+ *+ * Inline rather than delegated so the parity gate, which reads bodies off the prototype, can+ * verify the matrix row (see docs/29).+ */+ // eslint-disable-next-line @typescript-eslint/require-await, @typescript-eslint/no-unused-vars+ async upsertLabel(_label: LabelInput): Promise<void> {+ throw new EngineNotSupportedError('upsertLabel');+ }++ // eslint-disable-next-line @typescript-eslint/require-await, @typescript-eslint/no-unused-vars+ async deleteLabel(_labelId: string): Promise<void> {+ throw new EngineNotSupportedError('deleteLabel');+ }+// eslint-disable-next-line @typescript-eslint/require-await, @typescript-eslint/no-unused-varsasync subscribeToPresence(_chatId: string): Promise<void> {throw new EngineNotSupportedError('subscribeToPresence');diff --git a/src/engine/adapters/wwebjs-labels.ts b/src/engine/adapters/wwebjs-labels.tsindex dbbb8ce93..903f7878b 100644--- a/src/engine/adapters/wwebjs-labels.ts+++ b/src/engine/adapters/wwebjs-labels.ts@@ -1,7 +1,7 @@import { type Client } from 'whatsapp-web.js';-import { Label } from '../interfaces/whatsapp-engine.interface';+import { Label, ChatSummary } from '../interfaces/whatsapp-engine.interface';import { GroupChat, BusinessClient } from '../types/whatsapp-web-js.types';-import { isChannelJid } from '../identity/wa-id';+import { isChannelJid, chatKind } from '../identity/wa-id';import { ChatLabelsUnsupportedError } from '../../common/errors/chat-labels-unsupported.error';import { type WwebjsEngineHost } from './wwebjs-host';@@ -32,6 +32,30 @@ export class WwebjsLabels {}));}+ /**+ * Every chat carrying a label. Mapped to the neutral ChatSummary here rather than returned raw,+ * for the same reason getChats does it: no whatsapp-web.js type may cross the engine boundary.+ * Entries without a serialized id are skipped rather than failing the whole request.+ */+ async getChatsByLabel(labelId: string): Promise<ChatSummary[]> {+ this.host.ensureReady();+ const chats = await (this.client() as unknown as BusinessClient).getChatsByLabelId(labelId);+ const summaries: ChatSummary[] = [];+ for (const chat of chats ?? []) {+ const id = chat.id?._serialized;+ if (!id) continue;+ summaries.push({+ id,+ name: chat.name || id,+ isGroup: Boolean(chat.isGroup),+ kind: chatKind(id),+ unreadCount: chat.unreadCount || 0,+ timestamp: chat.timestamp || 0,+ });+ }+ return summaries;+ }+async getLabelById(labelId: string): Promise<Label | null> {this.host.ensureReady();const label = await (this.client() as unknown as BusinessClient).getLabelById(labelId);diff --git a/src/engine/engine-capability-matrix.ts b/src/engine/engine-capability-matrix.tsindex 99aee7447..38e3853df 100644--- a/src/engine/engine-capability-matrix.ts+++ b/src/engine/engine-capability-matrix.ts@@ -56,6 +56,24 @@ export interface MethodCapability {export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {addLabelToChat: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ upsertLabel: {+ wwjs: { status: 'not-available', rootCause: 'library-limitation' },+ baileys: { status: 'supported' },+ evidence:+ "baileys addLabel(jid, LabelActionBody{id,name?,color?,deleted?}) (Socket/chats.d.ts:69) emits one `label_edit` app-state patch indexed by ['label_edit', id] (Utils/chat-utils.js:579-593), so create and update are the same write; whatsapp-web.js 1.34.7 exposes getLabels/getLabelById/getChatLabels/getChatsByLabelId/addOrRemoveLabels (index.d.ts:129-154) and nothing that edits a label itself",+ },+ deleteLabel: {+ wwjs: { status: 'not-available', rootCause: 'library-limitation' },+ baileys: { status: 'supported' },+ evidence:+ 'baileys the same addLabel write with deleted:true (LabelActionBody.deleted, Types/Label.d.ts:13-22 → labelEditAction.deleted, Utils/chat-utils.js:586); whatsapp-web.js has no label delete',+ },+ getChatsByLabel: {+ wwjs: { status: 'supported' },+ baileys: { status: 'not-available', rootCause: 'library-limitation' },+ evidence:+ "wwjs Client.getChatsByLabelId(labelId) (index.d.ts:153-154); baileys exposes label WRITES only (Socket/chats.d.ts:69-73 addLabel/addChatLabel/removeChatLabel) with no query at all — Types/Label.d.ts is types-only, so listing a label's chats needs an app-state cache fed by the label-association sync events",+ },addParticipants: {wwjs: { status: 'supported' },baileys: { status: 'supported' },diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex 752acbfe0..9443fa45e 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -280,6 +280,25 @@ export interface Label {hexColor: string;}+/**+ * A label to create or update. Keyed on a CALLER-SUPPLIED id, because that is exactly what the+ * underlying operation is: WhatsApp's app-state carries one `label_edit` write indexed by label id,+ * and whether it creates or updates depends only on whether that id already exists. There is no+ * server-assigned id to hand back, so inventing one here would be inventing a contract the protocol+ * does not have — and could silently overwrite an existing label.+ */+export interface LabelInput {+ id: string;+ name?: string;+ /**+ * WhatsApp's colour INDEX (0-19), not a hex value. Deliberately not the `hexColor` the read path+ * returns: neither library exposes the index-to-hex mapping — whatsapp-web.js passes hex straight+ * through from the WA Web store and Baileys only ever speaks in indices — so a translation table+ * here would be guesswork that silently sets the wrong colour.+ */+ color?: number;+}+// Phase 3: Status/Storiesexport interface Status {id: string;@@ -868,6 +887,16 @@ export interface IWhatsAppEngine {getLabelById(labelId: string): Promise<Label | null>;getChatLabels(chatId: string): Promise<Label[]>;addLabelToChat(chatId: string, labelId: string): Promise<void>;+ /**+ * Create or update a label, keyed on `label.id`. One operation, not two: the engines express both+ * through a single app-state write, and which one happens depends on whether the id already+ * exists. Only fields that are set are changed.+ */+ upsertLabel(label: LabelInput): Promise<void>;+ /** Delete a label. It disappears from every chat it was on. */+ deleteLabel(labelId: string): Promise<void>;+ /** Every chat carrying a label. */+ getChatsByLabel(labelId: string): Promise<ChatSummary[]>;removeLabelFromChat(chatId: string, labelId: string): Promise<void>;// Channels/Newsletter (Phase 3)diff --git a/src/engine/types/whatsapp-web-js.types.ts b/src/engine/types/whatsapp-web-js.types.tsindex 1cd1153ce..c359f4456 100644--- a/src/engine/types/whatsapp-web-js.types.ts+++ b/src/engine/types/whatsapp-web-js.types.ts@@ -107,10 +107,16 @@ export interface MessageWithReactions extends Omit<Message, 'hasReaction' | 'get*/export interface BusinessClient extends Omit<Client,- 'subscribeToChannel' | 'unsubscribeFromChannel' | 'getLabels' | 'getLabelById' | 'getChannels'+ 'subscribeToChannel' | 'unsubscribeFromChannel' | 'getLabels' | 'getLabelById' | 'getChannels' | 'getChatsByLabelId'> {getLabels(): Promise<Array<{ id: string; name: string; hexColor: string }>>;getLabelById(id: string): Promise<{ id: string; name: string; hexColor: string } | null>;+ /** Chats carrying a label. whatsapp-web.js has the read but exposes no label create/update/delete. */+ getChatsByLabelId(+ labelId: string,+ ): Promise<+ Array<{ id?: { _serialized?: string }; name?: string; isGroup?: boolean; unreadCount?: number; timestamp?: number }>+ >;getChannels(): Promise<WwjsChannelData[]>;/** Takes a channel ID (`…@newsletter`), NOT an invite code; resolves true only on success. */subscribeToChannel(channelId: string): Promise<boolean>;diff --git a/src/modules/label/dto/upsert-label.dto.ts b/src/modules/label/dto/upsert-label.dto.tsnew file mode 100644index 000000000..b6956ae48--- /dev/null+++ b/src/modules/label/dto/upsert-label.dto.ts@@ -0,0 +1,41 @@+import { ApiPropertyOptional } from '@nestjs/swagger';+import { IsInt, IsOptional, IsString, Max, MaxLength, Min, MinLength } from 'class-validator';+import { ToStrictNumber } from '../../../common/utils/strict-boolean';++/**+ * The body of a label create-or-update. The id is the path parameter, not a field: WhatsApp keys the+ * write on it, and taking it from the URL is what makes `PUT` the honest verb here.+ */+export class UpsertLabelDto {+ @ApiPropertyOptional({+ description: 'Label name. Omit to leave the current name untouched.',+ example: 'VIP customer',+ minLength: 1,+ maxLength: 100,+ })+ @IsOptional()+ @IsString()+ @MinLength(1)+ // WhatsApp's own label editor caps names well below this; the bound exists so a runaway payload+ // cannot be written into app-state, not because 100 is a protocol limit.+ @MaxLength(100)+ name?: string;++ @ApiPropertyOptional({+ description:+ "WhatsApp's colour INDEX (0-19), not a hex value — the read path's `hexColor` cannot be " ++ 'translated back, because neither engine exposes the mapping. Omit to leave the colour alone.',+ example: 3,+ minimum: 0,+ maximum: 19,+ })+ // The global pipe runs with implicit conversion, and Number('') is 0 — which here is a REAL+ // colour, so a blank field would silently recolour the label instead of being refused.+ @ToStrictNumber()+ @IsOptional()+ @IsInt()+ @Min(0)+ // WhatsApp defines exactly 20 predefined label colours (baileys LabelColor, Types/Label.d.ts).+ @Max(19)+ color?: number;+}diff --git a/src/modules/label/label.controller.ts b/src/modules/label/label.controller.tsindex ecc3548e6..4bc19f451 100644--- a/src/modules/label/label.controller.ts+++ b/src/modules/label/label.controller.ts@@ -1,7 +1,8 @@-import { Controller, Get, Post, Delete, Param, Body, HttpCode, HttpStatus } from '@nestjs/common';+import { Controller, Get, Post, Put, Delete, Param, Body, HttpCode, HttpStatus } from '@nestjs/common';import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiBody } from '@nestjs/swagger';import { LabelService } from './label.service';import { AddLabelDto } from './dto/add-label.dto';+import { UpsertLabelDto } from './dto/upsert-label.dto';import { RequireRole } from '../auth/decorators/auth.decorators';import { ApiKeyRole } from '../auth/entities/api-key.entity';@@ -36,6 +37,71 @@ export class LabelController {return this.labelService.getLabelById(sessionId, labelId);}+ @Get(':labelId/chats')+ @ApiOperation({+ summary: 'Get every chat carrying a label',+ description:+ 'whatsapp-web.js only. Baileys exposes label writes but no label query of any kind, so it ' + 'answers `501`.',+ })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiParam({ name: 'labelId', description: 'Label ID' })+ @ApiResponse({ status: 200, description: 'Chats carrying the label' })+ @ApiResponse({ status: 400, description: 'Session not started' })+ @ApiResponse({ status: 501, description: 'The active engine cannot list chats by label (Baileys)' })+ async getChatsByLabel(@Param('sessionId') sessionId: string, @Param('labelId') labelId: string) {+ return this.labelService.getChatsByLabel(sessionId, labelId);+ }++ @Put(':labelId')+ @RequireRole(ApiKeyRole.OPERATOR)+ @HttpCode(HttpStatus.OK)+ @ApiOperation({+ summary: 'Create or update a label',+ description:+ 'Baileys only. `PUT` rather than `POST` because the label id is chosen by the caller: WhatsApp ' ++ 'carries one `label_edit` write keyed on that id, so whether this creates or updates depends ' ++ 'purely on whether the id already exists, and there is no server-assigned id to return.\n\n' ++ '**Choose an unused id to create.** Reusing one silently rewrites that label rather than ' ++ 'failing, because the protocol has no create-only form. Fields left out are left alone.\n\n' ++ 'whatsapp-web.js can read and assign labels but cannot edit one, and answers `501`.',+ })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiParam({ name: 'labelId', description: 'Label ID — caller-chosen' })+ @ApiBody({ type: UpsertLabelDto })+ @ApiResponse({ status: 200, description: 'Label created or updated' })+ @ApiResponse({ status: 400, description: 'Session not started, or validation failed' })+ @ApiResponse({ status: 501, description: 'The active engine cannot edit labels (whatsapp-web.js)' })+ async upsertLabel(+ @Param('sessionId') sessionId: string,+ @Param('labelId') labelId: string,+ @Body() dto: UpsertLabelDto,+ ): Promise<{ success: boolean }> {+ await this.labelService.upsertLabel(sessionId, labelId, dto);+ return { success: true };+ }++ @Delete(':labelId')+ @RequireRole(ApiKeyRole.OPERATOR)+ @HttpCode(HttpStatus.OK)+ @ApiOperation({+ summary: 'Delete a label',+ description:+ 'Baileys only. The label disappears from every chat it was on. whatsapp-web.js cannot edit ' ++ 'labels and answers `501`.',+ })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiParam({ name: 'labelId', description: 'Label ID' })+ @ApiResponse({ status: 200, description: 'Label deleted' })+ @ApiResponse({ status: 400, description: 'Session not started' })+ @ApiResponse({ status: 501, description: 'The active engine cannot edit labels (whatsapp-web.js)' })+ async deleteLabel(+ @Param('sessionId') sessionId: string,+ @Param('labelId') labelId: string,+ ): Promise<{ success: boolean }> {+ await this.labelService.deleteLabel(sessionId, labelId);+ return { success: true };+ }+@Get('chat/:chatId')@ApiOperation({ summary: 'Get labels for a specific chat' })@ApiParam({ name: 'sessionId', description: 'Session ID' })diff --git a/src/modules/label/label.service.spec.ts b/src/modules/label/label.service.spec.tsindex 1c0f6e4c5..27643b86f 100644--- a/src/modules/label/label.service.spec.ts+++ b/src/modules/label/label.service.spec.ts@@ -25,3 +25,48 @@ describe('LabelService', () => {expect(addLabelToChat).toHaveBeenCalledWith('chat1', 'l1');});});++// Create and update are one operation upstream — a single `label_edit` write keyed on the label id —+// so the service must not invent two, and must not send fields the caller did not set.+describe('LabelService label editing', () => {+ const makeService = (engine: Partial<IWhatsAppEngine>) => {+ const engines = new EngineRegistry();+ engines.set('s1', engine as IWhatsAppEngine);+ return new LabelService(engines);+ };++ it('sends the path id as the label id', async () => {+ const upsertLabel = jest.fn().mockResolvedValue(undefined);+ await makeService({ upsertLabel }).upsertLabel('s1', 'l1', { name: 'VIP' });+ expect(upsertLabel).toHaveBeenCalledWith({ id: 'l1', name: 'VIP' });+ });++ // Omitted fields must stay omitted rather than becoming undefined-valued keys: the adapter drops+ // undefined before it reaches app-state, and sending an explicit blank would clear the field.+ it('passes through only the fields the caller set', async () => {+ const upsertLabel = jest.fn().mockResolvedValue(undefined);+ await makeService({ upsertLabel }).upsertLabel('s1', 'l1', { color: 3 });+ expect(upsertLabel).toHaveBeenCalledWith({ id: 'l1', color: 3 });+ });++ it('delegates deleteLabel to the engine', async () => {+ const deleteLabel = jest.fn().mockResolvedValue(undefined);+ await makeService({ deleteLabel }).deleteLabel('s1', 'l1');+ expect(deleteLabel).toHaveBeenCalledWith('l1');+ });++ it('delegates getChatsByLabel to the engine', async () => {+ const getChatsByLabel = jest.fn().mockResolvedValue([{ id: '[email protected]' }]);+ await expect(makeService({ getChatsByLabel }).getChatsByLabel('s1', 'l1')).resolves.toEqual([{ id: '[email protected]' }]);+ expect(getChatsByLabel).toHaveBeenCalledWith('l1');+ });++ it.each([+ ['upsertLabel', (svc: LabelService) => svc.upsertLabel('s1', 'l1', {})],+ ['deleteLabel', (svc: LabelService) => svc.deleteLabel('s1', 'l1')],+ ['getChatsByLabel', (svc: LabelService) => svc.getChatsByLabel('s1', 'l1')],+ ])('throws 400 for %s when the session is not started', (_name, call) => {+ const engines = new EngineRegistry();+ expect(() => call(new LabelService(engines))).toThrow(BadRequestException);+ });+});diff --git a/src/modules/label/label.service.ts b/src/modules/label/label.service.tsindex 1e618aef5..404c1f2c1 100644--- a/src/modules/label/label.service.ts+++ b/src/modules/label/label.service.ts@@ -31,6 +31,23 @@ export class LabelService {return this.getEngine(sessionId).getChatLabels(chatId);}+ /**+ * Create or update a label. One operation on purpose: WhatsApp carries a single `label_edit`+ * write keyed by the label id, so whether this creates or updates depends only on whether that id+ * already exists — which is also why the caller chooses the id rather than being handed one.+ */+ upsertLabel(sessionId: string, labelId: string, body: { name?: string; color?: number }) {+ return this.getEngine(sessionId).upsertLabel({ id: labelId, ...body });+ }++ deleteLabel(sessionId: string, labelId: string) {+ return this.getEngine(sessionId).deleteLabel(labelId);+ }++ getChatsByLabel(sessionId: string, labelId: string) {+ return this.getEngine(sessionId).getChatsByLabel(labelId);+ }+addLabelToChat(sessionId: string, chatId: string, labelId: string) {return this.getEngine(sessionId).addLabelToChat(chatId, labelId);}