Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): replace phantom and false-success results with honest outcomes (#925)
Yudhi Armyndharis59becd7c232e
diff --git a/docs/engine-capability-matrix.md b/docs/engine-capability-matrix.mdindex 37b5f922c..c2061a21a 100644--- a/docs/engine-capability-matrix.md+++ b/docs/engine-capability-matrix.md@@ -16,7 +16,7 @@ Each row also cites an **evidence** string (the exact library file:symbol inspecThe `rootCause`/`evidence` fields are hand-curated from source traces of the installed libraries (`node_modules/@whiskeysockets/baileys`, `node_modules/whatsapp-web.js`); they are not regenerated by the spec and are updated by hand as adapters are wired or libraries change.-> **Phantom support.** The drift gate's throw-heuristic cannot see adapter methods that silently stub (return `null`/`[]` + a warn log) without throwing. Three wwjs entries — `getCatalog`, `getProducts`, `getProduct` — are marked `not-available` in the matrix even though their adapter bodies do not throw, because the library has no API for them. When the drift gate is extended to assert against this matrix, it must consult `status`, not just the throw pattern, for these rows (or the adapter stubs must start throwing).+> **Phantom support.** The drift gate's throw-heuristic cannot see adapter methods that silently stub (return `null`/`[]` + a warn log) without throwing. The wwjs catalog reads — `getCatalog`, `getProducts`, `getProduct` — used to be the live example (marked `not-available` here while their adapter bodies did not throw); the stubs have since been replaced with explicit `EngineNotSupportedError` 501s, so the throw-scan now covers them like every other unavailable row. Any future `not-available` row that must stay non-throwing cannot be verified by the gate — keep it hand-tracked in the matrix (or make the adapter throw).---@@ -30,8 +30,10 @@ The `rootCause`/`evidence` fields are hand-curated from source traces of the ins|---|---|---|| `getChannelMessages` | not-available — **adapter-gap** | supported || `getSubscribedChannels` | not-available — **library-limitation** | supported |+| `subscribeToChannel` | supported | not-available — **adapter-gap** |> **Wired.** ✅ `getChannelById`, `subscribeToChannel`, `unsubscribeFromChannel` on Baileys — via `newsletterMetadata('jid'|'invite', …)` → `NewsletterMetadata` mapped to `Channel` (id/name/description/inviteCode/subscriberCount/picture/verified/createdAt), `newsletterFollow` (subscribe, invite→jid bridge), `newsletterUnfollow` (unsubscribe, 1:1). `getChannelById` on Baileys resolves ANY channel by jid (richer than the wwjs subscribed-list lookup).+- **`subscribeToChannel` (wwjs, adapter-gap).** whatsapp-web.js `Client.subscribeToChannel(channelId)` takes a channel ID and resolves a boolean (`Client.js:2533`) — it cannot satisfy the subscribe-by-invite-code contract on its own. The correct wiring is two-step: `getChannelByInviteCode(inviteCode)` (`Client.js:1707`) → `subscribeToChannel(channel.id)`. The adapter previously passed the invite code straight in and fabricated a `Channel` out of the returned boolean (`{ id: "undefined" }` — a reported success that never subscribed); it now throws an honest `EngineNotSupportedError` (501) until the two-step flow is verified against a live session.- **`getChannelMessages` (baileys, adapter-gap).** `sock.newsletterFetchMessages(channelId, limit, 0, 0)` (`Socket/newsletter.d.ts:19`) returns the **raw `BinaryNode`** of `<message_updates>` children (`newsletter.js:149`). The fetch is one line; the real work is walking the children and mapping each to `ChannelMessage{id,body,timestamp,hasMedia}` — no library parser is exposed. Not wired: a hand-written BinaryNode walk can't be verified without a live WhatsApp session, so it stays a documented gap rather than an unverified implementation.- **`getSubscribedChannels` (baileys, library-limitation).** No enumerate-subscribed-newsletters query in the library. All 23 `Socket/newsletter.d.ts` exports are per-jid (`newsletterMetadata` requires a key; `newsletterSubscribers(jid)` returns the count of one newsletter). The `newsletter` event surfaces jids opportunistically during live sync, but that is incremental, not a list-all. Would require a raw WMex/app-state hack against an undocumented XWAPath.@@ -61,7 +63,7 @@ The `rootCause`/`evidence` fields are hand-curated from source traces of the ins- **`getProduct` (baileys, adapter-gap, medium-confidence).** No direct `getProduct(id)`; call `getCatalog({jid,limit})` then `products.find(p=>p.id===productId)` — loads the whole page to fetch one product.- **`sendProduct` (baileys, adapter-gap).** `AnyRegularMessageContent` accepts `{product: WASendableProduct, businessOwnerJid, body}` (`Types/Message.d.ts:203`, built in `messages.js:397`). Two-step wiring: `getCatalog` lookup to resolve the product's image/title/price, then `sock.sendMessage(chatId, {product:{...}, body})`. `productId`-only send without the lookup is not possible.- **`sendCatalog` (both, library-limitation).** No catalog-share message type exists in either library. Baileys `AnyMessageContent` has only `{product}` (single product); the catalog CRUD nodes (`Socket/business.js:294-362`) mutate the catalog, they don't send it. Would require raw-proto relay hacks (unverified).-- **wwjs catalog (library-limitation).** `whatsapp-web.js` has no `Client.getCatalog`/`getProducts`/`getProduct`/`sendProduct`/`sendCatalog` (`index.d.ts` grep = 0 hits). `Product`/`Order` are inbound-only parsers. The adapter currently stubs the reads to `null`/`[]` without throwing (phantom support).+- **wwjs catalog (library-limitation).** `whatsapp-web.js` has no `Client.getCatalog`/`getProducts`/`getProduct`/`sendProduct`/`sendCatalog` (`index.d.ts` grep = 0 hits). `Product`/`Order` are inbound-only parsers. The adapter throws an explicit `EngineNotSupportedError` (501) for the reads (they used to be phantom `null`/`[]` stubs) and the sends alike.### Status — post / delete@@ -123,6 +125,7 @@ _All Tier-2 items wired (see progress above). Remaining channel work is Tier 3:| # | Method : engine | Library call to wire | Effort | Value ||---|---|---|---|---|| 17 | `getProduct` : **baileys** | `getCatalog({jid,limit})` then `products.find(p=>p.id===productId)` (`Socket/business.d.ts:7`) | **S** | Single-product read. Inelegant — loads a whole page to fetch one product. Ship after #14 reuses the same catalog call. |+| 18 | `subscribeToChannel` : **wwjs** | 2-step: `getChannelByInviteCode(inviteCode)` (`index.d.ts:103`; `Client.js:1707`) → `subscribeToChannel(channel.id)` (`Client.js:2533`, boolean → throw on false) | **S** | Channel subscribe-by-invite parity with Baileys. Must be verified against a live session — the previous one-step call was a phantom (it passed the invite code where a channel id belongs and fabricated the returned Channel). |---@@ -149,6 +152,6 @@ These are honestly out of reach of a clean adapter wiring because the installed## Snapshot summary- **80** interface methods, **160** adapter-cells (80 × 2 engines).-- **140** supported cells; **20** not-available cells across **15** methods.-- Of the 20 not-available cells: **5 adapter-gaps** (fixable) + **15 library-limitations** + **0 uncertain**.-- **3 phantom-support rows** (wwjs `getCatalog`/`getProducts`/`getProduct` — they stub without throwing, so the drift gate's throw-heuristic cannot see them; the matrix is the source of truth for these).+- **139** supported cells; **21** not-available cells across **16** methods.+- Of the 21 not-available cells: **6 adapter-gaps** (fixable) + **15 library-limitations** + **0 uncertain**.+- **0 phantom-support rows** — every `not-available` row now throws at the adapter boundary, so the drift gate's throw-heuristic covers the full matrix.diff --git a/openapi.json b/openapi.jsonindex b4d6b56fa..28c42b546 100644--- a/openapi.json+++ b/openapi.json@@ -3271,7 +3271,7 @@},"responses": {"200": {- "description": "Participants added"+ "description": "Participants processed — `results` carries the per-participant outcome (a partial refusal does not fail the batch; a total refusal is an error)"}},"summary": "Add participants to a group",@@ -3313,7 +3313,7 @@},"responses": {"200": {- "description": "Participants removed"+ "description": "Participants processed — `results` carries the per-participant outcome (a partial refusal does not fail the batch; a total refusal is an error)"}},"summary": "Remove participants from a group",@@ -3357,7 +3357,7 @@},"responses": {"200": {- "description": "Participants promoted"+ "description": "Participants processed — `results` carries the per-participant outcome (a partial refusal does not fail the batch; a total refusal is an error)"}},"summary": "Promote participants to admin",@@ -3401,7 +3401,7 @@},"responses": {"200": {- "description": "Participants demoted"+ "description": "Participants processed — `results` carries the per-participant outcome (a partial refusal does not fail the batch; a total refusal is an error)"}},"summary": "Demote participants from admin",@@ -4088,7 +4088,7 @@"name": "limit","required": false,"in": "query",- "description": "Max messages to return (default 50)",+ "description": "Max messages to return (default 50, max 100)","schema": {"type": "number"}diff --git a/src/common/errors/engine-transport.error.spec.ts b/src/common/errors/engine-transport.error.spec.tsnew file mode 100644index 000000000..7664f5de0--- /dev/null+++ b/src/common/errors/engine-transport.error.spec.ts@@ -0,0 +1,18 @@+import { ServiceUnavailableException } from '@nestjs/common';+import { EngineTransportError } from './engine-transport.error';++// A dead engine transport (crashed Chromium page, dropped WebSocket) surfaced as a generic Error+// becomes HTTP 500, and folded into a broad catch it becomes a false 404/400. EngineTransportError+// extends ServiceUnavailableException so NestJS maps it to 503 through the built-in handler (no+// global filter) — same mapping discipline as EngineRefusedError (403).+describe('EngineTransportError', () => {+ it('is a ServiceUnavailableException -> HTTP 503 without a custom global filter', () => {+ const err = new EngineTransportError('Protocol error: Target closed');+ expect(err).toBeInstanceOf(ServiceUnavailableException);+ expect(err.getStatus()).toBe(503);+ });++ it('carries the transport detail as the message', () => {+ expect(new EngineTransportError('Connection Closed').message).toBe('Connection Closed');+ });+});diff --git a/src/common/errors/engine-transport.error.ts b/src/common/errors/engine-transport.error.tsnew file mode 100644index 000000000..05c4260c0--- /dev/null+++ b/src/common/errors/engine-transport.error.ts@@ -0,0 +1,17 @@+import { ServiceUnavailableException } from '@nestjs/common';++/**+ * Thrown by an engine adapter when an operation fails because the engine's TRANSPORT is dead —+ * the Chromium page/CDP connection is gone (whatsapp-web.js) or the WebSocket dropped (Baileys) —+ * rather than because the requested resource does not exist. A broad catch that folds this into a+ * not-found result makes a crashed session look like a missing group/channel (404) or a refused+ * invite (400), which is how operators end up debugging the wrong layer.+ *+ * Extends NestJS `ServiceUnavailableException` so it maps to **HTTP 503** through the built-in+ * exception handler — no custom global filter required. Mirrors {@link EngineNotReadyError} (409).+ */+export class EngineTransportError extends ServiceUnavailableException {+ constructor(detail: string) {+ super(detail);+ }+}diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 3dd8f9ac0..9117b80f4 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -28,7 +28,9 @@ class FakeSock extends EventEmitter {public groupFetchAllParticipating = jest.fn();public groupMetadata = jest.fn();public groupCreate = jest.fn();- public groupParticipantsUpdate = jest.fn().mockResolvedValue(undefined);+ public groupParticipantsUpdate = jest+ .fn()+ .mockResolvedValue([{ status: '200', jid: '[email protected]', content: {} }]);public groupLeave = jest.fn().mockResolvedValue(undefined);public groupUpdateSubject = jest.fn().mockResolvedValue(undefined);public groupUpdateDescription = jest.fn().mockResolvedValue(undefined);@@ -2364,12 +2366,27 @@ describe('BaileysAdapter group management', () => {]);});- it('getGroupInfo maps groupMetadata, and returns null when it rejects', async () => {+ it('getGroupInfo maps groupMetadata, and returns null only for a server refusal (401/403/404)', async () => {fakeSock.groupMetadata.mockResolvedValueOnce(META);const adapter = await ready();expect((await adapter.getGroupInfo('[email protected]'))?.id).toBe('[email protected]');- fakeSock.groupMetadata.mockRejectedValueOnce(new Error('not a group'));+ // Baileys carries a server refusal as Boom with the numeric WA code on `data`+ // (assertNodeErrorFree, WABinary/generic-utils.js:57).+ fakeSock.groupMetadata.mockRejectedValueOnce(Object.assign(new Error('item-not-found'), { data: 404 }));expect(await adapter.getGroupInfo('[email protected]')).toBeNull();+ fakeSock.groupMetadata.mockRejectedValueOnce(Object.assign(new Error('not-authorized'), { data: 401 }));+ expect(await adapter.getGroupInfo('[email protected]')).toBeNull();+ });++ it('getGroupInfo does NOT fold a transport death into null — a dead socket is not "group not found"', async () => {+ const adapter = await ready();+ // Local Boom, no server error node: DisconnectReason-shaped 428 Connection Closed.+ const connectionClosed = Object.assign(new Error('Connection Closed'), { output: { statusCode: 428 } });+ fakeSock.groupMetadata.mockRejectedValueOnce(connectionClosed);+ await expect(adapter.getGroupInfo('[email protected]')).rejects.toBe(connectionClosed);+ // A non-boom failure (programming/protocol error) propagates too.+ fakeSock.groupMetadata.mockRejectedValueOnce(new Error('unexpected'));+ await expect(adapter.getGroupInfo('[email protected]')).rejects.toThrow('unexpected');});it('getGroupInfo canonicalizes participant + owner ids through the session store (lid -> phone)', async () => {@@ -2478,11 +2495,63 @@ describe('BaileysAdapter group management', () => {it('joinGroupViaInviteCode maps an IQ error to InvalidInviteCodeError (400)', async () => {// A rejected groupAcceptInvite (not-authorized / gone IQ) is the same client-facing cause.- fakeSock.groupAcceptInvite.mockRejectedValue(new Error('not-authorized'));+ // Baileys carries the refusal as Boom with the numeric WA code on `data`.+ fakeSock.groupAcceptInvite.mockRejectedValue(Object.assign(new Error('not-authorized'), { data: 401 }));const adapter = await ready();await expect(adapter.joinGroupViaInviteCode('BAD')).rejects.toBeInstanceOf(InvalidInviteCodeError);});+ it('joinGroupViaInviteCode does NOT fold a transport death into a 400 — a dead socket is not a bad invite', async () => {+ // Local Boom, no server error node: DisconnectReason-shaped 428 Connection Closed.+ const connectionClosed = Object.assign(new Error('Connection Closed'), { output: { statusCode: 428 } });+ fakeSock.groupAcceptInvite.mockRejectedValue(connectionClosed);+ const adapter = await ready();+ await expect(adapter.joinGroupViaInviteCode('CODE123')).rejects.toBe(connectionClosed);+ });++ it('addParticipants maps the per-participant [{status, jid}] array — a partial refusal does not throw', async () => {+ fakeSock.groupParticipantsUpdate.mockResolvedValueOnce([+ { status: '200', jid: '[email protected]', content: {} },+ { status: '403', jid: '[email protected]', content: {} },+ { status: '409', jid: '[email protected]', content: {} },+ ]);+ const adapter = await ready();+ const results = await adapter.addParticipants('[email protected]', ['[email protected]', '[email protected]', '[email protected]']);+ // Jids cross the engine boundary back in the neutral dialect; only the 200 entry is a success.+ expect(results).toEqual([+ { id: '[email protected]', success: true, status: 200 },+ { id: '[email protected]', success: false, status: 403 },+ { id: '[email protected]', success: false, status: 409 },+ ]);+ });++ it.each([+ ['addParticipants', 'add'],+ ['removeParticipants', 'remove'],+ ['promoteParticipants', 'promote'],+ ['demoteParticipants', 'demote'],+ ])('%s throws EngineRefusedError (403) when EVERY participant is refused (e.g. not admin)', async method => {+ fakeSock.groupParticipantsUpdate.mockResolvedValueOnce([+ { status: '403', jid: '[email protected]', content: {} },+ { status: '403', jid: '[email protected]', content: {} },+ ]);+ const adapter = await ready();+ const err = await (adapter as unknown as Record<string, (g: string, p: string[]) => Promise<unknown>>)+ .catch((e: unknown) => e);+ expect(err).toBeInstanceOf(EngineRefusedError);+ expect((err as Error).message).toMatch(/failed for all 2 participant/);+ });++ it('removeParticipants throws EngineRefusedError when the server returns no per-participant outcome', async () => {+ // An empty result is no evidence of success — reporting one would be a false success.+ fakeSock.groupParticipantsUpdate.mockResolvedValueOnce([]);+ const adapter = await ready();+ await expect(adapter.removeParticipants('[email protected]', ['[email protected]'])).rejects.toBeInstanceOf(+ EngineRefusedError,+ );+ });+it.each([['setGroupMessagesAdminsOnly', true, 'announcement'],['setGroupMessagesAdminsOnly', false, 'not_announcement'],diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex d435f34cb..6403bf797 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -35,6 +35,7 @@ import {MessageReaction,MessageResult,PaginatedProducts,+ ParticipantOperationResult,PollInput,Product,ProductQueryOptions,@@ -816,38 +817,93 @@ export class BaileysAdapter implements IWhatsAppEngine {const metadata = await this.sock!.groupMetadata(groupId);return mapBaileysGroupInfo(metadata, jid => this.sessionStore.toNeutralJid(jid));} catch (err) {- this.logger.debug('groupMetadata failed; treating as not-found', {- groupId,- error: err instanceof Error ? err.message : String(err),- });- return null; // not a group / not found+ // Only a SERVER refusal may become null (→ service 404): the group does not exist or the+ // account cannot see it. Anything else — a dropped socket, a timeout, a protocol error —+ // folded into null makes a dead transport look like a missing group, so it propagates.+ const code = BaileysAdapter.refusedStatusCode(err);+ if (code === 401 || code === 403 || code === 404) {+ this.logger.debug('groupMetadata refused; treating as not-found', {+ groupId,+ error: err instanceof Error ? err.message : String(err),+ });+ return null; // not a group / not visible to this account+ }+ throw err;}}+ /**+ * WA error code of a SERVER-refused Baileys query, or undefined for a transport/local failure.+ * Baileys carries a refusal two ways: `assertNodeErrorFree` puts the numeric WA code on Boom's+ * `data` (WABinary/generic-utils.js:57), and `extractGroupMetadata` puts it on `output.statusCode`+ * with the error node as `data` (Socket/groups.js:280). Transport deaths ('Connection Closed',+ * 'Timed Out') are LOCAL Booms with DisconnectReason statusCodes (408/428) and no server error+ * node — so a numeric `data` (or an object `data` alongside a statusCode) is the discriminator.+ */+ private static refusedStatusCode(error: unknown): number | undefined {+ const err = error as { data?: unknown; output?: { statusCode?: unknown } } | null | undefined;+ if (typeof err?.data === 'number') {+ return err.data;+ }+ if (err?.data !== undefined && typeof err.output?.statusCode === 'number') {+ return err.output.statusCode;+ }+ return undefined;+ }+async createGroup(name: string, participants: string[]): Promise<Group> {this.ensureReady();const metadata = await this.sock!.groupCreate(name, this.toEngineParticipants(participants));return mapBaileysGroup(metadata, this.normalizedSelfJid(), jid => this.sessionStore.toNeutralJid(jid));}- async addParticipants(groupId: string, participants: string[]): Promise<void> {- this.ensureReady();- await this.sock!.groupParticipantsUpdate(groupId, this.toEngineParticipants(participants), 'add');+ async addParticipants(groupId: string, participants: string[]): Promise<ParticipantOperationResult[]> {+ return this.runParticipantsUpdate(groupId, participants, 'add');}- async removeParticipants(groupId: string, participants: string[]): Promise<void> {- this.ensureReady();- await this.sock!.groupParticipantsUpdate(groupId, this.toEngineParticipants(participants), 'remove');+ async removeParticipants(groupId: string, participants: string[]): Promise<ParticipantOperationResult[]> {+ return this.runParticipantsUpdate(groupId, participants, 'remove');}- async promoteParticipants(groupId: string, participants: string[]): Promise<void> {- this.ensureReady();- await this.sock!.groupParticipantsUpdate(groupId, this.toEngineParticipants(participants), 'promote');+ async promoteParticipants(groupId: string, participants: string[]): Promise<ParticipantOperationResult[]> {+ return this.runParticipantsUpdate(groupId, participants, 'promote');+ }++ async demoteParticipants(groupId: string, participants: string[]): Promise<ParticipantOperationResult[]> {+ return this.runParticipantsUpdate(groupId, participants, 'demote');}- async demoteParticipants(groupId: string, participants: string[]): Promise<void> {+ /**+ * Baileys `groupParticipantsUpdate` resolves a per-participant `[{status, jid}]` array where+ * `status` is the server's error attr or '200' (Socket/groups.js:153-155) — discarding it turned+ * every not-admin/not-registered/already-member refusal into a reported success. Map the entries+ * verbatim; THROW only when the operation failed for every requested participant (a refusal of+ * the operation itself → HTTP 403) or the server returned no outcome at all.+ */+ private async runParticipantsUpdate(+ groupId: string,+ participants: string[],+ action: 'add' | 'remove' | 'promote' | 'demote',+ ): Promise<ParticipantOperationResult[]> {this.ensureReady();- await this.sock!.groupParticipantsUpdate(groupId, this.toEngineParticipants(participants), 'demote');+ const raw = await this.sock!.groupParticipantsUpdate(groupId, this.toEngineParticipants(participants), action);+ const results: ParticipantOperationResult[] = (raw ?? []).map(entry => ({+ id: entry.jid ? this.sessionStore.toNeutralJid(entry.jid) : '',+ success: entry.status === '200',+ status: Number.isFinite(Number(entry.status)) ? Number(entry.status) : undefined,+ }));+ if (results.length === 0) {+ throw new EngineRefusedError(+ `groupParticipantsUpdate(${action}) returned no per-participant outcome for group ${groupId}`,+ );+ }+ if (results.every(r => !r.success)) {+ const detail = results.map(r => `${r.id || '?'} (${r.status ?? '?'})`).join(', ');+ throw new EngineRefusedError(+ `${action}Participants failed for all ${results.length} participant(s) in group ${groupId}: ${detail}`,+ );+ }+ return results;}/**@@ -897,15 +953,17 @@ export class BaileysAdapter implements IWhatsAppEngine {this.ensureReady();// Baileys resolves undefined when the invite is invalid/expired/revoked — no group id surfaces —// and rejects with an IQ error (e.g. not-authorized / gone) for the same client-facing cause.- // Both map to a 400, not a 500.+ // Both map to a 400. A transport failure (dropped socket, timeout) is NOT a refused invite:+ // folding it into the 400 makes a dead connection look like a bad code, so it propagates.let jid: string | undefined;try {jid = await this.sock!.groupAcceptInvite(inviteCode);} catch (error) {- // A refused invite and a socket/protocol failure both land here, and only the first is the- // caller's fault. The client-facing answer stays 400, but the original error is kept in the- // log: without it an upstream change turns every join into an unexplained 400.- this.logger.warn('Failed to accept group invite', { error: String(error) });+ const code = BaileysAdapter.refusedStatusCode(error);+ if (code === undefined || code < 400 || code >= 500) {+ throw error;+ }+ this.logger.warn('Group invite refused', { error: String(error) });jid = undefined;}if (!jid) {diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 38aec6b91..4661cc369 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -25,6 +25,7 @@ import { EngineNotSupportedError } from '../../common/errors/engine-not-supporteimport { EditedMessage, EngineStatus, GroupEvent, IncomingCallEvent } from '../interfaces/whatsapp-engine.interface';import { CallNotFoundError } from '../../common/errors/call-not-found.error';import { EngineRefusedError } from '../../common/errors/engine-refused.error';+import { EngineTransportError } from '../../common/errors/engine-transport.error';import { InvalidInviteCodeError } from '../../common/errors/invalid-invite-code.error';import { GroupNotFoundError } from '../../common/errors/group-not-found.error';import { SsrfBlockedError } from '../../common/security/ssrf-guard';@@ -3470,14 +3471,14 @@ describe('WhatsAppWebJsAdapter page transport error detection (wedged page fast-expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);});- // joinGroupViaInviteCode answers 400 for every acceptInvite failure, because a refused invite is- // indistinguishable from a page error at that call site. The 400 stays, but a dead page still has- // to reach the liveness path rather than being reported purely as the caller's bad invite code.- it('detects a transport error during joinGroupViaInviteCode (still a 400 to the caller)', async () => {+ // joinGroupViaInviteCode answers 503 for a transport failure (a refused invite is no longer+ // conflated with a dead page at that call site). The dead page still has to reach the liveness+ // path rather than being reported purely as the caller's bad invite code.+ it('detects a transport error during joinGroupViaInviteCode (a 503 to the caller)', async () => {const acceptInvite = jest.fn().mockRejectedValue(new Error('Protocol error: Target closed'));const { adapter, onDisconnected } = readyAdapter({ acceptInvite });- await expect(adapter.joinGroupViaInviteCode('CODE123')).rejects.toBeInstanceOf(InvalidInviteCodeError);+ await expect(adapter.joinGroupViaInviteCode('CODE123')).rejects.toBeInstanceOf(EngineTransportError);expect(onDisconnected).toHaveBeenCalledTimes(1);expect(onDisconnected).toHaveBeenCalledWith('Page transport error during joinGroupViaInviteCode');@@ -3677,3 +3678,217 @@ describe('WhatsAppWebJsAdapter group join + settings + own profile', () => {});});});++describe('WhatsAppWebJsAdapter honest outcomes (no phantom success)', () => {+ const GROUP = '[email protected]';++ 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;+ };++ const groupChat = (over: Record<string, unknown> = {}) => ({+ isGroup: true,+ id: { _serialized: GROUP },+ name: 'G',+ participants: [],+ ...over,+ });++ describe('subscribeToChannel (phantom → honest 501)', () => {+ it('throws EngineNotSupportedError instead of fabricating a Channel from the library boolean', async () => {+ // wwebjs Client.subscribeToChannel(channelId) takes a channel id and resolves a boolean; the+ // old wiring passed the invite code and mapped the boolean as a Channel ({ id: "undefined" }).+ const subscribeToChannel = jest.fn().mockResolvedValue(true);+ const adapter = readyAdapter({ subscribeToChannel });+ await expect(adapter.subscribeToChannel('INVITE123')).rejects.toBeInstanceOf(EngineNotSupportedError);+ expect(subscribeToChannel).not.toHaveBeenCalled();+ });+ });++ describe('catalog reads (phantom stubs → honest 501s)', () => {+ it.each(['getCatalog', 'getProducts', 'getProduct'] as const)('%s throws EngineNotSupportedError', async method => {+ const adapter = readyAdapter({});+ await expect((adapter as unknown as Record<string, () => Promise<unknown>>)[method]()).rejects.toBeInstanceOf(+ EngineNotSupportedError,+ );+ });+ });++ describe('addParticipants (per-participant result is honored)', () => {+ it('maps the per-participant {code, message} object — a partial refusal does not throw', async () => {+ const addParticipants = jest.fn().mockResolvedValue({+ '[email protected]': { code: 200, message: 'The participant was added successfully', isInviteV4Sent: false },+ '[email protected]': {+ code: 403,+ message: 'The participant can be added by sending private invitation only',+ isInviteV4Sent: true,+ },+ '[email protected]': { code: 409, message: 'The participant is already a group member', isInviteV4Sent: false },+ });+ const adapter = readyAdapter({ getChatById: jest.fn().mockResolvedValue(groupChat({ addParticipants })) });++ const results = await adapter.addParticipants(GROUP, ['628111', '[email protected]', '628333']);++ expect(addParticipants).toHaveBeenCalledWith(['[email protected]', '[email protected]', '[email protected]']);+ expect(results).toEqual([+ { id: '[email protected]', success: true, status: 200, message: 'The participant was added successfully' },+ {+ id: '[email protected]',+ success: false,+ status: 403,+ message: 'The participant can be added by sending private invitation only',+ },+ { id: '[email protected]', success: false, status: 409, message: 'The participant is already a group member' },+ ]);+ });++ it('throws EngineRefusedError (403) when the library resolves a batch-refusal STRING (e.g. not admin)', async () => {+ const addParticipants = jest+ .fn()+ .mockResolvedValue('AddParticipantsError: You have no admin rights to add a participant to a group');+ const adapter = readyAdapter({ getChatById: jest.fn().mockResolvedValue(groupChat({ addParticipants })) });+ const err = await adapter.addParticipants(GROUP, ['628111']).catch((e: unknown) => e);+ expect(err).toBeInstanceOf(EngineRefusedError);+ expect((err as Error).message).toMatch(/no admin rights/);+ });++ it('throws EngineRefusedError (403) when EVERY participant is refused', async () => {+ const addParticipants = jest.fn().mockResolvedValue({+ '[email protected]': { code: 404, message: 'The phone number is not registered on WhatsApp', isInviteV4Sent: false },+ '[email protected]': { code: 404, message: 'The phone number is not registered on WhatsApp', isInviteV4Sent: false },+ });+ const adapter = readyAdapter({ getChatById: jest.fn().mockResolvedValue(groupChat({ addParticipants })) });+ const err = await adapter.addParticipants(GROUP, ['628111', '628222']).catch((e: unknown) => e);+ expect(err).toBeInstanceOf(EngineRefusedError);+ expect((err as Error).message).toMatch(/failed for all 2 participant/);+ });+ });++ describe.each([['removeParticipants'], ['promoteParticipants'], ['demoteParticipants']])(+ '%s (batch {status} is honored)',+ op => {+ it('resolves one success entry per requested participant on {status: 200}', async () => {+ const chat = groupChat({ [op]: jest.fn().mockResolvedValue({ status: 200 }) });+ const adapter = readyAdapter({ getChatById: jest.fn().mockResolvedValue(chat) });+ const results = await (adapter as unknown as Record<string, (g: string, p: string[]) => Promise<unknown>>)[op](+ GROUP,+ ['628111', '[email protected]'],+ );+ expect(results).toEqual([+ { id: '[email protected]', success: true, status: 200 },+ { id: '[email protected]', success: true, status: 200 },+ ]);+ });++ it('throws EngineRefusedError on a non-200 batch status instead of reporting success', async () => {+ const chat = groupChat({ [op]: jest.fn().mockResolvedValue({ status: 403 }) });+ const adapter = readyAdapter({ getChatById: jest.fn().mockResolvedValue(chat) });+ await expect(+ (adapter as unknown as Record<string, (g: string, p: string[]) => Promise<unknown>>)[op](GROUP, ['628111']),+ ).rejects.toBeInstanceOf(EngineRefusedError);+ });+ },+ );++ describe('setGroupSubject / setGroupDescription (library boolean is honored)', () => {+ it.each([+ ['setGroupSubject', 'setSubject'],+ ['setGroupDescription', 'setDescription'],+ ] as const)('%s throws EngineRefusedError when wwebjs resolves false', async (method, libMethod) => {+ const chat = groupChat({ [libMethod]: jest.fn().mockResolvedValue(false) });+ const adapter = readyAdapter({ getChatById: jest.fn().mockResolvedValue(chat) });+ await expect(+ (adapter as unknown as Record<string, (g: string, v: string) => Promise<void>>)[method](GROUP, 'New'),+ ).rejects.toBeInstanceOf(EngineRefusedError);+ });++ it.each([+ ['setGroupSubject', 'setSubject'],+ ['setGroupDescription', 'setDescription'],+ ] as const)('%s resolves on true', async (method, libMethod) => {+ const chat = groupChat({ [libMethod]: jest.fn().mockResolvedValue(true) });+ const adapter = readyAdapter({ getChatById: jest.fn().mockResolvedValue(chat) });+ await expect(+ (adapter as unknown as Record<string, (g: string, v: string) => Promise<void>>)[method](GROUP, 'New'),+ ).resolves.toBeUndefined();+ });+ });++ describe('getChannelMessages limit guard (wwebjs fails OPEN on limit < 1)', () => {+ const CHANNEL = '120363401234567890@newsletter';+ const adapterWithChannel = (fetchMessages: jest.Mock) =>+ readyAdapter({ getChannels: jest.fn().mockResolvedValue([{ id: { _serialized: CHANNEL }, fetchMessages }]) });++ it.each([+ [0, 50],+ [-5, 50],+ [NaN, 50],+ [Number.POSITIVE_INFINITY, 50],+ [30, 30],+ [30.9, 30],+ ])('limit %s is forwarded as { limit: %i }', async (input, expected) => {+ const fetchMessages = jest.fn().mockResolvedValue([]);+ await adapterWithChannel(fetchMessages).getChannelMessages(CHANNEL, input);+ expect(fetchMessages).toHaveBeenCalledWith({ limit: expected });+ });+ });++ describe('unsubscribeFromChannel (library boolean is honored)', () => {+ it('throws EngineRefusedError when wwebjs resolves false', async () => {+ const adapter = readyAdapter({ unsubscribeFromChannel: jest.fn().mockResolvedValue(false) });+ await expect(adapter.unsubscribeFromChannel('120363401234567890@newsletter')).rejects.toBeInstanceOf(+ EngineRefusedError,+ );+ });++ it('resolves on true', async () => {+ const adapter = readyAdapter({ unsubscribeFromChannel: jest.fn().mockResolvedValue(true) });+ await expect(adapter.unsubscribeFromChannel('120363401234567890@newsletter')).resolves.toBeUndefined();+ });+ });++ describe('transport death vs genuine not-found', () => {+ const transportError = () => new Error('Protocol error: Connection closed. Target closed');++ it('getGroupInfo answers EngineTransportError (503) on a dead page — not null (→ false 404)', async () => {+ const adapter = readyAdapter({ getChatById: jest.fn().mockRejectedValue(transportError()) });+ await expect(adapter.getGroupInfo(GROUP)).rejects.toBeInstanceOf(EngineTransportError);+ });++ it('getGroupInfo still maps a genuine lookup failure to null (→ 404)', async () => {+ // getChatById RESOLVES undefined for an unknown chat (wwebjs does not throw): dereferencing it+ // fails inside the try — that is the genuine not-found path.+ const adapter = readyAdapter({ getChatById: jest.fn().mockResolvedValue(undefined) });+ await expect(adapter.getGroupInfo(GROUP)).resolves.toBeNull();+ });++ it('joinGroupViaInviteCode answers EngineTransportError (503) on a dead page — not 400', async () => {+ const adapter = readyAdapter({ acceptInvite: jest.fn().mockRejectedValue(transportError()) });+ await expect(adapter.joinGroupViaInviteCode('CODE123')).rejects.toBeInstanceOf(EngineTransportError);+ });++ it('joinGroupViaInviteCode still maps a refused invite to InvalidInviteCodeError (400)', async () => {+ const adapter = readyAdapter({+ acceptInvite: jest.fn().mockRejectedValue(new Error('Evaluation failed: Error: 404')),+ });+ await expect(adapter.joinGroupViaInviteCode('BAD')).rejects.toBeInstanceOf(InvalidInviteCodeError);+ });++ it('getProfilePicture answers EngineTransportError (503) on a dead page — not null (→ false "no picture")', async () => {+ const adapter = readyAdapter({ getProfilePicUrl: jest.fn().mockRejectedValue(transportError()) });+ await expect(adapter.getProfilePicture('[email protected]')).rejects.toBeInstanceOf(EngineTransportError);+ });++ it('getProfilePicture still maps a genuine lookup failure to null (→ "no picture")', async () => {+ // A wwebjs "this contact has no picture" rejects with a ServerError — it is NOT a transport+ // signature. It must resolve to null so the API answers "no avatar" rather than a 503.+ const adapter = readyAdapter({+ getProfilePicUrl: jest.fn().mockRejectedValue(new Error("Server returned error: couldn't get profile picture")),+ });+ await expect(adapter.getProfilePicture('[email protected]')).resolves.toBeNull();+ });+ });+});diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex d94bea252..ede45dca4 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -25,6 +25,7 @@ import {Group,GroupInfo,GroupParticipant,+ ParticipantOperationResult,LocationInput,PollInput,ContactCard,@@ -62,6 +63,7 @@ import { InvalidInviteCodeError } from '../../common/errors/invalid-invite-code.import { GroupNotFoundError } from '../../common/errors/group-not-found.error';import { ChannelNotFoundError } from '../../common/errors/channel-not-found.error';import { ChannelMediaNotSupportedError } from '../../common/errors/channel-media-not-supported.error';+import { EngineTransportError } from '../../common/errors/engine-transport.error';import { loadRemoteMediaBuffer } from '../../common/media/load-remote-media';import {GroupChat,@@ -1014,6 +1016,12 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginprivate static readonly PAGE_TRANSPORT_ERROR_PATTERN =/protocol error|target closed|targetclosederror|detached frame|session closed|connection closed/i;+ /** Whether the error carries a dead page/transport signature (see PAGE_TRANSPORT_ERROR_PATTERN). */+ private isPageTransportError(error: unknown): boolean {+ const message = error instanceof Error ? error.message : String(error);+ return WhatsAppWebJsAdapter.PAGE_TRANSPORT_ERROR_PATTERN.test(message);+ }+/*** Report a failed client/page operation as a session death when the error matches* PAGE_TRANSPORT_ERROR_PATTERN. A wedged page can fire NO events while still reporting CONNECTED@@ -1023,12 +1031,11 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin* handlePuppeteerDeath's guard makes this safe during teardown and against double-reporting.*/private reportIfPageTransportError(error: unknown, context: string): void {- const message = error instanceof Error ? error.message : String(error);- if (!WhatsAppWebJsAdapter.PAGE_TRANSPORT_ERROR_PATTERN.test(message)) {+ if (!this.isPageTransportError(error)) {return;}this.logger.warn(`Page transport error during ${context} — treating the session as dead`, {- error: message,+ error: error instanceof Error ? error.message : String(error),});this.handlePuppeteerDeath(`Page transport error during ${context}`);}@@ -1809,6 +1816,13 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginlinkedParentJID: extractLinkedParentJID(groupChat.groupMetadata),};} catch (error) {+ // A dead page and a genuinely-missing group both land in this catch; only the second may+ // become null (→ service 404). A transport death surfaced as "group not found" sends+ // operators debugging the wrong layer — report it and answer 503 instead.+ if (this.isPageTransportError(error)) {+ this.reportIfPageTransportError(error, 'getGroupInfo');+ throw new EngineTransportError(`Transport died while reading group ${groupId}`);+ }this.logger.warn(`Failed to get group: ${groupId}`, { error: String(error) });return null;}@@ -1841,44 +1855,88 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin};}- async addParticipants(groupId: string, participants: string[]): Promise<void> {+ async addParticipants(groupId: string, participants: string[]): Promise<ParticipantOperationResult[]> {this.ensureReady();const chat = await this.client!.getChatById(groupId);if (!chat.isGroup) {throw new Error('Chat is not a group');}const participantIds = participants.map(p => (p.includes('@') ? p : `${p}@c.us`));- await (chat as unknown as GroupChat).addParticipants(participantIds);+ const raw = await (chat as unknown as GroupChat).addParticipants(participantIds);+ // whatsapp-web.js reports a batch-level refusal (no admin rights, empty group) by RESOLVING a+ // plain reason string (GroupChat.js:106-107,128-130) instead of throwing — surface it as a+ // refusal, not a success.+ if (typeof raw === 'string') {+ throw new EngineRefusedError(raw);+ }+ // Per-participant outcome: code 200 = added; 403 invite-only / 404 not registered / 408+ // recently left / 409 already a member / 419 group full (GroupChat.js:102-116).+ const results: ParticipantOperationResult[] = Object.entries(raw ?? {}).map(([id, r]) => ({+ id,+ success: r.code === 200,+ status: r.code,+ message: r.message || undefined,+ }));+ return this.assertParticipantResults('addParticipants', groupId, results);}- async removeParticipants(groupId: string, participants: string[]): Promise<void> {- this.ensureReady();- const chat = await this.client!.getChatById(groupId);- if (!chat.isGroup) {- throw new Error('Chat is not a group');- }- const participantIds = participants.map(p => (p.includes('@') ? p : `${p}@c.us`));- await (chat as unknown as GroupChat).removeParticipants(participantIds);+ async removeParticipants(groupId: string, participants: string[]): Promise<ParticipantOperationResult[]> {+ return this.runStatusOnlyParticipantOp('removeParticipants', groupId, participants);}- async promoteParticipants(groupId: string, participants: string[]): Promise<void> {+ async promoteParticipants(groupId: string, participants: string[]): Promise<ParticipantOperationResult[]> {+ return this.runStatusOnlyParticipantOp('promoteParticipants', groupId, participants);+ }++ async demoteParticipants(groupId: string, participants: string[]): Promise<ParticipantOperationResult[]> {+ return this.runStatusOnlyParticipantOp('demoteParticipants', groupId, participants);+ }++ /**+ * whatsapp-web.js remove/promote/demote resolve `{status: 200}` for the whole batch and reject on+ * a page-side failure (GroupChat.js:267-298,305-340,343-374) — there is no per-participant+ * breakdown to map. A non-200 status is a batch refusal; a 200 confirms the batch, so report one+ * success entry per requested participant rather than discarding the outcome.+ */+ private async runStatusOnlyParticipantOp(+ op: 'removeParticipants' | 'promoteParticipants' | 'demoteParticipants',+ groupId: string,+ participants: string[],+ ): Promise<ParticipantOperationResult[]> {this.ensureReady();const chat = await this.client!.getChatById(groupId);if (!chat.isGroup) {throw new Error('Chat is not a group');}const participantIds = participants.map(p => (p.includes('@') ? p : `${p}@c.us`));- await (chat as unknown as GroupChat).promoteParticipants(participantIds);+ const res = await (chat as unknown as GroupChat)[op](participantIds);+ if (res?.status !== 200) {+ throw new EngineRefusedError(`${op} refused for group ${groupId} (status ${res?.status ?? 'unknown'})`);+ }+ return participantIds.map(id => ({ id, success: true, status: 200 }));}- async demoteParticipants(groupId: string, participants: string[]): Promise<void> {- this.ensureReady();- const chat = await this.client!.getChatById(groupId);- if (!chat.isGroup) {- throw new Error('Chat is not a group');+ /**+ * Shared gate for the membership writes: a result list with at least one success resolves as-is+ * (partial refusals stay visible per participant); a batch that failed for EVERY requested+ * participant is a refusal of the operation itself (HTTP 403), not a per-participant detail; and+ * an empty result is no evidence of success at all.+ */+ private assertParticipantResults(+ op: string,+ groupId: string,+ results: ParticipantOperationResult[],+ ): ParticipantOperationResult[] {+ if (results.length === 0) {+ throw new EngineRefusedError(`${op} returned no per-participant outcome for group ${groupId}`);+ }+ if (results.every(r => !r.success)) {+ const detail = results.map(r => `${r.id} (${r.status ?? '?'})`).join(', ');+ throw new EngineRefusedError(+ `${op} failed for all ${results.length} participant(s) in group ${groupId}: ${detail}`,+ );}- const participantIds = participants.map(p => (p.includes('@') ? p : `${p}@c.us`));- await (chat as unknown as GroupChat).demoteParticipants(participantIds);+ return results;}async leaveGroup(groupId: string): Promise<void> {@@ -1896,7 +1954,12 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginif (!chat.isGroup) {throw new Error('Chat is not a group');}- await (chat as unknown as GroupChat).setSubject(subject);+ // GroupChat.setSubject resolves false when WA Web rejects the change (e.g. the account lacks+ // admin rights; index.d.ts:1982) instead of throwing — surface the refusal, not a false success.+ const ok = await (chat as unknown as GroupChat).setSubject(subject);+ if (!ok) {+ throw new EngineRefusedError(`Failed to set the subject for group ${groupId} — admin rights required`);+ }}async setGroupDescription(groupId: string, description: string): Promise<void> {@@ -1905,7 +1968,11 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginif (!chat.isGroup) {throw new Error('Chat is not a group');}- await (chat as unknown as GroupChat).setDescription(description);+ // Same discarded-boolean contract as setSubject (index.d.ts:1984).+ const ok = await (chat as unknown as GroupChat).setDescription(description);+ if (!ok) {+ throw new EngineRefusedError(`Failed to set the description for group ${groupId} — admin rights required`);+ }}// Reactions (Phase 3)@@ -2076,20 +2143,27 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginreturn channels.find(c => c.id === channelId) ?? null;}- async subscribeToChannel(inviteCode: string): Promise<Channel> {+ // whatsapp-web.js `Client.subscribeToChannel(channelId)` takes a channel ID and resolves a+ // boolean (index.d.ts:71; Client.js:2533) — the interface contract here is subscribe-by-INVITE-CODE+ // returning the subscribed Channel. The old wiring passed the invite code straight in and mapped+ // the returned boolean as if it were a Channel, fabricating `{ id: "undefined" }`: a reported+ // success that never subscribed anything. A real wiring is the two-step+ // `getChannelByInviteCode(inviteCode)` (Client.js:1707) → `subscribeToChannel(channel.id)` flow;+ // until that is verified against a live session, an honest 501 beats a phantom success.+ // eslint-disable-next-line @typescript-eslint/require-await, @typescript-eslint/no-unused-vars+ async subscribeToChannel(_inviteCode: string): Promise<Channel> {this.ensureReady();- const ch = await (this.client as unknown as BusinessClient).subscribeToChannel(inviteCode);- this.logger.log(`Subscribed to channel with invite code: ${inviteCode}`);- return {- id: String(typeof ch.id === 'object' ? ch.id._serialized : ch.id),- name: String(ch.name || ''),- description: ch.description ? String(ch.description) : undefined,- };+ throw new EngineNotSupportedError('subscribeToChannel');}async unsubscribeFromChannel(channelId: string): Promise<void> {this.ensureReady();- await (this.client as unknown as BusinessClient).unsubscribeFromChannel(channelId);+ // Resolves false instead of throwing when the unsubscription did not complete (Client.js:2556)+ // — surface the refusal rather than reporting a false success.+ const ok = await (this.client as unknown as BusinessClient).unsubscribeFromChannel(channelId);+ if (!ok) {+ throw new EngineRefusedError(`Failed to unsubscribe from channel ${channelId}`);+ }this.logger.log(`Unsubscribed from channel: ${channelId}`);}@@ -2105,7 +2179,11 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginif (!channel) {throw new ChannelNotFoundError(channelId);}- const messages = await channel.fetchMessages({ limit });+ // wwebjs Channel.fetchMessages only honors a limit > 0: its load-earlier loop AND the final+ // splice are both gated on `searchOptions.limit > 0` (Channel.js:352), so a 0/negative/NaN+ // limit fails OPEN and returns every loaded message. Substitute the default instead.+ const safeLimit = Number.isFinite(limit) && limit >= 1 ? Math.trunc(limit) : 50;+ const messages = await channel.fetchMessages({ limit: safeLimit });return (messages ?? []).map(msg => ({// Read `$1` before the sentinel (#747), and don't `String()` the object branch: that turned an// unreadable id into the literal "undefined" rather than the empty sentinel every other path@@ -2231,7 +2309,13 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginconst url = await this.client!.getProfilePicUrl(contactId);return url || null;} catch (error) {- this.reportIfPageTransportError(error, 'getProfilePicture');+ // Mirrors getGroupInfo: a dead page and a contact with no picture both land here, and only the+ // second may become null (→ service: the contact simply has no avatar). A transport death+ // surfaced as "no picture" sends operators debugging the wrong layer — report it and answer 503.+ if (this.isPageTransportError(error)) {+ this.reportIfPageTransportError(error, 'getProfilePicture');+ throw new EngineTransportError(`Transport died while reading profile picture for ${contactId}`);+ }this.logger.warn(`Failed to get profile picture for ${contactId}: ${String(error)}`);return null;}@@ -2318,9 +2402,12 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngingroupId = await this.client!.acceptInvite(inviteCode);} catch (error) {// A refused invite and a broken page both land here, and only the first is the caller's- // fault. Surface the transport case to the liveness path and keep the original error in the- // log: without it an upstream rename turns every join into an unexplained 400.- this.reportIfPageTransportError(error, 'joinGroupViaInviteCode');+ // fault. A transport death must not be reported as "invalid invite" (400): report the death+ // to the liveness path and answer 503 so the caller can tell the layers apart.+ if (this.isPageTransportError(error)) {+ this.reportIfPageTransportError(error, 'joinGroupViaInviteCode');+ throw new EngineTransportError('Transport died while accepting the group invite');+ }this.logger.warn(`Failed to accept group invite: ${String(error)}`);groupId = undefined;}@@ -2567,27 +2654,24 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin}// ========== Catalog (Phase 3) ==========+ // whatsapp-web.js has no Catalog API at all (no Client.getCatalog/getProducts/getProduct symbol in+ // index.d.ts). These used to be phantom stubs — a warn log plus null/empty results — so the API+ // reported "no catalog" / "no products" for a capability that never ran. Honest 501s instead,+ // matching sendProduct/sendCatalog below.async getCatalog(): Promise<Catalog | null> {this.ensureReady();- // whatsapp-web.js doesn't have native Catalog API support- this.logger.warn('getCatalog not implemented in whatsapp-web.js adapter');- return null;+ throw new EngineNotSupportedError('getCatalog');}async getProducts(_options?: ProductQueryOptions): Promise<PaginatedProducts> {this.ensureReady();- this.logger.warn('getProducts not implemented in whatsapp-web.js adapter');- return {- products: [],- pagination: { page: 1, limit: 20, total: 0, totalPages: 0 },- };+ throw new EngineNotSupportedError('getProducts');}async getProduct(_productId: string): Promise<Product | null> {this.ensureReady();- this.logger.warn('getProduct not implemented in whatsapp-web.js adapter');- return null;+ throw new EngineNotSupportedError('getProduct');}async sendProduct(_chatId: string, _productId: string, _body?: string): Promise<MessageResult> {diff --git a/src/engine/engine-capability-matrix.ts b/src/engine/engine-capability-matrix.tsindex 7d75efe82..21c7fa0af 100644--- a/src/engine/engine-capability-matrix.ts+++ b/src/engine/engine-capability-matrix.ts@@ -29,13 +29,14 @@* adapters are wired or libraries change.** NOTE on phantom support: the drift gate's throw-heuristic cannot see adapter methods that silently- * stub (return null/[] + a warn log) without throwing. The matrix BELOW is the source-of-truth: three- * wwjs entries (getCatalog/getProducts/getProduct) are marked `not-available` here even though their- * adapter bodies do not throw — the library has no API for them, so the adapter stubs. If the drift- * gate is extended to assert against this matrix, it must consult `status`, not just the throw- * pattern, for these rows (or the adapter stubs must start throwing). getContactStatus/- * getContactStatuses were on this list until #714 wired them on whatsapp-web.js; their rows say- * `supported` and the adapter really does read stories, so they no longer belong here.+ * stub (return null/[] + a warn log) without throwing. The wwjs catalog rows (getCatalog/getProducts/+ * getProduct) used to be the live example — marked `not-available` here while their adapter bodies+ * did not throw — until the adapter stubs were replaced with explicit EngineNotSupportedError 501s,+ * so the throw-scan now sees them like every other unavailable row. If a future row must stay+ * non-throwing while `not-available`, the gate cannot verify it: keep it hand-tracked here (or make+ * the adapter throw). getContactStatus/getContactStatuses were on this list until #714 wired them on+ * whatsapp-web.js; their rows say `supported` and the adapter really does read stories, so they no+ * longer belong here.*/export type CapabilityStatus = 'supported' | 'not-available';export type RootCause = 'adapter-gap' | 'library-limitation' | 'uncertain';@@ -55,14 +56,24 @@ export interface MethodCapability {export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {addLabelToChat: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },- addParticipants: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ addParticipants: {+ wwjs: { status: 'supported' },+ baileys: { status: 'supported' },+ 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",+ },blockContact: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },checkNumberExists: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },createGroup: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },deleteChat: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },deleteMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },deleteStatus: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },- demoteParticipants: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ demoteParticipants: {+ wwjs: { status: 'supported' },+ baileys: { status: 'supported' },+ evidence:+ "wwjs GroupChat.demoteParticipants → batch {status:200} only (index.d.ts:2195 ChangeParticipantsPermissions; GroupChat.js:343-374) — a non-200 now throws at the adapter; baileys groupParticipantsUpdate(jid,pids,'demote') → per-jid [{status}] (Socket/groups.js:140-156)",+ },destroy: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },disconnect: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },editMessage: {@@ -77,7 +88,7 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {wwjs: { status: 'not-available', rootCause: 'library-limitation' },baileys: { status: 'not-available', rootCause: 'adapter-gap' },evidence:- 'baileys Socket/business.d.ts:7 getCatalog({jid,limit,cursor}) + getCollections (business.d.ts:11) — adapter unwired (returns Product[]+cursor, not Catalog metadata; medium-confidence shape synthesis); wwjs index.d.ts has NO Client.getCatalog (0 hits), adapter stubs to null @WhatsAppWebJsAdapter.getCatalog',+ 'baileys Socket/business.d.ts:7 getCatalog({jid,limit,cursor}) + getCollections (business.d.ts:11) — adapter unwired (returns Product[]+cursor, not Catalog metadata; medium-confidence shape synthesis); wwjs index.d.ts has NO Client.getCatalog (0 hits) — adapter throws EngineNotSupportedError (was a phantom null stub)',},getChannelById: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },getChannelMessages: {@@ -139,13 +150,13 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {wwjs: { status: 'not-available', rootCause: 'library-limitation' },baileys: { status: 'not-available', rootCause: 'adapter-gap' },evidence:- 'baileys only getCatalog (Socket/business.d.ts:7); getProduct = getCatalog then find-by-id (compose-and-filter, loads whole page; medium-confidence); wwjs no Client.getProduct — only page-internal getProductMetadata (Utils.js:1253), not a public Client fn; adapter stubs to null @WhatsAppWebJsAdapter.getProduct',+ 'baileys only getCatalog (Socket/business.d.ts:7); getProduct = getCatalog then find-by-id (compose-and-filter, loads whole page; medium-confidence); wwjs no Client.getProduct — only page-internal getProductMetadata (Utils.js:1253), not a public Client fn — adapter throws EngineNotSupportedError (was a phantom null stub)',},getProducts: {wwjs: { status: 'not-available', rootCause: 'library-limitation' },baileys: { status: 'not-available', rootCause: 'adapter-gap' },evidence:- 'baileys Socket/business.d.ts:7 getCatalog({jid,limit,cursor}) → {products, nextPageCursor} — adapter unwired; wwjs no Client.getProducts in index.d.ts (0 hits); adapter stubs to empty @WhatsAppWebJsAdapter.getProducts',+ 'baileys Socket/business.d.ts:7 getCatalog({jid,limit,cursor}) → {products, nextPageCursor} — adapter unwired; wwjs no Client.getProducts in index.d.ts (0 hits) — adapter throws EngineNotSupportedError (was a phantom empty-list stub)',},getProfilePicture: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },getPushName: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },@@ -170,10 +181,20 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {postImageStatus: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },postTextStatus: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },postVideoStatus: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },- promoteParticipants: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ promoteParticipants: {+ wwjs: { status: 'supported' },+ baileys: { status: 'supported' },+ evidence:+ "wwjs GroupChat.promoteParticipants → batch {status:200} only (index.d.ts:2193 ChangeParticipantsPermissions; GroupChat.js:305-340) — a non-200 now throws at the adapter; baileys groupParticipantsUpdate(jid,pids,'promote') → per-jid [{status}] (Socket/groups.js:140-156)",+ },reactToMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },removeLabelFromChat: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },- removeParticipants: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ removeParticipants: {+ wwjs: { status: 'supported' },+ baileys: { status: 'supported' },+ evidence:+ "wwjs GroupChat.removeParticipants → batch {status:200} only (index.d.ts:2189; GroupChat.js:267-298) — a non-200 now throws at the adapter instead of being discarded; baileys groupParticipantsUpdate(jid,pids,'remove') → per-jid [{status}] (Socket/groups.js:140-156)",+ },rejectCall: {wwjs: { status: 'supported' },baileys: { status: 'supported' },@@ -207,7 +228,12 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {sendStickerMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },sendTextMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },sendVideoMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },- setGroupDescription: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ setGroupDescription: {+ wwjs: { status: 'supported' },+ baileys: { status: 'supported' },+ evidence:+ 'wwjs GroupChat.setDescription(description) → boolean (index.d.ts:1984; false → adapter throws EngineRefusedError); baileys groupUpdateDescription(jid, description?) (Socket/groups.d.ts:21)',+ },setGroupEphemeral: {wwjs: { status: 'not-available', rootCause: 'library-limitation' },baileys: { status: 'supported' },@@ -226,7 +252,12 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {evidence:"wwjs GroupChat.setMessagesAdminsOnly(adminsOnly?) (index.d.ts:2210; sets groupMetadata.announce, GroupChat.js:513); baileys groupSettingUpdate(jid, 'announcement'|'not_announcement') (Socket/groups.d.ts:41)",},- setGroupSubject: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ setGroupSubject: {+ wwjs: { status: 'supported' },+ baileys: { status: 'supported' },+ evidence:+ 'wwjs GroupChat.setSubject(newSubject) → boolean (index.d.ts:1982; false → adapter throws EngineRefusedError); baileys groupUpdateSubject(jid, subject) (Socket/groups.d.ts:20)',+ },setProfileName: {wwjs: { status: 'supported' },baileys: { status: 'supported' },@@ -245,7 +276,17 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {evidence:'wwjs Client.setStatus(status) (index.d.ts:245); baileys updateProfileStatus(status) (Socket/chats.d.ts:49)',},- subscribeToChannel: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ subscribeToChannel: {+ wwjs: { status: 'not-available', rootCause: 'adapter-gap' },+ baileys: { status: 'supported' },+ evidence:+ "wwjs Client.subscribeToChannel(channelId) → boolean (index.d.ts:71; Client.js:2533) takes a CHANNEL id, not the interface's invite code, and getChannelByInviteCode(inviteCode) (index.d.ts:103; Client.js:1707) is the invite→channel bridge — the adapter used to pass the invite code straight in and fabricate a Channel from the returned boolean; now an honest EngineNotSupportedError pending a verified two-step wiring; baileys newsletterMetadata('invite', code) + newsletterFollow (Socket/newsletter.d.ts)",+ },unblockContact: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },- unsubscribeFromChannel: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ unsubscribeFromChannel: {+ wwjs: { status: 'supported' },+ baileys: { status: 'supported' },+ evidence:+ 'wwjs Client.unsubscribeFromChannel(channelId, options?) → boolean (index.d.ts:74; Client.js:2556; false → adapter throws EngineRefusedError); baileys newsletterUnfollow(jid) (Socket/newsletter.d.ts)',+ },};diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex 8b8f54f52..64fc6b603 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -190,6 +190,26 @@ export interface GroupParticipant {isSuperAdmin: boolean;}+/**+ * Outcome of a group membership write (add/remove/promote/demote) for ONE participant. Engines+ * that report per-participant results map them verbatim (whatsapp-web.js `addParticipants` resolves+ * a `{[participantId]: {code, message}}` object; Baileys `groupParticipantsUpdate` resolves a+ * `[{status, jid}]` array); engines that only confirm the batch as a whole (whatsapp-web.js+ * remove/promote/demote resolve `{status: 200}`) report one success entry per requested participant.+ * `status` is the engine's own code when it reported one (e.g. 200 ok, 403 invite-only/not-admin,+ * 404 not registered, 409 already a member).+ */+export interface ParticipantOperationResult {+ /** Neutral participant id the outcome belongs to. */+ id: string;+ /** True only when the engine confirmed the change for THIS participant. */+ success: boolean;+ /** Engine-reported status code, when it gave one. */+ status?: number;+ /** Engine-reported human-readable reason, when it gave one. */+ message?: string;+}+export interface GroupInfo {id: string;name: string;@@ -590,10 +610,16 @@ export interface IWhatsAppEngine {// Groups - Extended (Phase 3)getGroupInfo(groupId: string): Promise<GroupInfo | null>;createGroup(name: string, participants: string[]): Promise<Group>;- addParticipants(groupId: string, participants: string[]): Promise<void>;- removeParticipants(groupId: string, participants: string[]): Promise<void>;- promoteParticipants(groupId: string, participants: string[]): Promise<void>;- demoteParticipants(groupId: string, participants: string[]): Promise<void>;+ /**+ * Membership writes resolve one {@link ParticipantOperationResult} per participant, so a partial+ * refusal (one invite-only number among several added) is visible instead of being flattened into+ * a blanket success. They THROW only when the operation failed for every requested participant —+ * e.g. the account lacks admin rights — or the batch itself was refused.+ */+ addParticipants(groupId: string, participants: string[]): Promise<ParticipantOperationResult[]>;+ removeParticipants(groupId: string, participants: string[]): Promise<ParticipantOperationResult[]>;+ promoteParticipants(groupId: string, participants: string[]): Promise<ParticipantOperationResult[]>;+ demoteParticipants(groupId: string, participants: string[]): Promise<ParticipantOperationResult[]>;leaveGroup(groupId: string): Promise<void>;setGroupSubject(groupId: string, subject: string): Promise<void>;setGroupDescription(groupId: string, description: string): Promise<void>;diff --git a/src/engine/types/whatsapp-web-js.types.ts b/src/engine/types/whatsapp-web-js.types.tsindex 7e6a67fc3..4fc830098 100644--- a/src/engine/types/whatsapp-web-js.types.ts+++ b/src/engine/types/whatsapp-web-js.types.ts@@ -52,13 +52,18 @@ export interface GroupChat extends Omit<Chat, 'isReadOnly' | 'getLabels'> {isReadOnly?: boolean;isAnnounce?: boolean;groupMetadata?: GroupMetadataRaw;- addParticipants(ids: string[]): Promise<void>;- removeParticipants(ids: string[]): Promise<void>;- promoteParticipants(ids: string[]): Promise<void>;- demoteParticipants(ids: string[]): Promise<void>;+ addParticipants(+ ids: string[],+ options?: Record<string, unknown>,+ ): Promise<Record<string, { code: number; message: string; isInviteV4Sent: boolean }> | string>;+ removeParticipants(ids: string[]): Promise<{ status: number }>;+ promoteParticipants(ids: string[]): Promise<{ status: number }>;+ demoteParticipants(ids: string[]): Promise<{ status: number }>;leave(): Promise<void>;- setSubject(subject: string): Promise<void>;- setDescription(desc: string): Promise<void>;+ /** Resolves false when WA Web rejects the change (e.g. no admin rights) — does not throw. */+ setSubject(subject: string): Promise<boolean>;+ /** Resolves false when WA Web rejects the change (e.g. no admin rights) — does not throw. */+ setDescription(desc: string): Promise<boolean>;getLabels(): Promise<Array<{ id: string; name: string; hexColor: string }>>;addLabel(id: string): Promise<void>;removeLabel(id: string): Promise<void>;@@ -94,8 +99,10 @@ export interface BusinessClient extends Omit<getLabels(): Promise<Array<{ id: string; name: string; hexColor: string }>>;getLabelById(id: string): Promise<{ id: string; name: string; hexColor: string } | null>;getChannels(): Promise<WwjsChannelData[]>;- subscribeToChannel(inviteCode: string): Promise<WwjsChannelData>;- unsubscribeFromChannel(id: string): Promise<void>;+ /** Takes a channel ID (`…@newsletter`), NOT an invite code; resolves true only on success. */+ subscribeToChannel(channelId: string): Promise<boolean>;+ /** Resolves true only when the unsubscription completed. */+ unsubscribeFromChannel(id: string, options?: Record<string, unknown>): Promise<boolean>;}/**diff --git a/src/modules/channel/channel.controller.ts b/src/modules/channel/channel.controller.tsindex 185d20f74..94753f5ae 100644--- a/src/modules/channel/channel.controller.ts+++ b/src/modules/channel/channel.controller.ts@@ -39,7 +39,12 @@ export class ChannelController {@ApiOperation({ summary: 'Get messages from a channel' })@ApiParam({ name: 'sessionId', description: 'Session ID' })@ApiParam({ name: 'channelId', description: 'Channel ID' })- @ApiQuery({ name: 'limit', required: false, type: Number, description: 'Max messages to return (default 50)' })+ @ApiQuery({+ name: 'limit',+ required: false,+ type: Number,+ description: 'Max messages to return (default 50, max 100)',+ })@ApiResponse({status: 200,description: 'List of channel messages',diff --git a/src/modules/channel/channel.service.spec.ts b/src/modules/channel/channel.service.spec.tsindex 6279337f1..1eb576069 100644--- a/src/modules/channel/channel.service.spec.ts+++ b/src/modules/channel/channel.service.spec.ts@@ -23,4 +23,23 @@ describe('ChannelService', () => {await makeService({ getChannelMessages }).getChannelMessages('s1', 'ch1', 25);expect(getChannelMessages).toHaveBeenCalledWith('ch1', 25);});++ // The wwjs engine treats a limit < 1 as "no limit" (fail-open): the service clamps the window+ // the same way MessageService.getChatHistory does, so no caller can pull an unbounded history.+ it.each([+ [undefined, 50],+ [NaN, 50],+ [Number.POSITIVE_INFINITY, 50],+ [0, 1],+ [-10, 1],+ [1, 1],+ [100, 100],+ [101, 100],+ [10 ** 9, 100],+ [30.7, 30],+ ])('clamps limit %s to %i before calling the engine', async (input, expected) => {+ const getChannelMessages = jest.fn().mockResolvedValue([]);+ await makeService({ getChannelMessages }).getChannelMessages('s1', 'ch1', input);+ expect(getChannelMessages).toHaveBeenCalledWith('ch1', expected);+ });});diff --git a/src/modules/channel/channel.service.ts b/src/modules/channel/channel.service.tsindex 1196d517e..d7e902775 100644--- a/src/modules/channel/channel.service.ts+++ b/src/modules/channel/channel.service.ts@@ -8,6 +8,8 @@ import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interfa*/@Injectable()export class ChannelService {+ private static readonly MAX_CHANNEL_HISTORY_LIMIT = 100;+constructor(private readonly sessionService: SessionService) {}private getEngine(sessionId: string): IWhatsAppEngine {@@ -30,8 +32,16 @@ export class ChannelService {return channel;}- getChannelMessages(sessionId: string, channelId: string, limit?: number) {- return this.getEngine(sessionId).getChannelMessages(channelId, limit);+ /**+ * `limit` is clamped to [1, 100] (and falls back to 50 for non-finite input) so a caller cannot+ * ask the engine for an unbounded history window — the wwjs engine treats a limit < 1 as "no+ * limit" and would return every loaded message (same clamp discipline as MessageService.getChatHistory).+ */+ getChannelMessages(sessionId: string, channelId: string, limit = 50) {+ const safeLimit = Number.isFinite(limit)+ ? Math.min(Math.max(Math.trunc(limit), 1), ChannelService.MAX_CHANNEL_HISTORY_LIMIT)+ : 50;+ return this.getEngine(sessionId).getChannelMessages(channelId, safeLimit);}subscribeToChannel(sessionId: string, inviteCode: string) {diff --git a/src/modules/group/group.controller.spec.ts b/src/modules/group/group.controller.spec.tsindex 5300ef2b9..dbb322490 100644--- a/src/modules/group/group.controller.spec.ts+++ b/src/modules/group/group.controller.spec.ts@@ -48,4 +48,36 @@ describe('GroupController join + settings', () => {});await expect(controller.updateSettings('s1', 'g1', {})).rejects.toThrow(/At least one/);});++ it('POST :groupId/participants returns the per-participant results as an additive field', async () => {+ const results = [+ { id: '[email protected]', success: true, status: 200 },+ { id: '[email protected]', success: false, status: 403 },+ ];+ const { controller, service } = build({ addParticipants: jest.fn().mockResolvedValue(results) });+ await expect(+ controller.addParticipants('s1', 'g1', { participants: ['[email protected]', '[email protected]'] }),+ ).resolves.toEqual({+ success: true,+ message: 'Participants added',+ results,+ });+ expect(service.addParticipants).toHaveBeenCalledWith('s1', 'g1', ['[email protected]', '[email protected]']);+ });++ it.each([+ ['removeParticipants', 'Participants removed'],+ ['promoteParticipants', 'Participants promoted to admin'],+ ['demoteParticipants', 'Participants demoted from admin'],+ ] as const)('%s returns the per-participant results as an additive field', async (method, message) => {+ const results = [{ id: '[email protected]', success: true, status: 200 }];+ const { controller } = build({ [method]: jest.fn().mockResolvedValue(results) });+ await expect(+ (controller as unknown as Record<string, (s: string, g: string, dto: unknown) => Promise<unknown>>)[method](+ 's1',+ 'g1',+ { participants: ['[email protected]'] },+ ),+ ).resolves.toEqual({ success: true, message, results });+ });});diff --git a/src/modules/group/group.controller.ts b/src/modules/group/group.controller.tsindex 97ec6b3b3..cb8b511b1 100644--- a/src/modules/group/group.controller.ts+++ b/src/modules/group/group.controller.ts@@ -90,15 +90,19 @@ export class GroupController {@ApiParam({ name: 'sessionId', description: 'Session ID' })@ApiParam({ name: 'groupId', description: 'Group ID' })@ApiBody({ type: ParticipantsDto })- @ApiResponse({ status: 200, description: 'Participants added' })+ @ApiResponse({+ status: 200,+ description:+ 'Participants processed — `results` carries the per-participant outcome (a partial refusal does not fail the batch; a total refusal is an error)',+ })@HttpCode(HttpStatus.OK)async addParticipants(@Param('sessionId') sessionId: string,@Param('groupId') groupId: string,@Body() dto: ParticipantsDto,) {- await this.groupService.addParticipants(sessionId, groupId, dto.participants);- return { success: true, message: 'Participants added' };+ const results = await this.groupService.addParticipants(sessionId, groupId, dto.participants);+ return { success: true, message: 'Participants added', results };}@Delete(':groupId/participants')@@ -107,14 +111,18 @@ export class GroupController {@ApiParam({ name: 'sessionId', description: 'Session ID' })@ApiParam({ name: 'groupId', description: 'Group ID' })@ApiBody({ type: ParticipantsDto })- @ApiResponse({ status: 200, description: 'Participants removed' })+ @ApiResponse({+ status: 200,+ description:+ 'Participants processed — `results` carries the per-participant outcome (a partial refusal does not fail the batch; a total refusal is an error)',+ })async removeParticipants(@Param('sessionId') sessionId: string,@Param('groupId') groupId: string,@Body() dto: ParticipantsDto,) {- await this.groupService.removeParticipants(sessionId, groupId, dto.participants);- return { success: true, message: 'Participants removed' };+ const results = await this.groupService.removeParticipants(sessionId, groupId, dto.participants);+ return { success: true, message: 'Participants removed', results };}@Post(':groupId/participants/promote')@@ -123,15 +131,19 @@ export class GroupController {@ApiParam({ name: 'sessionId', description: 'Session ID' })@ApiParam({ name: 'groupId', description: 'Group ID' })@ApiBody({ type: ParticipantsDto })- @ApiResponse({ status: 200, description: 'Participants promoted' })+ @ApiResponse({+ status: 200,+ description:+ 'Participants processed — `results` carries the per-participant outcome (a partial refusal does not fail the batch; a total refusal is an error)',+ })@HttpCode(HttpStatus.OK)async promoteParticipants(@Param('sessionId') sessionId: string,@Param('groupId') groupId: string,@Body() dto: ParticipantsDto,) {- await this.groupService.promoteParticipants(sessionId, groupId, dto.participants);- return { success: true, message: 'Participants promoted to admin' };+ const results = await this.groupService.promoteParticipants(sessionId, groupId, dto.participants);+ return { success: true, message: 'Participants promoted to admin', results };}@Post(':groupId/participants/demote')@@ -140,15 +152,19 @@ export class GroupController {@ApiParam({ name: 'sessionId', description: 'Session ID' })@ApiParam({ name: 'groupId', description: 'Group ID' })@ApiBody({ type: ParticipantsDto })- @ApiResponse({ status: 200, description: 'Participants demoted' })+ @ApiResponse({+ status: 200,+ description:+ 'Participants processed — `results` carries the per-participant outcome (a partial refusal does not fail the batch; a total refusal is an error)',+ })@HttpCode(HttpStatus.OK)async demoteParticipants(@Param('sessionId') sessionId: string,@Param('groupId') groupId: string,@Body() dto: ParticipantsDto,) {- await this.groupService.demoteParticipants(sessionId, groupId, dto.participants);- return { success: true, message: 'Participants demoted from admin' };+ const results = await this.groupService.demoteParticipants(sessionId, groupId, dto.participants);+ return { success: true, message: 'Participants demoted from admin', results };}@Put(':groupId/subject')diff --git a/src/plugins/engines/whatsapp-web-js/index.spec.ts b/src/plugins/engines/whatsapp-web-js/index.spec.tsindex 1c3a0f365..466a42353 100644--- a/src/plugins/engines/whatsapp-web-js/index.spec.ts+++ b/src/plugins/engines/whatsapp-web-js/index.spec.ts@@ -80,3 +80,13 @@ describe('WhatsAppWebJsPlugin.createEngine (opaque config)', () => {);});});++describe('WhatsAppWebJsPlugin.getFeatures', () => {+ it('does not advertise catalog — the wwjs adapter 501s every catalog method', () => {+ const features = new WhatsAppWebJsPlugin().getFeatures();+ expect(features).not.toContain('catalog');+ expect(features).toEqual(+ expect.arrayContaining(['text-messages', 'media-messages', 'group-management', 'labels', 'channels']),+ );+ });+});diff --git a/src/plugins/engines/whatsapp-web-js/index.ts b/src/plugins/engines/whatsapp-web-js/index.tsindex 9bc375fee..de1846125 100644--- a/src/plugins/engines/whatsapp-web-js/index.ts+++ b/src/plugins/engines/whatsapp-web-js/index.ts@@ -90,7 +90,8 @@ export class WhatsAppWebJsPlugin implements IEnginePlugin {'labels','channels','status-updates',- 'catalog',+ // No 'catalog': whatsapp-web.js has no catalog/product API, so the adapter 501s those methods —+ // advertising the feature here would promise clients a capability the engine cannot deliver.];}