Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(wwebjs): answer 503 when a list read outruns the protocol timeout
Yudhi Armyndharis9caddb70a3d4
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex a80421341..1989f0648 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -491,7 +491,7 @@ is the instant the mute ends in epoch milliseconds (`0` = indefinite), the sameSorted by `timestamp` DESC (most recent first) then paginated. `timestamp` is an epoch number (seconds). `kind` is the user-facing chat discriminator — one of `individual|group|channel|status|broadcast|unknown`; `isGroup` is retained for back-compat (true only for `kind: "group"`).-**Errors:** `400` session not started · `401` · `403` · `404` session not found · `409` session not connected (also answered for a few seconds while WhatsApp Web reloads its page and the engine re-injects) · `503` page connection died mid-read+**Errors:** `400` session not started · `401` · `403` · `404` session not found · `409` session not connected (also answered for a few seconds while WhatsApp Web reloads its page and the engine re-injects) · `503` page connection died mid-read, or the command timed out#### GET /api/sessions/stats/overview@@ -2387,7 +2387,7 @@ On Baileys the list is the saved address book: contacts with a name saved on the]```-**Errors:** `400` session is not started · `401` missing/invalid API key, or key not scoped to this session · `409` conflict or engine not ready (retryable) · `503` the WhatsApp page died while reading contacts (retry shortly)+**Errors:** `400` session is not started · `401` missing/invalid API key, or key not scoped to this session · `409` conflict or engine not ready (retryable) · `503` the WhatsApp page died while reading contacts or the command timed out (retry shortly)#### GET /api/sessions/:sessionId/contacts/blockeddiff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.mdindex 32d35ccb6..50ef465ca 100644--- a/docs/12-troubleshooting-faq.md+++ b/docs/12-troubleshooting-faq.md@@ -785,7 +785,9 @@ quoting the message it printed.- `GET /api/sessions/{id}/chats` (or another read that walks the whole store) fails on an accountwith thousands of chats, while smaller accounts on the same deployment are fine-- The error names a CDP method and the setting: `Runtime.callFunctionOn timed out. Increase the 'protocolTimeout' setting in launch/connect calls for a higher timeout if needed.`+- The chat and contact lists answer `503` with `WhatsApp Web did not answer the chat list read in time`+ (or `the contact list read`); another read may answer `500` with the raw error, which names a CDP+ method and the setting: `Runtime.callFunctionOn timed out. Increase the 'protocolTimeout' setting in launch/connect calls for a higher timeout if needed.`- The session stays `ready` and the next request works, so the page did not die**Cause:** Puppeteer gives every browser command a time budget, 180 000 ms by default, and onediff --git a/openapi.json b/openapi.jsonindex 2fb3303ca..367bb83ad 100644--- a/openapi.json+++ b/openapi.json@@ -1098,7 +1098,7 @@"description": "The session is not connected: an engine exists for it but is not `ready`, meaning 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, and for those few seconds the answer is a `409` naming the reload; retry shortly."},"503": {- "description": "The whatsapp-web.js page connection died mid-read, so nothing could be read. Deliberately not reported as an empty list — a page that went away says nothing about the chats."+ "description": "The whatsapp-web.js page connection died mid-read, or WhatsApp Web did not answer within the protocol timeout, so nothing could be read. Deliberately not reported as an empty list: a page that went away says nothing about the chats."}},"summary": "Get active chats for a session",@@ -4593,7 +4593,7 @@"description": "The session is not connected: an engine exists for it but is not `ready`, meaning 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, and for those few seconds the answer is a `409` naming the reload; retry shortly."},"503": {- "description": "The WhatsApp page died while reading contacts, retry shortly"+ "description": "The WhatsApp page died while reading contacts, or WhatsApp Web did not answer within the protocol timeout. Retry shortly."}},"summary": "Get all contacts for a session",diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 7fa5ee0d4..5addcdf40 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -6074,6 +6074,23 @@ describe('WhatsAppWebJsAdapter page transport error detection (wedged page fast-expect(onDisconnected).not.toHaveBeenCalled();});+ // A walk over a large address book that outruns Puppeteer's per-command budget got no answer: a+ // 503 the client retries, not a bare 500, and not a death.+ it('answers a protocol timeout on the contact walk with a 503 and reports no death', async () => {+ const evaluate = jest+ .fn()+ .mockRejectedValue(+ new Error(+ "Runtime.callFunctionOn timed out. Increase the 'protocolTimeout' setting in launch/connect calls for a higher timeout if needed.",+ ),+ );+ const { adapter, onDisconnected } = readyAdapter({ pupPage: { evaluate } });++ await expect(adapter.getContacts()).rejects.toBeInstanceOf(EngineTransportError);+ expect(onDisconnected).not.toHaveBeenCalled();+ expect(adapter.getStatus()).toBe(EngineStatus.READY);+ });+// A rejection that carries no transport-death signature is an ordinary failure, not a dead page —// it must reach the caller unchanged and leave the session READY, unlike the 503 case above.it('propagates a non-transport rejection from getContacts untouched and leaves the session READY', async () => {diff --git a/src/engine/adapters/wwebjs-chats.ts b/src/engine/adapters/wwebjs-chats.tsindex ceadc4479..f46f1086e 100644--- a/src/engine/adapters/wwebjs-chats.ts+++ b/src/engine/adapters/wwebjs-chats.ts@@ -36,6 +36,10 @@ export class WwebjsChats {this.host.reportIfPageTransportError(error, 'getChats');throw new EngineTransportError('Transport died while listing chats');}+ // A read that outran the protocol budget got no answer: a 503, but no death.+ if (isProtocolTimeout(error)) {+ throw new EngineTransportError('WhatsApp Web did not answer the chat list read in time');+ }throw error;}const summaries: ChatSummary[] = [];diff --git a/src/engine/adapters/wwebjs-contacts.ts b/src/engine/adapters/wwebjs-contacts.tsindex f4197bf57..629960c76 100644--- a/src/engine/adapters/wwebjs-contacts.ts+++ b/src/engine/adapters/wwebjs-contacts.ts@@ -140,6 +140,10 @@ export class WwebjsContacts {this.host.reportIfPageTransportError(error, 'getContacts');throw new EngineTransportError('Transport died while reading contacts');}+ // A walk that outran the protocol budget got no answer: a 503, but no death.+ if (isProtocolTimeout(error)) {+ throw new EngineTransportError('WhatsApp Web did not answer the contact list read in time');+ }throw error;}diff --git a/src/engine/adapters/wwebjs-protocol-timeout.spec.ts b/src/engine/adapters/wwebjs-protocol-timeout.spec.tsindex 52e9af859..3c8cb03a3 100644--- a/src/engine/adapters/wwebjs-protocol-timeout.spec.ts+++ b/src/engine/adapters/wwebjs-protocol-timeout.spec.ts@@ -220,6 +220,21 @@ describe('a protocol timeout is a 503, never a not-found verdict', () => {expect(reportIfPageTransportError).not.toHaveBeenCalled();});+ // The two list reads walk the whole store in one command, so they are the ones a large account+ // pushes past the budget; neither has a not-found verdict, but a raw rethrow would answer 500.+ it.each([+ ['getContacts', (host: WwebjsEngineHost) => new WwebjsContacts(host).getContacts(), 'pupPage'],+ ['getChats', (host: WwebjsEngineHost) => chats(host).getChats(), 'getChats'],+ ] as const)('%s answers an expired protocolTimeout with a 503 and reports no death', async (_op, call, via) => {+ const timeout = jest.fn().mockRejectedValue(new Error(await puppeteerProtocolTimeoutMessage()));+ const client = via === 'pupPage' ? { pupPage: { evaluate: timeout } } : { getChats: timeout };+ const { host, reportIfPageTransportError } = makeHost(client as unknown as Record<string, jest.Mock>);++ await expect(call(host)).rejects.toBeInstanceOf(EngineTransportError);+ expect(timeout).toHaveBeenCalledTimes(1);+ expect(reportIfPageTransportError).not.toHaveBeenCalled();+ });+// Negative twin: an ordinary page-side refusal keeps its not-found verdict.it.each([['getGroupInfo', null],diff --git a/src/modules/contact/contact.controller.ts b/src/modules/contact/contact.controller.tsindex f303cd3a9..7e9cbab87 100644--- a/src/modules/contact/contact.controller.ts+++ b/src/modules/contact/contact.controller.ts@@ -28,7 +28,12 @@ export class ContactController {type: [ContactDto],})@ApiResponse({ status: 400, description: 'Session not ready' })- @ApiResponse({ status: 503, description: 'The WhatsApp page died while reading contacts, retry shortly' })+ @ApiResponse({+ status: 503,+ description:+ 'The WhatsApp page died while reading contacts, or WhatsApp Web did not answer within the protocol ' ++ 'timeout. Retry shortly.',+ })@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })@ApiQuery({ name: 'limit', required: false, description: 'Max contacts to return (1–1000, default 1000)' })@ApiQuery({ name: 'offset', required: false, description: 'Number of contacts to skip (for paging)' })diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.tsindex 23a40d06a..71ca4d975 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -508,8 +508,9 @@ export class SessionController {@ApiResponse({status: 503,description:- 'The whatsapp-web.js page connection died mid-read, so nothing could be read. Deliberately not ' +- 'reported as an empty list — a page that went away says nothing about the chats.',+ 'The whatsapp-web.js page connection died mid-read, or WhatsApp Web did not answer within the ' ++ 'protocol timeout, so nothing could be read. Deliberately not reported as an empty list: a page ' ++ 'that went away says nothing about the chats.',})@ApiQuery({ name: 'limit', required: false, description: 'Max chats to return (1–1000, default 1000)' })@ApiQuery({ name: 'offset', required: false, description: 'Number of chats to skip (for paging)' })