Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(messages): handle unsent lookup failures
Yudhi Armyndharis30f5aaf314ef
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9900d10a2..fb50a6a72 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed- Fix Baileys first-contact addresses and reject phone numbers reported as unregistered before sending.+- Release send idempotency keys when transport explicitly reports that nothing was sent.- Preserve archived media and reactions during concurrent metadata updates.- Keep sent media when merging onto an echo row fails.- Keep inline media when its WhatsApp message ID is unavailable.diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex e86e65b27..bf9acc6f0 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -888,7 +888,7 @@ Two properties to design around:{ "success": true }```-**Errors:** `400` validation, or session not started · `401` · `403` · `404` session not found · `501` the active engine cannot observe presence (whatsapp-web.js exposes only `sendPresenceAvailable`/`sendPresenceUnavailable`, which publish the account's _own_ presence, and emits no presence event) · `409` conflict or engine not ready (retryable)+**Errors:** `400` validation, or session not started · `401` · `403` · `404` session not found · `501` the active engine cannot observe presence (whatsapp-web.js exposes only `sendPresenceAvailable`/`sendPresenceUnavailable`, which publish the account's _own_ presence, and emits no presence event) · `409` conflict or engine not ready (retryable) · `503` Baileys recipient lookup failed or timed out before the operation was sent#### GET /api/sessions/:sessionId/presence/:chatId@@ -1292,15 +1292,16 @@ The single-recipient send routes (`send-text`, `send-template`, `send-image`, `sThe key is 1-255 visible ASCII characters (a UUID works), unique per session, and is held for **24 hours** from the first request. Within that window:-| Retry with the same key | Answer |-| -------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |-| first request succeeded, same route and body | the first response again, with `Idempotent-Replayed: true`; nothing is sent |-| first request still running | `409` `IDEMPOTENCY_KEY_IN_PROGRESS`; retry after it finishes |-| first request failed during an engine send (including `4xx` or `501`), with another server error, or a timeout | `409` `IDEMPOTENCY_OUTCOME_UNKNOWN`: the message may have gone out; check the chat, then use a **new** key |-| first request was refused with `4xx` or `501` before calling the engine | the key was freed, so the retry runs as a new request |-| different route or body (key order in the JSON does not matter) | `422` `IDEMPOTENCY_KEY_REUSED` |+| Retry with the same key | Answer |+| ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |+| first request succeeded, same route and body | the first response again, with `Idempotent-Replayed: true`; nothing is sent |+| first request still running | `409` `IDEMPOTENCY_KEY_IN_PROGRESS`; retry after it finishes |+| first request failed with an uncertain delivery outcome | `409` `IDEMPOTENCY_OUTCOME_UNKNOWN`: the message may have gone out; check the chat, then use a **new** key |+| first request was refused with `4xx` or `501` before calling the engine | the key was freed, so the retry runs as a new request |+| transport explicitly reported that nothing was sent, such as a Baileys recipient lookup timeout | the key was freed, so the retry runs as a new request |+| different route or body (key order in the JSON does not matter) | `422` `IDEMPOTENCY_KEY_REUSED` |-A malformed key, or the header sent twice, gets `400` `IDEMPOTENCY_KEY_INVALID`. A request still pending ten minutes after it was claimed (its node most likely stopped) also reads as `IDEMPOTENCY_OUTCOME_UNKNOWN`. HTTP status alone does not prove that nothing was sent: an engine can report `409` after attempting delivery, so engine-stage failures retain the key conservatively. Keys are stored in the data database (`send_idempotency_keys`); concurrent processes using that database share the claim, and the session-owner proxy forwards the header. This does not change the deployment support limits in [Horizontal scaling](./13-horizontal-scaling.md). `send-bulk` does not take the header: retrying its request can create another batch. A call that outlives the 24-hour key window is outside the retry guarantee.+A malformed key, or the header sent twice, gets `400` `IDEMPOTENCY_KEY_INVALID`. A request still pending ten minutes after it was claimed (its node most likely stopped) also reads as `IDEMPOTENCY_OUTCOME_UNKNOWN`. HTTP status alone does not prove that nothing was sent: an engine can report `409` after attempting delivery, so engine-stage failures retain the key unless transport explicitly proves that nothing was sent. Keys are stored in the data database (`send_idempotency_keys`); concurrent processes using that database share the claim, and the session-owner proxy forwards the header. This does not change the deployment support limits in [Horizontal scaling](./13-horizontal-scaling.md). `send-bulk` does not take the header: retrying its request can create another batch. A call that outlives the 24-hour key window is outside the retry guarantee.#### GET /api/sessions/:sessionId/messages@@ -1785,7 +1786,7 @@ rejected with `400` rather than guessing which half was meant.`messageId` is the WhatsApp message id from the engine. By default (`SIMULATE_TYPING`; set it to `false` to disable) a typing indicator and a humanising pause run before the send: 500 ms plus 45 ms per character, capped at `SIMULATE_TYPING_MAX_MS` (default 5000 ms), with +/-15% jitter.-**Errors:** `400` unknown body field, validation failure, or session not active / blocked by a plugin hook · `401` missing/invalid API key · `403` key role below OPERATOR · `404` the `quotedMessageId` could not be resolved (see Quoted sends) · `500` engine error · `409` conflict or engine not ready (retryable) · `501` not supported on the active engine · `422` the `Idempotency-Key` was already used for a different request (see [Idempotent sends](#idempotent-sends))+**Errors:** `400` unknown body field, validation failure, or session not active / blocked by a plugin hook · `401` missing/invalid API key · `403` key role below OPERATOR · `404` the `quotedMessageId` could not be resolved (see Quoted sends) · `500` engine error · `409` conflict or engine not ready (retryable) · `501` not supported on the active engine · `422` the `Idempotency-Key` was already used for a different request (see [Idempotent sends](#idempotent-sends)) · `503` Baileys recipient lookup failed or timed out before the operation was sent##### Quoted sends@@ -1874,7 +1875,7 @@ Render a stored text template (header/body/footer joined by blank lines, `{{varsDelegates to the send-text path after rendering.-**Errors:** `400` unknown body field, validation failure, neither `templateId` nor `templateName` given, or session not active · `401` missing/invalid API key · `403` key role below OPERATOR · `404` session or template not found · `500` engine error · `409` conflict or engine not ready (retryable) · `422` the `Idempotency-Key` was already used for a different request (see [Idempotent sends](#idempotent-sends))+**Errors:** `400` unknown body field, validation failure, neither `templateId` nor `templateName` given, or session not active · `401` missing/invalid API key · `403` key role below OPERATOR · `404` session or template not found · `500` engine error · `409` conflict or engine not ready (retryable) · `422` the `Idempotency-Key` was already used for a different request (see [Idempotent sends](#idempotent-sends)) · `503` Baileys recipient lookup failed or timed out before the operation was sent#### POST /api/sessions/:sessionId/messages/send-image@@ -2037,7 +2038,7 @@ Send a location pin.{ "messageId": "[email protected]_3EB0ABCD", "timestamp": 1719312000 }```-**Errors:** `400` invalid coords / session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `404` the `quotedMessageId` could not be resolved (see Quoted sends) · `500` engine error · `409` conflict or engine not ready (retryable) · `501` whatsapp-web.js cannot send a location to a channel (`<id>@newsletter`) or a status or broadcast list (`@broadcast`); nothing is sent · `422` the `Idempotency-Key` was already used for a different request (see [Idempotent sends](#idempotent-sends))+**Errors:** `400` invalid coords / session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `404` the `quotedMessageId` could not be resolved (see Quoted sends) · `500` engine error · `409` conflict or engine not ready (retryable) · `501` whatsapp-web.js cannot send a location to a channel (`<id>@newsletter`) or a status or broadcast list (`@broadcast`); nothing is sent · `422` the `Idempotency-Key` was already used for a different request (see [Idempotent sends](#idempotent-sends)) · `503` Baileys recipient lookup failed or timed out before the operation was sent#### POST /api/sessions/:sessionId/messages/send-contact@@ -2070,7 +2071,7 @@ Send a contact card (vCard).{ "messageId": "[email protected]_3EB0ABCD", "timestamp": 1719312000 }```-**Errors:** `400` validation failure / session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `404` the `quotedMessageId` could not be resolved (see Quoted sends) · `500` engine error · `409` conflict or engine not ready (retryable) · `501` whatsapp-web.js cannot send a contact card to a channel (`<id>@newsletter`) or a status or broadcast list (`@broadcast`); nothing is sent · `422` the `Idempotency-Key` was already used for a different request (see [Idempotent sends](#idempotent-sends))+**Errors:** `400` validation failure / session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `404` the `quotedMessageId` could not be resolved (see Quoted sends) · `500` engine error · `409` conflict or engine not ready (retryable) · `501` whatsapp-web.js cannot send a contact card to a channel (`<id>@newsletter`) or a status or broadcast list (`@broadcast`); nothing is sent · `422` the `Idempotency-Key` was already used for a different request (see [Idempotent sends](#idempotent-sends)) · `503` Baileys recipient lookup failed or timed out before the operation was sent#### POST /api/sessions/:sessionId/messages/send-sticker@@ -2135,7 +2136,7 @@ Send a native WhatsApp poll.{ "messageId": "[email protected]_3EB0ABCD", "timestamp": 1719312000 }```-**Errors:** `400` validation failure (option count/length) / session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `404` the `quotedMessageId` could not be resolved (see Quoted sends) · `500` engine error · `409` conflict or engine not ready (retryable) · `501` whatsapp-web.js cannot send a poll to a status or broadcast list (`@broadcast`), nor one with `quotedMessageId` to a channel (`<id>@newsletter`); nothing is sent · `422` the `Idempotency-Key` was already used for a different request (see [Idempotent sends](#idempotent-sends))+**Errors:** `400` validation failure (option count/length) / session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `404` the `quotedMessageId` could not be resolved (see Quoted sends) · `500` engine error · `409` conflict or engine not ready (retryable) · `501` whatsapp-web.js cannot send a poll to a status or broadcast list (`@broadcast`), nor one with `quotedMessageId` to a channel (`<id>@newsletter`); nothing is sent · `422` the `Idempotency-Key` was already used for a different request (see [Idempotent sends](#idempotent-sends)) · `503` Baileys recipient lookup failed or timed out before the operation was sent#### POST /api/sessions/:sessionId/messages/reply@@ -2170,7 +2171,7 @@ Reply to a message, quoting a prior message.The quoted body is best-effort resolved from the DB for the reply preview.-**Errors:** `400` validation failure / session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `404` the quoted message is not found in this chat · `500` engine error · `409` conflict or engine not ready (retryable) · `501` whatsapp-web.js cannot send a reply to a channel (`<id>@newsletter`) or a status or broadcast list (`@broadcast`); nothing is sent · `422` the `Idempotency-Key` was already used for a different request (see [Idempotent sends](#idempotent-sends))+**Errors:** `400` validation failure / session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `404` the quoted message is not found in this chat · `500` engine error · `409` conflict or engine not ready (retryable) · `501` whatsapp-web.js cannot send a reply to a channel (`<id>@newsletter`) or a status or broadcast list (`@broadcast`); nothing is sent · `422` the `Idempotency-Key` was already used for a different request (see [Idempotent sends](#idempotent-sends)) · `503` Baileys recipient lookup failed or timed out before the operation was sent#### POST /api/sessions/:sessionId/messages/click-button@@ -2213,7 +2214,7 @@ Tap a choice on a WhatsApp Business button / list prompt by sending the structur> render after the store evicts the prompt, and a tap then 404s. URL/call CTA buttons cannot be> clicked this way, only quick-reply style choices and list rows.-**Errors:** `400` validation failure, session not active, the message is not a clickable prompt, or `buttonId` is not among its choices · `401` · `403` · `404` prompt not in the engine store / wrong chat · `501` whatsapp-web.js · `409` conflict or engine not ready (retryable) · `500` engine error+**Errors:** `400` validation failure, session not active, the message is not a clickable prompt, or `buttonId` is not among its choices · `401` · `403` · `404` prompt not in the engine store / wrong chat · `501` whatsapp-web.js · `409` conflict or engine not ready (retryable) · `500` engine error · `503` Baileys recipient lookup failed or timed out before the operation was sent#### POST /api/sessions/:sessionId/messages/forward@@ -2247,7 +2248,7 @@ Forward a message from one chat to another.`messageId` may be an empty string when the engine could not recover the forwarded copy's id.-**Errors:** `400` validation failure / session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `404` the message to forward is not found in `fromChatId` · `500` engine error · `409` conflict or engine not ready (retryable) · `422` the `Idempotency-Key` was already used for a different request (see [Idempotent sends](#idempotent-sends))+**Errors:** `400` validation failure / session not active / unknown body field · `401` missing/invalid API key · `403` key role below OPERATOR · `404` the message to forward is not found in `fromChatId` · `500` engine error · `409` conflict or engine not ready (retryable) · `422` the `Idempotency-Key` was already used for a different request (see [Idempotent sends](#idempotent-sends)) · `503` Baileys recipient lookup failed or timed out before the operation was sent#### POST /api/sessions/:sessionId/messages/reactdiff --git a/openapi.json b/openapi.jsonindex cad2ecb14..efe1d8cf3 100644--- a/openapi.json+++ b/openapi.json@@ -2263,6 +2263,16 @@}}}+ },+ "503": {+ "description": "Baileys could not complete the recipient lookup within the request budget. On send routes, no message was handed to WhatsApp for this lookup failure.",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }}},"summary": "Subscribe to a chat's presence",@@ -4430,6 +4440,16 @@}}}+ },+ "503": {+ "description": "Baileys could not complete the recipient lookup within the request budget. On send routes, no message was handed to WhatsApp for this lookup failure.",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }}},"summary": "Send a text message",@@ -4541,6 +4561,16 @@}}}+ },+ "503": {+ "description": "Baileys could not complete the recipient lookup within the request budget. On send routes, no message was handed to WhatsApp for this lookup failure.",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }}},"summary": "Render a stored text template and send it as a text message",@@ -4674,7 +4704,7 @@}},"503": {- "description": "The session routes its `url` fetches through an egress proxy, and the fetch failed or timed out before any response arrived, so the request was not carried out. The proxy or the target behind it may be at fault; the gateway cannot tell which. Retryable, but a `503` that persists while the proxy works points at the `url`. Without a session proxy the same failure answers `400`.",+ "description": "The session routes its `url` fetches through an egress proxy, and the fetch failed or timed out before any response arrived, so the request was not carried out. The proxy or the target behind it may be at fault; the gateway cannot tell which. Retryable, but a `503` that persists while the proxy works points at the `url`. Without a session proxy the same failure answers `400`. Baileys could not complete the recipient lookup within the request budget. On send routes, no message was handed to WhatsApp for this lookup failure.","content": {"application/json": {"schema": {@@ -4814,7 +4844,7 @@}},"503": {- "description": "The session routes its `url` fetches through an egress proxy, and the fetch failed or timed out before any response arrived, so the request was not carried out. The proxy or the target behind it may be at fault; the gateway cannot tell which. Retryable, but a `503` that persists while the proxy works points at the `url`. Without a session proxy the same failure answers `400`.",+ "description": "The session routes its `url` fetches through an egress proxy, and the fetch failed or timed out before any response arrived, so the request was not carried out. The proxy or the target behind it may be at fault; the gateway cannot tell which. Retryable, but a `503` that persists while the proxy works points at the `url`. Without a session proxy the same failure answers `400`. Baileys could not complete the recipient lookup within the request budget. On send routes, no message was handed to WhatsApp for this lookup failure.","content": {"application/json": {"schema": {@@ -4955,7 +4985,7 @@}},"503": {- "description": "The session routes its `url` fetches through an egress proxy, and the fetch failed or timed out before any response arrived, so the request was not carried out. The proxy or the target behind it may be at fault; the gateway cannot tell which. Retryable, but a `503` that persists while the proxy works points at the `url`. Without a session proxy the same failure answers `400`.",+ "description": "The session routes its `url` fetches through an egress proxy, and the fetch failed or timed out before any response arrived, so the request was not carried out. The proxy or the target behind it may be at fault; the gateway cannot tell which. Retryable, but a `503` that persists while the proxy works points at the `url`. Without a session proxy the same failure answers `400`. Baileys could not complete the recipient lookup within the request budget. On send routes, no message was handed to WhatsApp for this lookup failure.","content": {"application/json": {"schema": {@@ -5096,7 +5126,7 @@}},"503": {- "description": "The session routes its `url` fetches through an egress proxy, and the fetch failed or timed out before any response arrived, so the request was not carried out. The proxy or the target behind it may be at fault; the gateway cannot tell which. Retryable, but a `503` that persists while the proxy works points at the `url`. Without a session proxy the same failure answers `400`.",+ "description": "The session routes its `url` fetches through an egress proxy, and the fetch failed or timed out before any response arrived, so the request was not carried out. The proxy or the target behind it may be at fault; the gateway cannot tell which. Retryable, but a `503` that persists while the proxy works points at the `url`. Without a session proxy the same failure answers `400`. Baileys could not complete the recipient lookup within the request budget. On send routes, no message was handed to WhatsApp for this lookup failure.","content": {"application/json": {"schema": {@@ -5168,7 +5198,7 @@}},"400": {- "description": "The request was rejected before anything was sent. Among the causes: the recipient could not be addressed — WhatsApp reports no deliverable id for that `chatId`, which is how it says the number is not on WhatsApp — as well as body validation and a session that is not active.",+ "description": "Baileys rejects a phone number reported as unregistered. The request was rejected before anything was sent. Among the causes: the recipient could not be addressed — WhatsApp reports no deliverable id for that `chatId`, which is how it says the number is not on WhatsApp — as well as body validation and a session that is not active.","content": {"application/json": {"schema": {@@ -5226,6 +5256,16 @@}}}+ },+ "503": {+ "description": "Baileys could not complete the recipient lookup within the request budget. On send routes, no message was handed to WhatsApp for this lookup failure.",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }}},"summary": "Send a location message",@@ -5289,7 +5329,7 @@}},"400": {- "description": "The request was rejected before anything was sent. Among the causes: the recipient could not be addressed — WhatsApp reports no deliverable id for that `chatId`, which is how it says the number is not on WhatsApp — as well as body validation and a session that is not active.",+ "description": "Baileys rejects a phone number reported as unregistered. The request was rejected before anything was sent. Among the causes: the recipient could not be addressed — WhatsApp reports no deliverable id for that `chatId`, which is how it says the number is not on WhatsApp — as well as body validation and a session that is not active.","content": {"application/json": {"schema": {@@ -5347,6 +5387,16 @@}}}+ },+ "503": {+ "description": "Baileys could not complete the recipient lookup within the request budget. On send routes, no message was handed to WhatsApp for this lookup failure.",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }}},"summary": "Send a contact card message",@@ -5409,7 +5459,7 @@}},"400": {- "description": "The request was rejected before anything was sent. Among the causes: the recipient could not be addressed — WhatsApp reports no deliverable id for that `chatId`, which is how it says the number is not on WhatsApp — as well as body validation and a session that is not active.",+ "description": "Baileys rejects a phone number reported as unregistered. The request was rejected before anything was sent. Among the causes: the recipient could not be addressed — WhatsApp reports no deliverable id for that `chatId`, which is how it says the number is not on WhatsApp — as well as body validation and a session that is not active.","content": {"application/json": {"schema": {@@ -5479,7 +5529,7 @@}},"503": {- "description": "The session routes its `url` fetches through an egress proxy, and the fetch failed or timed out before any response arrived, so the request was not carried out. The proxy or the target behind it may be at fault; the gateway cannot tell which. Retryable, but a `503` that persists while the proxy works points at the `url`. Without a session proxy the same failure answers `400`.",+ "description": "The session routes its `url` fetches through an egress proxy, and the fetch failed or timed out before any response arrived, so the request was not carried out. The proxy or the target behind it may be at fault; the gateway cannot tell which. Retryable, but a `503` that persists while the proxy works points at the `url`. Without a session proxy the same failure answers `400`. Baileys could not complete the recipient lookup within the request budget. On send routes, no message was handed to WhatsApp for this lookup failure.","content": {"application/json": {"schema": {@@ -5553,7 +5603,7 @@}},"400": {- "description": "The request was rejected before anything was sent. Among the causes: the recipient could not be addressed — WhatsApp reports no deliverable id for that `chatId`, which is how it says the number is not on WhatsApp — as well as body validation and a session that is not active.",+ "description": "Baileys rejects a phone number reported as unregistered. The request was rejected before anything was sent. Among the causes: the recipient could not be addressed — WhatsApp reports no deliverable id for that `chatId`, which is how it says the number is not on WhatsApp — as well as body validation and a session that is not active.","content": {"application/json": {"schema": {@@ -5611,6 +5661,16 @@}}}+ },+ "503": {+ "description": "Baileys could not complete the recipient lookup within the request budget. On send routes, no message was handed to WhatsApp for this lookup failure.",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }}},"summary": "Send a native WhatsApp poll",@@ -5664,7 +5724,7 @@}},"400": {- "description": "The request was rejected before anything was sent. Among the causes: the recipient could not be addressed — WhatsApp reports no deliverable id for that `chatId`, which is how it says the number is not on WhatsApp — as well as body validation and a session that is not active.",+ "description": "Baileys rejects a phone number reported as unregistered. The request was rejected before anything was sent. Among the causes: the recipient could not be addressed — WhatsApp reports no deliverable id for that `chatId`, which is how it says the number is not on WhatsApp — as well as body validation and a session that is not active.","content": {"application/json": {"schema": {@@ -5732,6 +5792,16 @@}}}+ },+ "503": {+ "description": "Baileys could not complete the recipient lookup within the request budget. On send routes, no message was handed to WhatsApp for this lookup failure.",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }}},"summary": "Reply to a message",@@ -5835,6 +5905,16 @@}}}+ },+ "503": {+ "description": "Baileys could not complete the recipient lookup within the request budget. On send routes, no message was handed to WhatsApp for this lookup failure.",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }}},"summary": "Click a button on a WhatsApp Business prompt (Baileys only)",@@ -5888,7 +5968,7 @@}},"400": {- "description": "The request was rejected before anything was sent. Among the causes: the recipient could not be addressed — WhatsApp reports no deliverable id for that `chatId`, which is how it says the number is not on WhatsApp — as well as body validation and a session that is not active.",+ "description": "Baileys rejects a phone number reported as unregistered. The request was rejected before anything was sent. Among the causes: the recipient could not be addressed — WhatsApp reports no deliverable id for that `chatId`, which is how it says the number is not on WhatsApp — as well as body validation and a session that is not active.","content": {"application/json": {"schema": {@@ -5946,6 +6026,16 @@}}}+ },+ "503": {+ "description": "Baileys could not complete the recipient lookup within the request budget. On send routes, no message was handed to WhatsApp for this lookup failure.",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }}},"summary": "Forward a message to another chat",@@ -6040,7 +6130,7 @@}},"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.",+ "description": "Baileys could not complete the recipient lookup within the request budget. On send routes, no message was handed to WhatsApp for this lookup failure. 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.","content": {"application/json": {"schema": {@@ -6630,7 +6720,7 @@}},"503": {- "description": "WhatsApp did not answer within the request budget. The change may or may not have been applied — the gateway stopped waiting for a confirmation that never came.",+ "description": "Baileys could not complete the recipient lookup within the request budget. On send routes, no message was handed to WhatsApp for this lookup failure. WhatsApp did not answer within the request budget. The change may or may not have been applied — the gateway stopped waiting for a confirmation that never came.","content": {"application/json": {"schema": {@@ -6844,7 +6934,7 @@}},"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.",+ "description": "Baileys could not complete the recipient lookup within the request budget. On send routes, no message was handed to WhatsApp for this lookup failure. 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.","content": {"application/json": {"schema": {@@ -6946,7 +7036,7 @@}},"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.",+ "description": "Baileys could not complete the recipient lookup within the request budget. On send routes, no message was handed to WhatsApp for this lookup failure. 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.","content": {"application/json": {"schema": {@@ -7150,7 +7240,7 @@}},"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.",+ "description": "Baileys could not complete the recipient lookup within the request budget. On send routes, no message was handed to WhatsApp for this lookup failure. 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.","content": {"application/json": {"schema": {@@ -15517,7 +15607,7 @@}},"400": {- "description": "Product has no image (a product card requires one), a plugin blocked the send, or a plugin returned an invalid productId or body.",+ "description": "Recipient reported as unregistered, product has no image, a plugin blocked the send, or a plugin returned an invalid productId or body.","content": {"application/json": {"schema": {@@ -15577,7 +15667,7 @@}},"503": {- "description": "WhatsApp did not answer the catalog query within the request budget, or rate-limited it. For some business accounts WhatsApp never answers it, so a retry may not help.",+ "description": "WhatsApp did not answer the catalog query within the request budget, or rate-limited it. For some business accounts WhatsApp never answers it, so a retry may not help. Baileys could not complete the recipient lookup within the request budget. On send routes, no message was handed to WhatsApp for this lookup failure.","content": {"application/json": {"schema": {diff --git a/src/common/errors/engine-send-failure.ts b/src/common/errors/engine-send-failure.tsindex 54f9cba2b..743a59b68 100644--- a/src/common/errors/engine-send-failure.ts+++ b/src/common/errors/engine-send-failure.ts@@ -1,4 +1,4 @@-/** Errors escaping an engine send, including its failure bookkeeping, have an uncertain outcome. */+/** Record that an error escaped an engine send, independently of its HTTP status. */const attemptedSendFailures = new WeakSet<object>();export function markEngineSendFailure<T>(error: T): T {diff --git a/src/common/openapi/engine-status-responses.ts b/src/common/openapi/engine-status-responses.tsindex f8ef74e83..55326cf70 100644--- a/src/common/openapi/engine-status-responses.ts+++ b/src/common/openapi/engine-status-responses.ts@@ -85,6 +85,7 @@ export const SESSION_NOT_STARTED_404 =* a 404 meaning that four of the six routes carrying this constant do not even declare.*/export const RECIPIENT_UNREACHABLE_400 =+ 'Baileys rejects a phone number reported as unregistered. ' +'The request was rejected before anything was sent. Among the causes: the recipient could not be ' +'addressed — WhatsApp reports no deliverable id for that `chatId`, which is how it says the number ' +'is not on WhatsApp — as well as body validation and a session that is not active.';@@ -94,6 +95,10 @@ export const ENGINE_REFUSED_403 ='WhatsApp refused the operation. The request was well formed — the refusal happened WhatsApp-side, ' +'most often because the account lacks the admin rights the operation requires.';+export const RECIPIENT_LOOKUP_503 =+ 'Baileys could not complete the recipient lookup within the request budget. On send routes, ' ++ 'no message was handed to WhatsApp for this lookup failure.';+/** `MessageNotFoundError` (404): outside the adapter's lookup window, or revoked. */export const MESSAGE_NOT_FOUND_404 ="No such message: the id is outside the engine's lookup window (roughly the last hundred messages " +diff --git a/src/config/openapi-contract.spec.ts b/src/config/openapi-contract.spec.tsindex ded025fff..e31e2a6fa 100644--- a/src/config/openapi-contract.spec.ts+++ b/src/config/openapi-contract.spec.ts@@ -16,6 +16,23 @@ const snapshot = (): OpenAPIObject =>JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'openapi.json'), 'utf8')) as OpenAPIObject;describe('openapi.json structural invariants', () => {+ it('message send responses document recipient lookup failures', () => {+ const routes: string[] = [];+ for (const [route, item] of Object.entries(snapshot().paths)) {+ const responses = item.post?.responses ?? {};+ const sendsMessage = ['200', '201'].some(status => {+ const response = responses[status];+ if (!response || '$ref' in response) return false;+ const schema = response.content?.['application/json']?.schema;+ return schema && '$ref' in schema && schema.$ref.endsWith('/MessageResponseDto');+ });+ if (!sendsMessage) continue;+ routes.push(route);+ expect(responses['503']).toBeDefined();+ }+ expect(routes.length).toBeGreaterThan(0);+ });+// OpenAPI 3.0 requires every template expression in a path to resolve to a declared path parameter,// on the path item or on the operation. A route whose handler never binds the parameter — a// class-level prefix nothing reads, or a wildcard read off the request — publishes the template withdiff --git a/src/modules/catalog/catalog.controller.ts b/src/modules/catalog/catalog.controller.tsindex 91f6291f9..3907a39de 100644--- a/src/modules/catalog/catalog.controller.ts+++ b/src/modules/catalog/catalog.controller.ts@@ -5,7 +5,11 @@ import { SendProductDto, ProductQueryDto } from './dto/send-product.dto';import { ChatScoped, RequireRole } from '../auth/decorators/auth.decorators';import { ApiKeyRole } from '../auth/entities/api-key.entity';import { CatalogDto, PaginatedProductsDto, ProductDto, ProductMessageResponseDto } from './dto/catalog-response.dto';-import { ENGINE_NOT_READY_409, SESSION_NOT_STARTED_404 } from '../../common/openapi/engine-status-responses';+import {+ ENGINE_NOT_READY_409,+ RECIPIENT_LOOKUP_503,+ SESSION_NOT_STARTED_404,+} from '../../common/openapi/engine-status-responses';/*** Every catalog read walks WhatsApp's business-catalog IQ, which the server simply leaves@@ -90,15 +94,15 @@ export class CatalogController {@ApiResponse({status: 400,description:- 'Product has no image (a product card requires one), a plugin blocked the send, or a plugin returned an invalid productId or body.',+ 'Recipient reported as unregistered, product has no image, a plugin blocked the send, or a plugin returned an invalid productId or body.',})@ApiResponse({status: 501,description: 'Not supported by the active engine: whatsapp-web.js cannot send product messages.',})- @ApiResponse({ status: 503, description: CATALOG_TIMEOUT_503 })@ApiResponse({ status: 403, description: CATALOG_REFUSED_403 })@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })+ @ApiResponse({ status: 503, description: `${CATALOG_TIMEOUT_503} ${RECIPIENT_LOOKUP_503}` })async sendProduct(@Param('sessionId') sessionId: string, @Body() dto: SendProductDto) {return this.catalogService.sendProduct(sessionId, dto.chatId, dto.productId, dto.body);}diff --git a/src/modules/message/idempotency/send-idempotency.interceptor.spec.ts b/src/modules/message/idempotency/send-idempotency.interceptor.spec.tsindex aa7b64dea..6b678632b 100644--- a/src/modules/message/idempotency/send-idempotency.interceptor.spec.ts+++ b/src/modules/message/idempotency/send-idempotency.interceptor.spec.ts@@ -11,6 +11,7 @@ import {import { lastValueFrom, of, throwError } from 'rxjs';import { EngineNotReadyError } from '../../../common/errors/engine-not-ready.error';import { markEngineSendFailure } from '../../../common/errors/engine-send-failure';+import { EngineNotSentError } from '../../../common/errors/engine-not-sent.error';import { SendIdempotencyInterceptor, sendFailureProvesNothingSent } from './send-idempotency.interceptor';import { hashSendRequest, SendIdempotencyService } from './send-idempotency.service';@@ -130,6 +131,13 @@ describe('SendIdempotencyInterceptor', () => {expect(store.release).not.toHaveBeenCalled();});+ it('releases the key when engine transport explicitly reports nothing was sent', async () => {+ const error = markEngineSendFailure(new EngineNotSentError('recipient lookup timed out'));+ await expect(run(contextFor({ 'idempotency-key': 'k-1' }), () => throwError(() => error))).rejects.toBe(error);+ expect(store.release).toHaveBeenCalledWith('row-1');+ expect(store.markFailed).not.toHaveBeenCalled();+ });+it('still answers the send when recording its outcome fails', async () => {store.complete.mockRejectedValue(new Error('db down'));diff --git a/src/modules/message/idempotency/send-idempotency.interceptor.ts b/src/modules/message/idempotency/send-idempotency.interceptor.tsindex 5c78ad1a2..76d854fe5 100644--- a/src/modules/message/idempotency/send-idempotency.interceptor.ts+++ b/src/modules/message/idempotency/send-idempotency.interceptor.ts@@ -13,6 +13,7 @@ import type { Request, Response } from 'express';import { from, lastValueFrom, Observable, of } from 'rxjs';import { createLogger } from '../../../common/services/logger.service';import { isEngineSendFailure } from '../../../common/errors/engine-send-failure';+import { EngineNotSentError } from '../../../common/errors/engine-not-sent.error';import { hashSendRequest, isValidIdempotencyKey, SendIdempotencyService } from './send-idempotency.service';/** Request header a client sets to make a send safe to retry. */@@ -24,10 +25,11 @@ export const IDEMPOTENT_REPLAYED_HEADER = 'idempotent-replayed';* Whether a failed send proves nothing reached WhatsApp, so the key can be freed for a retry.** A 4xx or 501 before the engine call is a refusal. Errors escaping the shared engine-send failure- * boundary stay uncertain regardless of status: a disconnected socket can report 409 after+ * boundary stay uncertain unless transport explicitly reports nothing was sent: a socket can report 409 after* WhatsApp accepted the message. Other server errors/timeouts also keep the key taken.*/export function sendFailureProvesNothingSent(error: unknown): boolean {+ if (error instanceof EngineNotSentError) return true;if (isEngineSendFailure(error) || !(error instanceof HttpException)) return false;const status: number = error.getStatus();const notImplemented: number = HttpStatus.NOT_IMPLEMENTED;diff --git a/src/modules/message/message.controller.ts b/src/modules/message/message.controller.tsindex 1043624fb..eef14f4bb 100644--- a/src/modules/message/message.controller.ts+++ b/src/modules/message/message.controller.ts@@ -59,6 +59,7 @@ import {MEDIA_URL_PROXY_503,MESSAGE_NOT_FOUND_404,RECIPIENT_UNREACHABLE_400,+ RECIPIENT_LOOKUP_503,} from '../../common/openapi/engine-status-responses';import { IdempotentSend } from './idempotency/idempotent-send.decorator';@@ -178,6 +179,7 @@ export class MessageController {})@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })@ApiResponse({ status: 501, description: `${CUSTOM_LINK_PREVIEW_501} ${QUOTED_SEND_501}` })+ @ApiResponse({ status: 503, description: RECIPIENT_LOOKUP_503 })async sendText(@Param('sessionId') sessionId: string, @Body() dto: SendTextMessageDto): Promise<MessageResponseDto> {return this.messageService.sendText(sessionId, dto);}@@ -199,6 +201,7 @@ export class MessageController {})@ApiResponse({ status: 404, description: 'Template not found' })@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })+ @ApiResponse({ status: 503, description: RECIPIENT_LOOKUP_503 })async sendTemplate(@Param('sessionId') sessionId: string,@Body() dto: SendTemplateMessageDto,@@ -227,7 +230,7 @@ export class MessageController {@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })@ApiResponse({ status: 501, description: `${CHANNEL_MEDIA_501} ${QUOTED_SEND_501}` })@ApiResponse({ status: 413, description: MEDIA_TOO_LARGE_413 })- @ApiResponse({ status: 503, description: MEDIA_URL_PROXY_503 })+ @ApiResponse({ status: 503, description: `${MEDIA_URL_PROXY_503} ${RECIPIENT_LOOKUP_503}` })async sendImage(@Param('sessionId') sessionId: string,@Body() dto: SendMediaMessageDto,@@ -254,7 +257,7 @@ export class MessageController {@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })@ApiResponse({ status: 501, description: `${CHANNEL_MEDIA_501} ${QUOTED_SEND_501}` })@ApiResponse({ status: 413, description: MEDIA_TOO_LARGE_413 })- @ApiResponse({ status: 503, description: MEDIA_URL_PROXY_503 })+ @ApiResponse({ status: 503, description: `${MEDIA_URL_PROXY_503} ${RECIPIENT_LOOKUP_503}` })async sendVideo(@Param('sessionId') sessionId: string,@Body() dto: SendMediaMessageDto,@@ -281,7 +284,7 @@ export class MessageController {@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })@ApiResponse({ status: 501, description: `${CHANNEL_MEDIA_501} ${QUOTED_SEND_501}` })@ApiResponse({ status: 413, description: MEDIA_TOO_LARGE_413 })- @ApiResponse({ status: 503, description: MEDIA_URL_PROXY_503 })+ @ApiResponse({ status: 503, description: `${MEDIA_URL_PROXY_503} ${RECIPIENT_LOOKUP_503}` })async sendAudio(@Param('sessionId') sessionId: string,@Body() dto: SendAudioMessageDto,@@ -308,7 +311,7 @@ export class MessageController {@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })@ApiResponse({ status: 501, description: `${CHANNEL_MEDIA_501} ${QUOTED_SEND_501}` })@ApiResponse({ status: 413, description: MEDIA_TOO_LARGE_413 })- @ApiResponse({ status: 503, description: MEDIA_URL_PROXY_503 })+ @ApiResponse({ status: 503, description: `${MEDIA_URL_PROXY_503} ${RECIPIENT_LOOKUP_503}` })async sendDocument(@Param('sessionId') sessionId: string,@Body() dto: SendMediaMessageDto,@@ -333,6 +336,7 @@ export class MessageController {@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })@ApiResponse({ status: 400, description: RECIPIENT_UNREACHABLE_400 })@ApiResponse({ status: 501, description: wwebjsRefuses501(`a location to ${CHANNEL_OR_BROADCAST}`) })+ @ApiResponse({ status: 503, description: RECIPIENT_LOOKUP_503 })async sendLocation(@Param('sessionId') sessionId: string, @Body() dto: SendLocationDto): Promise<MessageResponseDto> {return this.messageService.sendLocation(sessionId, dto);}@@ -352,6 +356,7 @@ export class MessageController {@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })@ApiResponse({ status: 400, description: RECIPIENT_UNREACHABLE_400 })@ApiResponse({ status: 501, description: wwebjsRefuses501(`a contact card to ${CHANNEL_OR_BROADCAST}`) })+ @ApiResponse({ status: 503, description: RECIPIENT_LOOKUP_503 })async sendContact(@Param('sessionId') sessionId: string, @Body() dto: SendContactDto): Promise<MessageResponseDto> {return this.messageService.sendContact(sessionId, dto);}@@ -375,7 +380,7 @@ export class MessageController {description: `${CHANNEL_MEDIA_501} ${wwebjsRefuses501('a sticker to a status or broadcast list (`@broadcast`) either')}`,})@ApiResponse({ status: 413, description: MEDIA_TOO_LARGE_413 })- @ApiResponse({ status: 503, description: MEDIA_URL_PROXY_503 })+ @ApiResponse({ status: 503, description: `${MEDIA_URL_PROXY_503} ${RECIPIENT_LOOKUP_503}` })async sendSticker(@Param('sessionId') sessionId: string,@Body() dto: SendMediaMessageDto,@@ -403,6 +408,7 @@ export class MessageController {'a poll to a status or broadcast list (`@broadcast`), nor one with `quotedMessageId` to a channel (`<id>@newsletter`)',),})+ @ApiResponse({ status: 503, description: RECIPIENT_LOOKUP_503 })async sendPoll(@Param('sessionId') sessionId: string, @Body() dto: SendPollDto): Promise<MessageResponseDto> {return this.messageService.sendPoll(sessionId, dto);}@@ -423,6 +429,7 @@ export class MessageController {@ApiResponse({ status: 400, description: RECIPIENT_UNREACHABLE_400 })@ApiResponse({ status: 404, description: MESSAGE_NOT_FOUND_404 })@ApiResponse({ status: 501, description: wwebjsRefuses501(`a reply to ${CHANNEL_OR_BROADCAST}`) })+ @ApiResponse({ status: 503, description: RECIPIENT_LOOKUP_503 })async reply(@Param('sessionId') sessionId: string, @Body() dto: ReplyMessageDto): Promise<MessageResponseDto> {return this.messageService.reply(sessionId, dto);}@@ -454,6 +461,7 @@ export class MessageController {@ApiResponse({ status: 404, description: MESSAGE_NOT_FOUND_404 })@ApiResponse({ status: 501, description: ENGINE_NOT_SUPPORTED_501 })@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })+ @ApiResponse({ status: 503, description: RECIPIENT_LOOKUP_503 })async clickButton(@Param('sessionId') sessionId: string, @Body() dto: ClickButtonDto): Promise<MessageResponseDto> {return this.messageService.clickButton(sessionId, dto);}@@ -472,6 +480,7 @@ export class MessageController {@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })@ApiResponse({ status: 400, description: RECIPIENT_UNREACHABLE_400 })@ApiResponse({ status: 404, description: MESSAGE_NOT_FOUND_404 })+ @ApiResponse({ status: 503, description: RECIPIENT_LOOKUP_503 })async forward(@Param('sessionId') sessionId: string, @Body() dto: ForwardMessageDto): Promise<MessageResponseDto> {return this.messageService.forward(sessionId, dto);}@@ -498,6 +507,8 @@ export class MessageController {@ApiResponse({status: 503,description:+ RECIPIENT_LOOKUP_503 ++ ' ' +'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.',})@@ -729,6 +740,8 @@ export class MessageController {@ApiResponse({status: 503,description:+ RECIPIENT_LOOKUP_503 ++ ' ' +'WhatsApp did not answer within the request budget. The change may or may not have been applied — ' +'the gateway stopped waiting for a confirmation that never came.',})@@ -792,6 +805,8 @@ export class MessageController {@ApiResponse({status: 503,description:+ RECIPIENT_LOOKUP_503 ++ ' ' +'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.',})@@ -818,6 +833,8 @@ export class MessageController {@ApiResponse({status: 503,description:+ RECIPIENT_LOOKUP_503 ++ ' ' +'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.',})@@ -883,6 +900,8 @@ export class MessageController {@ApiResponse({status: 503,description:+ RECIPIENT_LOOKUP_503 ++ ' ' +'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.',})diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.tsindex 72eaf0cfa..eda224a0f 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -61,6 +61,7 @@ import {ENGINE_NOT_READY_409,PAIRING_NOT_READY_409,PAIRING_TRANSPORT_503,+ RECIPIENT_LOOKUP_503,} from '../../common/openapi/engine-status-responses';@ApiTags('sessions')@@ -637,6 +638,7 @@ export class SessionController {@ApiResponse({ status: 404, description: 'Session not found' })@ApiResponse({ status: 501, description: 'The active engine cannot observe presence (whatsapp-web.js)' })@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })+ @ApiResponse({ status: 503, description: RECIPIENT_LOOKUP_503 })async subscribeToPresence(@Param('sessionId', ParseUUIDPipe) id: string,@Body() dto: SubscribePresenceDto,