Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): repair chat label add/remove on whatsapp-web.js (#556)

Yudhi Armyndhariseae546eee255
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f16caa129..4abf40305 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- **Sending to — or operating on — a WhatsApp Channel (newsletter) no longer logs internal errors.** On the whatsapp-web.js engine a channel JID (`…@newsletter`) resolves to a `Channel`, which has none of the per-chat operations; the gateway now skips those for channels instead of throwing. The typing indicator that precedes a send, the typing/recording presence endpoint and its MCP tool, mark-unread, and delete-chat now cleanly no-op for a channel (presence does nothing; mark-unread and delete-chat report no change) rather than emitting an internal `TypeError`. Fetching chat labels for a channel previously failed with HTTP 500 — it now returns an empty list. Direct chats, groups, and broadcast lists are unaffected. (#554) Thanks @DanielOberlechner.
+- **Adding and removing chat labels now works on the whatsapp-web.js engine.** The add- and remove-label endpoints called a method that does not exist in the engine, so every request failed with HTTP 500. They now apply the change correctly (reading the chat's current labels and writing back the updated set). Because labels are a WhatsApp Business feature, a request on a non-Business account — or against a chat type that has no labels, such as a channel — now returns a clear HTTP 422 instead of an internal error. (#556)
## [0.7.16] - 2026-06-30
diff --git a/src/common/errors/chat-labels-unsupported.error.spec.ts b/src/common/errors/chat-labels-unsupported.error.spec.ts
new file mode 100644
index 000000000..840acc425
--- /dev/null
+++ b/src/common/errors/chat-labels-unsupported.error.spec.ts
@@ -0,0 +1,12 @@
+import { ChatLabelsUnsupportedError } from './chat-labels-unsupported.error';
+
+describe('ChatLabelsUnsupportedError', () => {
+ it('carries HTTP 422 so NestJS returns Unprocessable Entity without a custom filter', () => {
+ expect(new ChatLabelsUnsupportedError().getStatus()).toBe(422);
+ });
+
+ it('defaults to the Business-account message and accepts an override', () => {
+ expect(new ChatLabelsUnsupportedError().message).toContain('WhatsApp Business account');
+ expect(new ChatLabelsUnsupportedError('Channels do not support chat labels.').message).toContain('Channels');
+ });
+});
diff --git a/src/common/errors/chat-labels-unsupported.error.ts b/src/common/errors/chat-labels-unsupported.error.ts
new file mode 100644
index 000000000..d182ed4e8
--- /dev/null
+++ b/src/common/errors/chat-labels-unsupported.error.ts
@@ -0,0 +1,15 @@
+import { UnprocessableEntityException } from '@nestjs/common';
+
+/**
+ * Thrown by an engine adapter when a chat-label write cannot be applied: either the account is not a
+ * WhatsApp Business account (labels are a Business-only feature — whatsapp-web.js rejects the write with
+ * an `[LT01] Only Whatsapp business` error) or the target chat type carries no labels (e.g. a channel).
+ *
+ * Extends NestJS `UnprocessableEntityException` so it maps to **HTTP 422** through NestJS's built-in
+ * exception handler — no custom global filter required. Mirrors how {@link EngineNotReadyError} maps to 409.
+ */
+export class ChatLabelsUnsupportedError extends UnprocessableEntityException {
+ constructor(message = 'Chat labels require a WhatsApp Business account.') {
+ super(message);
+ }
+}
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index bb4526ab1..f4b89026c 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -13,6 +13,7 @@ import {
import { getEffectiveWebVersionInfo, resolveWebVersionPin, __resetWebVersionCache } from '../wa-web-version';
import * as fs from 'fs';
import * as qrcode from 'qrcode';
+import { UnprocessableEntityException } from '@nestjs/common';
import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';
import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';
import { EngineStatus } from '../interfaces/whatsapp-engine.interface';
@@ -353,6 +354,71 @@ describe('WhatsAppWebJsAdapter channel-JID guard (#554 — wwebjs Channel lacks
});
});
+describe('WhatsAppWebJsAdapter chat labels (add/remove via read-modify-write, Business-only)', () => {
+ const USER = '[email protected]';
+ const NEWSLETTER = '120363401234567890@newsletter';
+
+ const readyAdapter = (client: unknown): WhatsAppWebJsAdapter => {
+ const adapter = new WhatsAppWebJsAdapter({ sessionId: 's', sessionDataPath: './data/sessions', puppeteer: {} });
+ (adapter as unknown as { status: EngineStatus }).status = EngineStatus.READY;
+ (adapter as unknown as { client: unknown }).client = client;
+ return adapter;
+ };
+
+ // whatsapp-web.js has no add-/remove-one primitive: addOrRemoveLabels(ids, chats) REPLACES the chat's
+ // label set with `ids`. A client mock that reports the chat already carries label 'A'.
+ const clientWith = (existing: string[], addOrRemoveLabels: jest.Mock) => ({
+ getChatById: jest.fn().mockResolvedValue({
+ getLabels: jest.fn().mockResolvedValue(existing.map(id => ({ id, name: id, hexColor: '#fff' }))),
+ }),
+ addOrRemoveLabels,
+ });
+
+ it('adds a label by writing back the union of the existing set and the new id', async () => {
+ const addOrRemoveLabels = jest.fn().mockResolvedValue(undefined);
+ await readyAdapter(clientWith(['A'], addOrRemoveLabels)).addLabelToChat(USER, 'B');
+ expect(addOrRemoveLabels).toHaveBeenCalledWith(['A', 'B'], [USER]);
+ });
+
+ it('is idempotent when adding a label the chat already has', async () => {
+ const addOrRemoveLabels = jest.fn().mockResolvedValue(undefined);
+ await readyAdapter(clientWith(['A', 'B'], addOrRemoveLabels)).addLabelToChat(USER, 'B');
+ expect(addOrRemoveLabels).toHaveBeenCalledWith(['A', 'B'], [USER]);
+ });
+
+ it('removes a label by writing back the set without it (keeping the rest)', async () => {
+ const addOrRemoveLabels = jest.fn().mockResolvedValue(undefined);
+ await readyAdapter(clientWith(['A', 'B'], addOrRemoveLabels)).removeLabelFromChat(USER, 'A');
+ expect(addOrRemoveLabels).toHaveBeenCalledWith(['B'], [USER]);
+ });
+
+ it('maps the whatsapp-web.js [LT01] "Only Whatsapp business" write error to 422', async () => {
+ const addOrRemoveLabels = jest
+ .fn()
+ .mockRejectedValue(new Error('Evaluation failed: [LT01] Only Whatsapp business'));
+ await expect(readyAdapter(clientWith(['A'], addOrRemoveLabels)).addLabelToChat(USER, 'B')).rejects.toBeInstanceOf(
+ UnprocessableEntityException,
+ );
+ });
+
+ it('rethrows a generic write failure unchanged (does not mask it as 422)', async () => {
+ const addOrRemoveLabels = jest.fn().mockRejectedValue(new Error('puppeteer detached'));
+ await expect(readyAdapter(clientWith(['A'], addOrRemoveLabels)).addLabelToChat(USER, 'B')).rejects.toThrow(
+ 'puppeteer detached',
+ );
+ });
+
+ it('rejects with 422 for a channel JID and never touches the client', async () => {
+ const addOrRemoveLabels = jest.fn();
+ const client = clientWith(['A'], addOrRemoveLabels);
+ await expect(readyAdapter(client).addLabelToChat(NEWSLETTER, 'B')).rejects.toBeInstanceOf(
+ UnprocessableEntityException,
+ );
+ expect(client.getChatById).not.toHaveBeenCalled();
+ expect(addOrRemoveLabels).not.toHaveBeenCalled();
+ });
+});
+
describe('WhatsAppWebJsAdapter.forceDestroy (recover a wedged session, #351)', () => {
const newAdapter = (): WhatsAppWebJsAdapter =>
new WhatsAppWebJsAdapter({ sessionId: 'sess-1', sessionDataPath: './data/sessions', puppeteer: {} });
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 8a92fe137..062cadd44 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -35,6 +35,7 @@ import {
} from '../interfaces/whatsapp-engine.interface';
import { resolveWebVersionPin } from '../wa-web-version';
import { isChannelJid } from '../identity/wa-id';
+import { ChatLabelsUnsupportedError } from '../../common/errors/chat-labels-unsupported.error';
import { createLogger } from '../../common/services/logger.service';
import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';
import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';
@@ -1263,16 +1264,45 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
async addLabelToChat(chatId: string, labelId: string): Promise<void> {
this.ensureReady();
- const chat = await this.client!.getChatById(chatId);
- await (chat as unknown as GroupChat).addLabel(labelId);
- this.logger.log(`Added label ${labelId} to chat ${chatId}`);
+ await this.changeChatLabel(chatId, labelId, true);
}
async removeLabelFromChat(chatId: string, labelId: string): Promise<void> {
this.ensureReady();
- const chat = await this.client!.getChatById(chatId);
- await (chat as unknown as GroupChat).removeLabel(labelId);
- this.logger.log(`Removed label ${labelId} from chat ${chatId}`);
+ await this.changeChatLabel(chatId, labelId, false);
+ }
+
+ /**
+ * whatsapp-web.js has no add-/remove-one-label primitive: `client.addOrRemoveLabels(ids, chats)` REPLACES
+ * a chat's label set with `ids` (adding the listed labels, removing any existing label not listed). So
+ * toggle a single label by reading the current set, mutating it, and writing the whole set back.
+ * Labels are a WhatsApp Business feature — the write throws `[LT01]` on a personal account; channels
+ * carry no labels at all. Both are surfaced as a 422 rather than an opaque 500.
+ *
+ * The read and write are separate calls, so two concurrent single-label writes to the SAME chat can
+ * lose an update (last write wins, as a full-set replace). Acceptable for low-frequency label admin;
+ * serialize per (sessionId, chatId) if that ever becomes a real workload.
+ */
+ private async changeChatLabel(chatId: string, labelId: string, add: boolean): Promise<void> {
+ if (isChannelJid(chatId)) {
+ throw new ChatLabelsUnsupportedError('Channels do not support chat labels.');
+ }
+ const ids = new Set((await this.getChatLabels(chatId)).map(label => label.id));
+ if (add) {
+ ids.add(labelId);
+ } else {
+ ids.delete(labelId);
+ }
+ try {
+ await this.client!.addOrRemoveLabels([...ids], [chatId]);
+ } catch (error) {
+ // whatsapp-web.js throws `[LT01] Only Whatsapp business` from the page context on a personal account.
+ if (String(error instanceof Error ? error.message : error).includes('LT01')) {
+ throw new ChatLabelsUnsupportedError();
+ }
+ throw error;
+ }
+ this.logger.log(`${add ? 'Added' : 'Removed'} label ${labelId} ${add ? 'to' : 'from'} chat ${chatId}`);
}
// Channels/Newsletter (Phase 3)
diff --git a/src/modules/label/label.controller.ts b/src/modules/label/label.controller.ts
index de3f3de73..91580e151 100644
--- a/src/modules/label/label.controller.ts
+++ b/src/modules/label/label.controller.ts
@@ -66,6 +66,10 @@ export class LabelController {
status: 200,
description: 'Label added to chat',
})
+ @ApiResponse({
+ status: 422,
+ description: 'Labels require a WhatsApp Business account, or the chat type has no labels',
+ })
async addLabelToChat(
@Param('sessionId') sessionId: string,
@Param('chatId') chatId: string,
@@ -85,6 +89,10 @@ export class LabelController {
status: 200,
description: 'Label removed from chat',
})
+ @ApiResponse({
+ status: 422,
+ description: 'Labels require a WhatsApp Business account, or the chat type has no labels',
+ })
async removeLabelFromChat(
@Param('sessionId') sessionId: string,
@Param('chatId') chatId: string,