Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): answer 503 when the page dies mid-request
Yudhi Armyndharis1b43531041ac
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 08dae8661..d0fd15acc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -86,6 +86,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0lookup, addressbook save and delete, and block and unblock. The list and single-contact reads in thesame file already made that split ([#1476](https://github.com/rmyndharis/OpenWA/issues/1476)).Thanks @onepay-ye.+- Fifteen more whatsapp-web.js operations answer `503` rather than `500` when the browser page dies+ mid-request: the group list and membership queue, the four label reads and writes, and nine message+ operations (history, reactions, react, edit, delete, star, pin, unpin and poll votes). Twelve of them+ had no error handling on that path at all, so a dead page was also never reported to the liveness+ check. Ten of these routes now declare `503` in the API contract; the message send routes keep+ answering `500` deliberately, because `503` is replay-safe in the SDK clients and a replayed send+ would duplicate the message.### Dependenciesdiff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 3c46eab19..63bc32599 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -1292,7 +1292,7 @@ Returns a bare array of engine-neutral `IncomingMessage` objects:Each item may also include `isStatusBroadcast`, `mentionedIds`, `isLidSender`, `ephemeralDuration` (the chat's disappearing-messages timer in seconds, present only when one is set), `contact`, `media { mimetype, filename?, data?, omitted?, sizeBytes? }`, `quotedMessage { id, body }`, `call { video, missed }` (for `call` messages), and `location { latitude, longitude, description?, address?, url? }`. `senderPhone` is **not** among them: this endpoint reads live from the engine and performs no privacy-id resolution, which runs only on the inbound `message.received` path (§6.6). To map an `@lid` sender seen here, call `GET /api/sessions/:sessionId/contacts/:contactId/phone`. `type` is one of `text|image|video|audio|voice|document|sticker|location|contact|poll|call|revoked|masked|unknown`. A `masked` message is one WhatsApp deliberately withholds from linked/companion devices — e.g. a high-security business OTP — so its `body` is empty by design (the content is only available on the primary phone) rather than a parsing failure; this occurs on the Baileys engine. `kind` is the user-facing chat discriminator of `chatId` — one of `individual|group|channel|status|broadcast|unknown`; it supersedes `isStatusBroadcast` (equivalent to `kind === 'status'`), which is retained for back-compat.-**Errors:** `400` session not active · `401` missing/invalid API key · `500` engine error · `409` conflict or engine not ready (retryable) · `501` not supported on the active engine+**Errors:** `400` session not active · `401` missing/invalid API key · `500` engine error · `409` conflict or engine not ready (retryable) · `501` not supported on the active engine · `503` the whatsapp-web.js page died mid-read (retryable)#### GET /api/sessions/:sessionId/messages/:chatId/:messageId/reactions@@ -1321,7 +1321,7 @@ Returns a bare array of `MessageReaction`:]```-**Errors:** `400` session not active · `401` missing/invalid API key · `500` engine error · `409` conflict or engine not ready (retryable) · `501` not supported on the active engine+**Errors:** `400` session not active · `401` missing/invalid API key · `500` engine error · `409` conflict or engine not ready (retryable) · `501` not supported on the active engine · `503` the whatsapp-web.js page died mid-read (retryable)#### POST /api/sessions/:sessionId/messages/vote-poll@@ -1351,7 +1351,7 @@ Cast a vote on a poll.> for _receiving_ votes. Sending one requires hand-building a `PollUpdateMessage` with HMAC-SHA256> vote encryption keyed by the poll creation's `messageSecret`, which is not wired here.-**Errors:** `400` session not active, or the target message is not a poll · `401` missing/invalid API key · `403` key lacks OPERATOR role · `404` poll not found in recent history · `501` Baileys engine · `409` conflict or engine not ready (retryable)+**Errors:** `400` session not active, or the target message is not a poll · `401` missing/invalid API key · `403` key lacks OPERATOR role · `404` poll not found in recent history · `501` Baileys engine · `409` conflict or engine not ready (retryable) · `503` the whatsapp-web.js page died mid-request; repeating it is safe (retryable)#### POST /api/sessions/:sessionId/messages/pin@@ -1369,7 +1369,7 @@ Pin a message in its chat for a bounded window.**Response** `200` — `{ "success": true }`-**Errors:** `400` session not active, or `durationSeconds` outside the three accepted values · `401` missing/invalid API key · `403` the whatsapp-web.js engine refused the pin (in a group only admins may pin; the Baileys engine has no acceptance signal and answers `200`) · `404` message not found in the chat · `409` conflict or engine not ready (retryable)+**Errors:** `400` session not active, or `durationSeconds` outside the three accepted values · `401` missing/invalid API key · `403` the whatsapp-web.js engine refused the pin (in a group only admins may pin; the Baileys engine has no acceptance signal and answers `200`) · `404` message not found in the chat · `409` conflict or engine not ready (retryable) · `503` the whatsapp-web.js page died mid-request; a retry is safe but restarts the pin duration> On whatsapp-web.js the message must be within the 100-message fetch window for the chat, the same> limit that applies to react/delete/edit. On Baileys it must be in the adapter's message store.@@ -1413,7 +1413,7 @@ Remove a message's pin. Takes no duration.**Response** `200` — `{ "success": true }`-**Errors:** `400` session not active · `401` missing/invalid API key · `403` the whatsapp-web.js engine refused the unpin (in a group only admins may unpin; the Baileys engine has no acceptance signal and answers `200`) · `404` message not found in the chat · `409` conflict or engine not ready (retryable)+**Errors:** `400` session not active · `401` missing/invalid API key · `403` the whatsapp-web.js engine refused the unpin (in a group only admins may unpin; the Baileys engine has no acceptance signal and answers `200`) · `404` message not found in the chat · `409` conflict or engine not ready (retryable) · `503` the whatsapp-web.js page died mid-request; repeating it is safe (retryable)#### GET /api/sessions/:sessionId/messages/:chatId/:messageId/media@@ -2064,7 +2064,7 @@ The controller hardcodes the result after the engine call. Note the `200` status{ "success": true }```-**Errors:** `400` session not active / message not found / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `500` engine error · `409` conflict or engine not ready (retryable)+**Errors:** `400` session not active / message not found / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `500` engine error · `409` conflict or engine not ready (retryable) · `503` the whatsapp-web.js page died mid-request; repeating it is safe (retryable)#### POST /api/sessions/:sessionId/messages/delete@@ -2133,7 +2133,7 @@ The edited message keeps its original id.{ "messageId": "[email protected]_3EB0ABCD", "timestamp": 1760000000 }```-**Errors:** `400` session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR, or the engine refused the edit (both engines refuse a message the account did not send; whatsapp-web.js also refuses one that is not text, where the Baileys engine has no acceptance signal and answers `200`) · `404` message not found · `409` conflict or engine not ready (retryable)+**Errors:** `400` session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR, or the engine refused the edit (both engines refuse a message the account did not send; whatsapp-web.js also refuses one that is not text, where the Baileys engine has no acceptance signal and answers `200`) · `404` message not found · `409` conflict or engine not ready (retryable) · `503` the whatsapp-web.js page died mid-request; repeating it is safe (retryable)#### POST /api/sessions/:sessionId/messages/send-bulk@@ -3881,7 +3881,7 @@ List all labels defined for the session (WhatsApp Business accounts only).Bare array — raw return of `engine.getLabels()`; no envelope.-**Errors:** `400` session is not started (no live engine), or the account is not a WhatsApp Business account · `401` missing/invalid API key · `501` the Baileys engine does not implement label reads (whatsapp-web.js only) · `409` conflict or engine not ready (retryable)+**Errors:** `400` session is not started (no live engine), or the account is not a WhatsApp Business account · `401` missing/invalid API key · `501` the Baileys engine does not implement label reads (whatsapp-web.js only) · `409` conflict or engine not ready (retryable) · `503` the whatsapp-web.js page died mid-read (retryable)#### GET /api/sessions/:sessionId/labels/:labelId@@ -3904,7 +3904,7 @@ Get a single label by its ID.The engine resolves `Label | null`; a `null` is mapped to `404` in the service, so a `200` always carries a label.-**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) · `409` conflict or engine not ready (retryable)+**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) · `409` conflict or engine not ready (retryable) · `503` the whatsapp-web.js page died mid-read (retryable)#### GET /api/sessions/:sessionId/labels/:labelId/chats@@ -3985,7 +3985,7 @@ List the labels currently assigned to a specific chat.Bare array — raw return of `engine.getChatLabels(chatId)`.-**Errors:** `400` session is not started · `401` missing/invalid API key · `501` the Baileys engine does not implement label reads (whatsapp-web.js only) · `409` conflict or engine not ready (retryable)+**Errors:** `400` session is not started · `401` missing/invalid API key · `501` the Baileys engine does not implement label reads (whatsapp-web.js only) · `409` conflict or engine not ready (retryable) · `503` the whatsapp-web.js page died mid-read (retryable)#### POST /api/sessions/:sessionId/labels/chat/:chatIddiff --git a/openapi.json b/openapi.jsonindex 323a41f47..800f1fe05 100644--- a/openapi.json+++ b/openapi.json@@ -3082,6 +3082,9 @@},"409": {"description": "The session is not connected — an engine exists for it but is not `ready`: disconnected, reconnecting, or still initializing, so the request never reached WhatsApp. Wait for `ready` and retry. A session that was never started answers `400` instead, and the session lifecycle routes answer `409` for a conflicting state rather than this. One window answers this while the session still reads `ready`: WhatsApp Web periodically reloads its own page and the engine re-injects into it — for those few seconds the answer is a `409` naming the reload; retry shortly."+ },+ "503": {+ "description": "The whatsapp-web.js page connection died mid-request. The change may or may not have been applied; repeating the request is safe, since it converges on the same state."}},"summary": "Add or remove a reaction to a message",@@ -3160,6 +3163,9 @@},"501": {"description": "The active engine cannot serve this operation. It is part of the engine contract, but the engine currently running has no implementation for it."+ },+ "503": {+ "description": "The whatsapp-web.js page connection died mid-read, so nothing could be read. Retry once the session is ready again."}},"summary": "Fetch chat history live from WhatsApp",@@ -3222,6 +3228,9 @@},"501": {"description": "The active engine cannot serve this operation. It is part of the engine contract, but the engine currently running has no implementation for it."+ },+ "503": {+ "description": "The whatsapp-web.js page connection died mid-read, so nothing could be read. Retry once the session is ready again."}},"summary": "Get reactions for a specific message",@@ -3384,6 +3393,9 @@},"501": {"description": "Not supported on the Baileys engine"+ },+ "503": {+ "description": "The whatsapp-web.js page connection died mid-request. The change may or may not have been applied; repeating the request is safe, since it converges on the same state."}},"summary": "Cast a vote on a poll",@@ -3438,6 +3450,9 @@},"409": {"description": "The session is not connected — an engine exists for it but is not `ready`: disconnected, reconnecting, or still initializing, so the request never reached WhatsApp. Wait for `ready` and retry. A session that was never started answers `400` instead, and the session lifecycle routes answer `409` for a conflicting state rather than this. One window answers this while the session still reads `ready`: WhatsApp Web periodically reloads its own page and the engine re-injects into it — for those few seconds the answer is a `409` naming the reload; retry shortly."+ },+ "503": {+ "description": "The whatsapp-web.js page connection died mid-request. The pin may or may not have been applied; a retry is safe, but it restarts the pin duration from the moment it succeeds."}},"summary": "Pin a message in its chat",@@ -3492,6 +3507,9 @@},"409": {"description": "The session is not connected — an engine exists for it but is not `ready`: disconnected, reconnecting, or still initializing, so the request never reached WhatsApp. Wait for `ready` and retry. A session that was never started answers `400` instead, and the session lifecycle routes answer `409` for a conflicting state rather than this. One window answers this while the session still reads `ready`: WhatsApp Web periodically reloads its own page and the engine re-injects into it — for those few seconds the answer is a `409` naming the reload; retry shortly."+ },+ "503": {+ "description": "The whatsapp-web.js page connection died mid-request. The change may or may not have been applied; repeating the request is safe, since it converges on the same state."}},"summary": "Remove a message’s pin",@@ -3600,6 +3618,9 @@},"409": {"description": "The session is not connected — an engine exists for it but is not `ready`: disconnected, reconnecting, or still initializing, so the request never reached WhatsApp. Wait for `ready` and retry. A session that was never started answers `400` instead, and the session lifecycle routes answer `409` for a conflicting state rather than this. One window answers this while the session still reads `ready`: WhatsApp Web periodically reloads its own page and the engine re-injects into it — for those few seconds the answer is a `409` naming the reload; retry shortly."+ },+ "503": {+ "description": "The whatsapp-web.js page connection died mid-request. The change may or may not have been applied; repeating the request is safe, since it converges on the same state."}},"summary": "Edit the text of a message sent by this account",@@ -6378,6 +6399,9 @@},"501": {"description": "The active engine cannot serve this operation. It is part of the engine contract, but the engine currently running has no implementation for it."+ },+ "503": {+ "description": "The whatsapp-web.js page connection died mid-read, so nothing could be read. Retry once the session is ready again."}},"summary": "Get all labels (WhatsApp Business only)",@@ -6428,6 +6452,9 @@},"501": {"description": "The active engine cannot serve this operation. It is part of the engine contract, but the engine currently running has no implementation for it."+ },+ "503": {+ "description": "The whatsapp-web.js page connection died mid-read, so nothing could be read. Retry once the session is ready again."}},"summary": "Get a specific label by ID",@@ -6652,6 +6679,9 @@},"501": {"description": "The active engine cannot serve this operation. It is part of the engine contract, but the engine currently running has no implementation for it."+ },+ "503": {+ "description": "The whatsapp-web.js page connection died mid-read, so nothing could be read. Retry once the session is ready again."}},"summary": "Get labels for a specific chat",diff --git a/src/engine/adapters/wwebjs-group-transport-death.spec.ts b/src/engine/adapters/wwebjs-group-transport-death.spec.tsnew file mode 100644index 000000000..6fa3613e1--- /dev/null+++ b/src/engine/adapters/wwebjs-group-transport-death.spec.ts@@ -0,0 +1,63 @@+import type { Client } from 'whatsapp-web.js';+import { WwebjsGroups } from './wwebjs-groups';+import { createLogger } from '../../common/services/logger.service';+import { type WwebjsEngineHost } from './wwebjs-host';+import { EngineTransportError } from '../../common/errors/engine-transport.error';++/**+ * Both group reads reported a dead page and then rethrew the raw Puppeteer error, so the caller got+ * HTTP 500 while both routes document 503 (session.controller.ts:446 for the list,+ * group.controller.ts:304 for the membership queue). The list route's own wording says the status+ * exists so a caller is never handed an empty list for a query that never ran; on whatsapp-web.js it+ * could not be produced at all, while Baileys has answered it since baileys-group-list.spec.ts:28.+ */+const logger = createLogger('wwebjs-group-transport-death.spec');++describe('group reads distinguish a dead page from an ordinary failure', () => {+ const transportError = new Error('Protocol error (Runtime.callFunctionOn): Target closed');++ function makeGroups(op: string, reject: unknown): { groups: WwebjsGroups; reportIfPageTransportError: jest.Mock } {+ const client = {+ info: {},+ // requireGroupChat runs before the guarded read, so it must resolve a real group.+ getChatById: jest.fn().mockResolvedValue({ isGroup: true }),+ getChats: op === 'getGroups' ? jest.fn().mockRejectedValue(reject) : jest.fn().mockResolvedValue([]),+ getGroupMembershipRequests:+ op === 'getGroupMembershipRequests' ? jest.fn().mockRejectedValue(reject) : jest.fn().mockResolvedValue([]),+ };+ const reportIfPageTransportError = jest.fn();+ const host = {+ ensureReady: jest.fn(),+ getClient: () => client as unknown as Client,+ isPageTransportError: (error: unknown) => error === transportError,+ reportIfPageTransportError,+ logger,+ } as unknown as WwebjsEngineHost;+ return { groups: new WwebjsGroups(host), reportIfPageTransportError };+ }++ const call = (groups: WwebjsGroups, op: string): Promise<unknown> =>+ ({+ getGroups: () => groups.getGroups(),+ getGroupMembershipRequests: () => groups.getGroupMembershipRequests('[email protected]'),+ })[op]!();++ const OPS = ['getGroups', 'getGroupMembershipRequests'];++ it.each(OPS)('%s answers a dead page with the 503 its route documents', async op => {+ const { groups, reportIfPageTransportError } = makeGroups(op, transportError);++ await expect(call(groups, op)).rejects.toThrow(EngineTransportError);+ expect(reportIfPageTransportError).toHaveBeenCalledWith(transportError, op);+ });++ // Negative twin: an ordinary page-side failure must still surface untouched, so the fix cannot+ // simply relabel every failure as a retryable 503.+ it.each(OPS)('%s still propagates an ordinary failure unchanged', async op => {+ const refusal = new Error('Evaluation failed: group not found');+ const { groups, reportIfPageTransportError } = makeGroups(op, refusal);++ await expect(call(groups, op)).rejects.toBe(refusal);+ expect(reportIfPageTransportError).not.toHaveBeenCalled();+ });+});diff --git a/src/engine/adapters/wwebjs-groups.ts b/src/engine/adapters/wwebjs-groups.tsindex 7840d1a8e..d2c9a8f8b 100644--- a/src/engine/adapters/wwebjs-groups.ts+++ b/src/engine/adapters/wwebjs-groups.ts@@ -18,7 +18,7 @@ import { EngineNotSupportedError } from '../../common/errors/engine-not-supporteimport { GroupNotFoundError } from '../../common/errors/group-not-found.error';import { InvalidInviteCodeError } from '../../common/errors/invalid-invite-code.error';import { toMessageMedia } from './wwebjs-messaging';-import { type WwebjsEngineHost } from './wwebjs-host';+import { type WwebjsEngineHost, withPage } from './wwebjs-host';/*** Extracts the JID of the parent community a group is linked to, if any.@@ -81,7 +81,7 @@ export class WwebjsGroups {async getGroups(): Promise<Group[]> {this.host.ensureReady();- try {+ return withPage(this.host, 'getGroups', async () => {const client = this.client();const chats = await client.getChats();@@ -105,10 +105,7 @@ export class WwebjsGroups {linkedParentJID: extractLinkedParentJID(groupChat.groupMetadata),};});- } catch (error) {- this.host.reportIfPageTransportError(error, 'getGroups');- throw error;- }+ });}async getGroupInfo(groupId: string): Promise<GroupInfo | null> {@@ -524,7 +521,7 @@ export class WwebjsGroups {// non-group jid answered 200 with an empty list, which reads as "this group has no pending// requests" rather than "there is no such group"; Baileys answers the refusal.await this.requireGroupChat(groupId);- try {+ return withPage(this.host, 'getGroupMembershipRequests', async () => {const raw = await this.client().getGroupMembershipRequests(groupId);// Raw page-context store objects: wids can arrive as {_serialized} OR {$1} (the #747// minifier rename), so every id goes through readWid; a requester whose wid is unreadable@@ -551,10 +548,7 @@ export class WwebjsGroups {},];});- } catch (error) {- this.host.reportIfPageTransportError(error, 'getGroupMembershipRequests');- throw error;- }+ });}approveGroupMembershipRequests(groupId: string, participants?: string[]): Promise<ParticipantOperationResult[]> {diff --git a/src/engine/adapters/wwebjs-label-transport-death.spec.ts b/src/engine/adapters/wwebjs-label-transport-death.spec.tsnew file mode 100644index 000000000..87973a90c--- /dev/null+++ b/src/engine/adapters/wwebjs-label-transport-death.spec.ts@@ -0,0 +1,75 @@+import type { Client } from 'whatsapp-web.js';+import { WwebjsLabels } from './wwebjs-labels';+import { createLogger } from '../../common/services/logger.service';+import { type WwebjsEngineHost } from './wwebjs-host';+import { EngineTransportError } from '../../common/errors/engine-transport.error';++/**+ * Three label reads had no error handling on the page call at all, so a dead page was both an opaque+ * 500 and a death the session was never told about; the label write saw only the `[LT01] Only+ * Whatsapp business` case and passed everything else through raw. getChatsByLabel in the same file+ * already made the split, which is why one label read answered 503 and the neighbouring ones 500.+ */+const logger = createLogger('wwebjs-label-transport-death.spec');++describe('label operations distinguish a dead page from an ordinary failure', () => {+ const transportError = new Error('Protocol error (Runtime.callFunctionOn): Target closed');++ function makeLabels(op: string, reject: unknown): { labels: WwebjsLabels; reportIfPageTransportError: jest.Mock } {+ const rejects = (name: string) =>+ op === name ? jest.fn().mockRejectedValue(reject) : jest.fn().mockResolvedValue([]);+ const chat = { getLabels: rejects('getChatLabels') };+ const client = {+ getLabels: rejects('getLabels'),+ getLabelById: op === 'getLabelById' ? jest.fn().mockRejectedValue(reject) : jest.fn().mockResolvedValue(null),+ getChatById: jest.fn().mockResolvedValue(chat),+ addOrRemoveLabels:+ op === 'changeChatLabel' ? jest.fn().mockRejectedValue(reject) : jest.fn().mockResolvedValue(undefined),+ };+ const reportIfPageTransportError = jest.fn();+ const host = {+ ensureReady: jest.fn(),+ getClient: () => client as unknown as Client,+ isPageTransportError: (error: unknown) => error === transportError,+ reportIfPageTransportError,+ logger,+ } as unknown as WwebjsEngineHost;+ return { labels: new WwebjsLabels(host), reportIfPageTransportError };+ }++ // changeChatLabel is private; addLabelToChat is its public entry point.+ const call = (labels: WwebjsLabels, op: string): Promise<unknown> =>+ ({+ getLabels: () => labels.getLabels(),+ getLabelById: () => labels.getLabelById('7'),+ getChatLabels: () => labels.getChatLabels('[email protected]'),+ changeChatLabel: () => labels.addLabelToChat('[email protected]', '7'),+ })[op]!();++ const OPS = ['getLabels', 'getLabelById', 'getChatLabels', 'changeChatLabel'];++ it.each(OPS)('%s answers a dead page with the 503 its route documents', async op => {+ const { labels, reportIfPageTransportError } = makeLabels(op, transportError);++ await expect(call(labels, op)).rejects.toThrow(EngineTransportError);+ expect(reportIfPageTransportError).toHaveBeenCalledWith(transportError, op);+ });++ // Negative twin: an ordinary page-side failure must still surface untouched, so the fix cannot+ // simply relabel every failure as a retryable 503.+ it.each(OPS)('%s still propagates an ordinary failure unchanged', async op => {+ const refusal = new Error('Evaluation failed: label not found');+ const { labels, reportIfPageTransportError } = makeLabels(op, refusal);++ await expect(call(labels, op)).rejects.toBe(refusal);+ expect(reportIfPageTransportError).not.toHaveBeenCalled();+ });++ // The label write's one bespoke mapping must survive the guard: a personal account still gets the+ // "not a Business account" refusal rather than a transport failure.+ it('still maps the page-side LT01 refusal to the unsupported error', async () => {+ const { labels } = makeLabels('changeChatLabel', new Error('[LT01] Only Whatsapp business'));++ await expect(labels.addLabelToChat('[email protected]', '7')).rejects.toThrow(/business/i);+ });+});diff --git a/src/engine/adapters/wwebjs-labels.ts b/src/engine/adapters/wwebjs-labels.tsindex 5a59bf260..d2f27f2e3 100644--- a/src/engine/adapters/wwebjs-labels.ts+++ b/src/engine/adapters/wwebjs-labels.ts@@ -5,7 +5,7 @@ import { isChannelJid, chatKind } from '../identity/wa-id';import { ChatLabelsUnsupportedError } from '../../common/errors/chat-labels-unsupported.error';import { LabelNotFoundError } from '../../common/errors/label-not-found.error';import { EngineTransportError } from '../../common/errors/engine-transport.error';-import { type WwebjsEngineHost } from './wwebjs-host';+import { type WwebjsEngineHost, withPage } from './wwebjs-host';/*** Chat-label operations (WhatsApp Business only) extracted from WhatsAppWebJsAdapter. The adapter@@ -22,7 +22,9 @@ export class WwebjsLabels {async getLabels(): Promise<Label[]> {this.host.ensureReady();- const labels = await (this.client() as unknown as BusinessClient).getLabels();+ const labels = await withPage(this.host, 'getLabels', () =>+ (this.client() as unknown as BusinessClient).getLabels(),+ );if (!labels) {return [];}@@ -81,7 +83,9 @@ export class WwebjsLabels {async getLabelById(labelId: string): Promise<Label | null> {this.host.ensureReady();- const label = await (this.client() as unknown as BusinessClient).getLabelById(labelId);+ const label = await withPage(this.host, 'getLabelById', () =>+ (this.client() as unknown as BusinessClient).getLabelById(labelId),+ );if (!label) {return null;}@@ -99,8 +103,10 @@ export class WwebjsLabels {// Return empty instead of letting the unguarded call throw a TypeError (HTTP 500).return [];}- const chat = await this.client().getChatById(chatId);- const labels = await (chat as unknown as GroupChat).getLabels();+ const labels = await withPage(this.host, 'getChatLabels', async () => {+ const chat = await this.client().getChatById(chatId);+ return (chat as unknown as GroupChat).getLabels();+ });if (!labels) {return [];}@@ -144,7 +150,7 @@ export class WwebjsLabels {ids.delete(labelId);}try {- await this.client().addOrRemoveLabels([...ids], [chatId]);+ await withPage(this.host, 'changeChatLabel', () => 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')) {diff --git a/src/engine/adapters/wwebjs-message-transport-death.spec.ts b/src/engine/adapters/wwebjs-message-transport-death.spec.tsnew file mode 100644index 000000000..d32246a4b--- /dev/null+++ b/src/engine/adapters/wwebjs-message-transport-death.spec.ts@@ -0,0 +1,108 @@+import type { Client } from 'whatsapp-web.js';+import { WwebjsMessaging } from './wwebjs-messaging';+import { createLogger } from '../../common/services/logger.service';+import { type WwebjsEngineHost } from './wwebjs-host';+import { EngineTransportError } from '../../common/errors/engine-transport.error';++/**+ * Nine non-send message operations had no transport handling, so a dead page was an opaque 500 and a+ * death nothing reported. Two of their routes already documented 503 and could not produce it+ * (message.controller.ts:514 delete, :604 star); the other seven gained the declaration with this+ * change.+ *+ * The SEND paths are deliberately absent from this file. A 503 is replay-safe for a non-idempotent+ * POST by this project's own client contract (sdk/go/retry.go:30-42, pinned by+ * sdk/go/client_test.go:279-296 and :317-335), so relabelling a send would invite a duplicate+ * message. Every operation below either reads, or converges on the same state when repeated.+ */+const logger = createLogger('wwebjs-message-transport-death.spec');++describe('non-send message operations distinguish a dead page from an ordinary failure', () => {+ const transportError = new Error('Protocol error (Runtime.callFunctionOn): Target closed');+ const MESSAGE_ID = '[email protected]_ABCDEF';++ function makeMessaging(+ op: string,+ reject: unknown,+ ): { messaging: WwebjsMessaging; reportIfPageTransportError: jest.Mock } {+ // Only the call under test rejects; everything else resolves, so each guard is exercised alone.+ const on = (name: string, ok: unknown) =>+ op === name ? jest.fn().mockRejectedValue(reject) : jest.fn().mockResolvedValue(ok);+ const message = {+ id: { _serialized: MESSAGE_ID, id: 'ABCDEF' },+ hasReaction: true,+ getReactions: on('getMessageReactions', []),+ react: on('reactToMessage', undefined),+ delete: on('deleteMessage', undefined),+ edit: on('editMessage', { id: { _serialized: MESSAGE_ID }, timestamp: 1 }),+ vote: on('votePoll', undefined),+ pin: on('pinMessage', true),+ unpin: on('unpinMessage', true),+ star: on('starMessage', undefined),+ unstar: on('starMessage', undefined),+ };+ const chat = { isGroup: false, fetchMessages: on('getChatHistory', [message]) };+ const client = { getChatById: jest.fn().mockResolvedValue(chat) };+ const reportIfPageTransportError = jest.fn();+ const host = {+ ensureReady: jest.fn(),+ getClient: () => client as unknown as Client,+ isPageTransportError: (error: unknown) => error === transportError,+ reportIfPageTransportError,+ logger,+ } as unknown as WwebjsEngineHost;+ return { messaging: new WwebjsMessaging(host), reportIfPageTransportError };+ }++ const CHAT = '[email protected]';+ const call = (messaging: WwebjsMessaging, op: string): Promise<unknown> =>+ ({+ getChatHistory: () => messaging.getChatHistory(CHAT, 10),+ getMessageReactions: () => messaging.getMessageReactions(CHAT, MESSAGE_ID),+ reactToMessage: () => messaging.reactToMessage(CHAT, MESSAGE_ID, '👍'),+ deleteMessage: () => messaging.deleteMessage(CHAT, MESSAGE_ID),+ editMessage: () => messaging.editMessage(CHAT, MESSAGE_ID, 'new body'),+ votePoll: () => messaging.votePoll(CHAT, MESSAGE_ID, ['a']),+ pinMessage: () => messaging.pinMessage(CHAT, MESSAGE_ID, 86400),+ starMessage: () => messaging.starMessage(CHAT, MESSAGE_ID, true),+ unpinMessage: () => messaging.unpinMessage(CHAT, MESSAGE_ID),+ })[op]!();++ const OPS = [+ 'getChatHistory',+ 'getMessageReactions',+ 'reactToMessage',+ 'deleteMessage',+ 'editMessage',+ 'votePoll',+ 'pinMessage',+ 'starMessage',+ 'unpinMessage',+ ];++ it.each(OPS)('%s answers a dead page with the 503 its route documents', async op => {+ const { messaging, reportIfPageTransportError } = makeMessaging(op, transportError);++ await expect(call(messaging, op)).rejects.toThrow(EngineTransportError);+ expect(reportIfPageTransportError).toHaveBeenCalledWith(transportError, op);+ });++ // Negative twin: an ordinary page-side failure must still surface untouched, so the fix cannot+ // simply relabel every failure as a retryable 503.+ it.each(OPS)('%s still propagates an ordinary failure unchanged', async op => {+ const refusal = new Error('Evaluation failed: message not found');+ const { messaging, reportIfPageTransportError } = makeMessaging(op, refusal);++ await expect(call(messaging, op)).rejects.toBe(refusal);+ expect(reportIfPageTransportError).not.toHaveBeenCalled();+ });++ // votePoll's one bespoke mapping must survive the guard: whatsapp-web.js signals "not a poll" by+ // throwing a bare string, which is a client mistake (400), not a transport failure.+ it('still maps the bare-string vote refusal to a bad request', async () => {+ const { messaging, reportIfPageTransportError } = makeMessaging('votePoll', 'not a poll creation message');++ await expect(messaging.votePoll(CHAT, MESSAGE_ID, ['a'])).rejects.toThrow(/is not a poll/);+ expect(reportIfPageTransportError).not.toHaveBeenCalled();+ });+});diff --git a/src/engine/adapters/wwebjs-messaging.ts b/src/engine/adapters/wwebjs-messaging.tsindex bff4d2aed..38f521761 100644--- a/src/engine/adapters/wwebjs-messaging.ts+++ b/src/engine/adapters/wwebjs-messaging.ts@@ -22,7 +22,7 @@ import { buildIncomingMessageBase } from './message-mapper';import { buildVCard } from './vcard';import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';import { RecipientUnreachableError } from '../../common/errors/recipient-unreachable.error';-import { type WwebjsEngineHost } from './wwebjs-host';+import { type WwebjsEngineHost, withPage } from './wwebjs-host';/*** Map a whatsapp-web.js MessageAck integer to the neutral DeliveryStatus.@@ -199,6 +199,11 @@ export class WwebjsMessaging {return this.host.getClient();}+ /** See {@link withPage} for what a dead page answers here. */+ private withPage<T>(context: string, op: () => Promise<T>): Promise<T> {+ return withPage(this.host, context, op);+ }+// Cache of resolved individual recipients: `<phone>@c.us` -> the id `sendMessage` accepts (a// `<lid>@lid` for a migrated contact, or the confirmed `@c.us` for a non-migrated one). `getNumberId`// is a rate-limited WhatsApp Web existence probe that also throws intermittently, so caching every@@ -608,7 +613,7 @@ export class WwebjsMessaging {async reactToMessage(chatId: string, messageId: string, emoji: string): Promise<void> {this.host.ensureReady();- try {+ await this.withPage('reactToMessage', async () => {// NOTE: do NOT resolve chatId to @lid here — whatsapp-web.js reacts using the found message's own// id, not this chatId, so LID-resolving the lookup gives no send benefit and would miss a message// stored under the pre-migration @c.us chat (#583 R1 review).@@ -619,26 +624,22 @@ export class WwebjsMessaging {throw new MessageNotFoundError(messageId, chatId);}await (message as MessageWithReactions).react(emoji);- this.host.logger.log(`Reacted to message ${messageId} with ${emoji || '(removed)'}`);- } catch (error) {- this.host.reportIfPageTransportError(error, 'reactToMessage');- throw error;- }+ });+ this.host.logger.log(`Reacted to message ${messageId} with ${emoji || '(removed)'}`);}async getMessageReactions(chatId: string, messageId: string): Promise<MessageReaction[]> {this.host.ensureReady();- const chat = await this.client().getChatById(chatId);- const messages = await chat.fetchMessages({ limit: 100 });- const message = messages.find(m => m.id._serialized === messageId);- if (!message) {- throw new MessageNotFoundError(messageId, chatId);- }- const msgWithReactions = message as MessageWithReactions;- if (!msgWithReactions.hasReaction) {- return [];- }- const reactions = await msgWithReactions.getReactions();+ const reactions = await this.withPage('getMessageReactions', async () => {+ const chat = await this.client().getChatById(chatId);+ const messages = await chat.fetchMessages({ limit: 100 });+ const message = messages.find(m => m.id._serialized === messageId);+ if (!message) {+ throw new MessageNotFoundError(messageId, chatId);+ }+ const msgWithReactions = message as MessageWithReactions;+ return msgWithReactions.hasReaction ? msgWithReactions.getReactions() : [];+ });if (!reactions) {return [];}@@ -666,8 +667,10 @@ export class WwebjsMessaging {signal?: AbortSignal,): Promise<IncomingMessage[]> {this.host.ensureReady();- const chat = await this.client().getChatById(chatId);- const messages = await chat.fetchMessages({ limit });+ const messages = await this.withPage('getChatHistory', async () => {+ const chat = await this.client().getChatById(chatId);+ return chat.fetchMessages({ limit });+ });const results: IncomingMessage[] = [];// Aggregate base64 budget across the whole pass: the per-message cap bounds ONE blob, but without// an aggregate bound a 100-message history could stack ~100 × 50 MiB into one response. Once the@@ -749,13 +752,15 @@ export class WwebjsMessaging {// NOTE: do NOT resolve chatId to @lid here — delete operates on the found message's own key, not// this chatId, so LID-resolving the lookup gives no benefit and would miss a message stored under// the pre-migration @c.us chat (#583 R1 review).- const chat = await this.client().getChatById(chatId);- const messages = await chat.fetchMessages({ limit: 100 });- const message = messages.find(m => m.id._serialized === messageId || m.id.id === messageId);- if (!message) {- throw new MessageNotFoundError(messageId, chatId);- }- await message.delete(forEveryone);+ await this.withPage('deleteMessage', async () => {+ const chat = await this.client().getChatById(chatId);+ const messages = await chat.fetchMessages({ limit: 100 });+ const message = messages.find(m => m.id._serialized === messageId || m.id.id === messageId);+ if (!message) {+ throw new MessageNotFoundError(messageId, chatId);+ }+ await message.delete(forEveryone);+ });this.host.logger.log(`Deleted message ${messageId} from chat ${chatId} (forEveryone: ${forEveryone})`);}@@ -765,20 +770,22 @@ export class WwebjsMessaging {// NOTE: do NOT resolve chatId to @lid here — edit operates on the found message's own key, not// this chatId, so LID-resolving the lookup would miss a message stored under the pre-migration// @c.us chat (#583 R1 review).- const chat = await this.client().getChatById(chatId);- // getChatById RESOLVES undefined for an unknown chat (wwebjs does not throw) — that is the same- // client-facing outcome as a message outside the fetch window, not a TypeError (-> 500).- if (!chat) {- throw new MessageNotFoundError(messageId, chatId);- }- const messages = await chat.fetchMessages({ limit: 100 });- const message = messages.find(m => m.id._serialized === messageId || m.id.id === messageId);- if (!message) {- throw new MessageNotFoundError(messageId, chatId);- }- // An edit REPLACES the content, so tags are re-applied rather than preserved: omitting mentions- // drops whatever the original carried. Options omitted entirely when none were asked for.- const edited = mentions?.length ? await message.edit(body, { mentions }) : await message.edit(body);+ const edited = await this.withPage('editMessage', async () => {+ const chat = await this.client().getChatById(chatId);+ // getChatById RESOLVES undefined for an unknown chat (wwebjs does not throw) — that is the same+ // client-facing outcome as a message outside the fetch window, not a TypeError (-> 500).+ if (!chat) {+ throw new MessageNotFoundError(messageId, chatId);+ }+ const messages = await chat.fetchMessages({ limit: 100 });+ const message = messages.find(m => m.id._serialized === messageId || m.id.id === messageId);+ if (!message) {+ throw new MessageNotFoundError(messageId, chatId);+ }+ // An edit REPLACES the content, so tags are re-applied rather than preserved: omitting mentions+ // drops whatever the original carried. Options omitted entirely when none were asked for.+ return mentions?.length ? message.edit(body, { mentions }) : message.edit(body);+ });if (!edited) {// wwebjs RESOLVES null (instead of throwing) when the page-side edit is refused — only the// account's own text messages are editable; surface the refusal, not a phantom success.@@ -813,9 +820,11 @@ export class WwebjsMessaging {this.host.ensureReady();// Same 100-message window as pin/react/delete, so a poll older than that is unreachable and// reported as not-found rather than as a failed vote.- const message = await this.findInFetchWindow(chatId, pollMessageId);try {- await (message as unknown as { vote(selected: string[]): Promise<void> }).vote(options);+ await this.withPage('votePoll', async () => {+ const message = await this.findInFetchWindow(chatId, pollMessageId);+ await (message as unknown as { vote(selected: string[]): Promise<void> }).vote(options);+ });} catch (error) {// vote() throws a BARE STRING (not an Error) when the target is not a poll creation message// (Message.js:1010). Left alone that surfaces as an opaque 500; it is a client mistake, so@@ -830,11 +839,14 @@ export class WwebjsMessaging {async pinMessage(chatId: string, messageId: string, durationSeconds: number): Promise<void> {this.host.ensureReady();- const message = await this.findInFetchWindow(chatId, messageId);// The page-side helper returns false rather than throwing for every refusal — a non-number// duration, a message it cannot resolve, or a send WhatsApp rejected (Injected/Utils.js:1670).// Surface that as a refusal instead of reporting a pin that never happened.- if (!(await message.pin(durationSeconds))) {+ const pinned = await this.withPage('pinMessage', async () => {+ const message = await this.findInFetchWindow(chatId, messageId);+ return message.pin(durationSeconds);+ });+ if (!pinned) {throw new EngineRefusedError(`the pin of message ${messageId} was rejected — in a group only admins may pin, and the duration must be 24h, 7d or 30d`,);@@ -844,20 +856,25 @@ export class WwebjsMessaging {async starMessage(chatId: string, messageId: string, star: boolean): Promise<void> {this.host.ensureReady();- const message = await this.findInFetchWindow(chatId, messageId);// Both resolve void, and the page-side helper silently does nothing when canStarMsg() refuses// the message (Message.js:672-712). There is no signal to map, so a star that WhatsApp declined// is indistinguishable from one it accepted — documented rather than faked into a refusal.- await (star ? message.star() : message.unstar());+ await this.withPage('starMessage', async () => {+ const message = await this.findInFetchWindow(chatId, messageId);+ await (star ? message.star() : message.unstar());+ });this.host.logger.log(`${star ? 'Starred' : 'Unstarred'} message ${messageId} in chat ${chatId}`);}async unpinMessage(chatId: string, messageId: string): Promise<void> {this.host.ensureReady();- const message = await this.findInFetchWindow(chatId, messageId);// unpin() passes duration 0 itself, so the injected non-number guard cannot bite here; a false// return means WhatsApp refused the unpin (e.g. not an admin).- if (!(await message.unpin())) {+ const unpinned = await this.withPage('unpinMessage', async () => {+ const message = await this.findInFetchWindow(chatId, messageId);+ return message.unpin();+ });+ if (!unpinned) {throw new EngineRefusedError(`the unpin of message ${messageId} was rejected — in a group only admins may unpin`);}this.host.logger.log(`Unpinned message ${messageId} in chat ${chatId}`);diff --git a/src/modules/label/label.controller.ts b/src/modules/label/label.controller.tsindex d401d9ef3..4eb82ec64 100644--- a/src/modules/label/label.controller.ts+++ b/src/modules/label/label.controller.ts@@ -24,6 +24,12 @@ export class LabelController {@ApiResponse({ status: 400, description: 'Session not ready or not a business account' })@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })@ApiResponse({ status: 501, description: ENGINE_NOT_SUPPORTED_501 })+ @ApiResponse({+ status: 503,+ description:+ 'The whatsapp-web.js page connection died mid-read, so nothing could be read. Retry once the ' ++ 'session is ready again.',+ })async findAll(@Param('sessionId') sessionId: string) {return this.labelService.getLabels(sessionId);}@@ -36,6 +42,12 @@ export class LabelController {@ApiResponse({ status: 404, description: 'Label not found' })@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })@ApiResponse({ status: 501, description: ENGINE_NOT_SUPPORTED_501 })+ @ApiResponse({+ status: 503,+ description:+ 'The whatsapp-web.js page connection died mid-read, so nothing could be read. Retry once the ' ++ 'session is ready again.',+ })async findOne(@Param('sessionId') sessionId: string, @Param('labelId') labelId: string) {return this.labelService.getLabelById(sessionId, labelId);}@@ -135,6 +147,12 @@ export class LabelController {@ApiResponse({ status: 200, description: 'List of labels for the chat', type: [LabelDto] })@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })@ApiResponse({ status: 501, description: ENGINE_NOT_SUPPORTED_501 })+ @ApiResponse({+ status: 503,+ description:+ 'The whatsapp-web.js page connection died mid-read, so nothing could be read. Retry once the ' ++ 'session is ready again.',+ })async getChatLabels(@Param('sessionId') sessionId: string, @Param('chatId') chatId: string) {return this.labelService.getChatLabels(sessionId, chatId);}diff --git a/src/modules/message/message.controller.ts b/src/modules/message/message.controller.tsindex 7656dc678..085134464 100644--- a/src/modules/message/message.controller.ts+++ b/src/modules/message/message.controller.ts@@ -376,6 +376,12 @@ export class MessageController {})@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })@ApiResponse({ status: 404, description: MESSAGE_NOT_FOUND_404 })+ @ApiResponse({+ status: 503,+ description:+ 'The whatsapp-web.js page connection died mid-request. The change may or may not have been applied; ' ++ 'repeating the request is safe, since it converges on the same state.',+ })async react(@Param('sessionId') sessionId: string, @Body() dto: ReactMessageDto): Promise<{ success: boolean }> {await this.messageService.reactToMessage(sessionId, dto);return { success: true };@@ -409,6 +415,12 @@ export class MessageController {@ApiResponse({ status: 200, description: 'Chat history (most recent messages)', type: [ChatHistoryMessageDto] })@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })@ApiResponse({ status: 501, description: ENGINE_NOT_SUPPORTED_501 })+ @ApiResponse({+ status: 503,+ description:+ 'The whatsapp-web.js page connection died mid-read, so nothing could be read. Retry once the ' ++ 'session is ready again.',+ })async getChatHistory(@Param('sessionId') sessionId: string,@Param('chatId') chatId: string,@@ -448,6 +460,12 @@ export class MessageController {@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })@ApiResponse({ status: 404, description: MESSAGE_NOT_FOUND_404 })@ApiResponse({ status: 501, description: ENGINE_NOT_SUPPORTED_501 })+ @ApiResponse({+ status: 503,+ description:+ 'The whatsapp-web.js page connection died mid-read, so nothing could be read. Retry once the ' ++ 'session is ready again.',+ })async getReactions(@Param('sessionId') sessionId: string,@Param('chatId') chatId: string,@@ -537,6 +555,12 @@ export class MessageController {@ApiResponse({ status: 404, description: 'Poll not found in the chat’s recent history' })@ApiResponse({ status: 501, description: 'Not supported on the Baileys engine' })@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })+ @ApiResponse({+ status: 503,+ description:+ 'The whatsapp-web.js page connection died mid-request. The change may or may not have been applied; ' ++ 'repeating the request is safe, since it converges on the same state.',+ })async votePoll(@Param('sessionId') sessionId: string, @Body() dto: VotePollDto): Promise<{ success: boolean }> {return this.messageService.votePoll(sessionId, dto);}@@ -561,6 +585,12 @@ export class MessageController {})@ApiResponse({ status: 404, description: 'Message not found in the chat' })@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })+ @ApiResponse({+ status: 503,+ description:+ 'The whatsapp-web.js page connection died mid-request. The pin may or may not have been applied; a ' ++ 'retry is safe, but it restarts the pin duration from the moment it succeeds.',+ })async pinMessage(@Param('sessionId') sessionId: string, @Body() dto: PinMessageDto): Promise<{ success: boolean }> {return this.messageService.pinMessage(sessionId, dto);}@@ -580,6 +610,12 @@ export class MessageController {})@ApiResponse({ status: 404, description: 'Message not found in the chat' })@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })+ @ApiResponse({+ status: 503,+ description:+ 'The whatsapp-web.js page connection died mid-request. The change may or may not have been applied; ' ++ 'repeating the request is safe, since it converges on the same state.',+ })async unpinMessage(@Param('sessionId') sessionId: string,@Body() dto: UnpinMessageDto,@@ -637,6 +673,12 @@ export class MessageController {})@ApiResponse({ status: 404, description: 'Message not found' })@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })+ @ApiResponse({+ status: 503,+ description:+ 'The whatsapp-web.js page connection died mid-request. The change may or may not have been applied; ' ++ 'repeating the request is safe, since it converges on the same state.',+ })async edit(@Param('sessionId') sessionId: string, @Body() dto: EditMessageDto): Promise<MessageResponseDto> {return this.messageService.editMessage(sessionId, dto);}