Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(engine): bound the whatsapp-web.js browser command timeout

JuanGalzerano200875f63e0a
diff --git a/.env.example b/.env.example
index 3883a8437..72bdb66e2 100644
--- a/.env.example
+++ b/.env.example
@@ -127,6 +127,12 @@ STATUS_SEED_ON_READY=false
# Path to a system Chromium/Chrome binary. Leave unset to use the bundled Puppeteer browser.
# Required in the Docker image and on hosts without a bundled browser (e.g. Alpine/ARM).
# PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium
+# How long a single browser command may take before it is abandoned, in milliseconds. Default 300000
+# (5 min), above Puppeteer's own 180000. Raise it if a large account (thousands of chats) fails a
+# read with "Runtime.callFunctionOn timed out"; the renderer is still working, the command budget
+# just ran out. Must be a POSITIVE integer — 0 does not mean "no limit later", it means no timer is
+# armed at all, so a wedged browser holds the request forever instead of failing it as 503.
+# PUPPETEER_PROTOCOL_TIMEOUT_MS=300000
# A freshly linked account is shown a "What's new on WhatsApp Web" modal that must be acknowledged or
# WhatsApp unlinks the companion a few minutes later. The whatsapp-web.js engine clicks it
# automatically, matching the English button label `Continue`. If your WhatsApp Web renders the modal
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 47379aa3d..de8f63080 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,26 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [Unreleased]
+
+### Added
+
+- `PUPPETEER_PROTOCOL_TIMEOUT_MS` sets how long a single browser command may take on the
+ whatsapp-web.js engine, defaulting to 300 000 ms, above Puppeteer's own 180 000 ms. A read that
+ walks the whole store, such as `GET /sessions/{sessionId}/chats` on an account with thousands of
+ chats, could run past the stock budget and fail with `Runtime.callFunctionOn timed out` while the
+ renderer was still working. The value must be positive: Puppeteer only arms its timer for a
+ truthy one, so `0` drops the bound instead of raising it and lets a wedged renderer hold the
+ request forever.
+
+### Changed
+
+- The whatsapp-web.js transport classifier now rules out a protocol timeout explicitly. That
+ message carries no transport-death signature on the current Puppeteer, so nothing was
+ misreporting it and behaviour is unchanged; the point is the spec, which pins the invariant in
+ both directions against the verbatim Puppeteer string so a future bump cannot start reading a
+ slow command as a dead page.
+
## [0.23.3] - 2026-08-24
### Added
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index 5d1596483..d4de2b9a3 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -67,6 +67,7 @@ services:
- SESSION_DATA_PATH=${SESSION_DATA_PATH:-/app/data/sessions}
- PUPPETEER_HEADLESS=${PUPPETEER_HEADLESS:-true}
- PUPPETEER_ARGS=${PUPPETEER_ARGS:---no-sandbox,--disable-setuid-sandbox,--disable-dev-shm-usage,--disable-gpu}
+ - PUPPETEER_PROTOCOL_TIMEOUT_MS=${PUPPETEER_PROTOCOL_TIMEOUT_MS:-}
# Optional WhatsApp Web version override. DEFAULT (empty, "latest", or "auto"): OpenWA auto-resolves a
# settled build from the third-party wppconnect-team/wa-version registry and pins its remote HTML
# (fetched into the web.whatsapp.com origin without an integrity check). Set "off" to disable pinning
diff --git a/docker-compose.yml b/docker-compose.yml
index f4906ee04..2d2211d2a 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -141,6 +141,7 @@ services:
- SESSION_DATA_PATH=${SESSION_DATA_PATH:-}
- PUPPETEER_HEADLESS=${PUPPETEER_HEADLESS:-}
- PUPPETEER_ARGS=${PUPPETEER_ARGS:-}
+ - PUPPETEER_PROTOCOL_TIMEOUT_MS=${PUPPETEER_PROTOCOL_TIMEOUT_MS:-}
# Optional WhatsApp Web version override. DEFAULT (empty, "latest", or "auto"): OpenWA auto-resolves a
# settled build from the third-party wppconnect-team/wa-version registry and pins its remote HTML
# (fetched into the web.whatsapp.com origin without an integrity check). Set "off" to disable pinning
diff --git a/docs/10-devops-infrastructure.md b/docs/10-devops-infrastructure.md
index fb83cda1a..a62d332e4 100644
--- a/docs/10-devops-infrastructure.md
+++ b/docs/10-devops-infrastructure.md
@@ -466,6 +466,8 @@ SESSION_DATA_PATH=./data/sessions
PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium
PUPPETEER_HEADLESS=true
PUPPETEER_ARGS=--no-sandbox,--disable-setuid-sandbox
+# Per-browser-command budget, ms. Default 300000. Raise for very large accounts; must stay positive.
+PUPPETEER_PROTOCOL_TIMEOUT_MS=300000
# ===========================================
# SECURITY
diff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.md
index 4abb6ef7b..c4d890966 100644
--- a/docs/12-troubleshooting-faq.md
+++ b/docs/12-troubleshooting-faq.md
@@ -665,6 +665,33 @@ rm -rf node_modules/whatsapp-web.js && npm ci
> Pinning `WWEBJS_WEB_VERSION` does **not** work around this — the rename is present in every
> current WhatsApp Web build, so no pin avoids it.
+### Issue: Reads on a large account fail with `Runtime.callFunctionOn timed out`
+
+> **Engine:** This issue applies to the `whatsapp-web.js` engine only (Chromium/Puppeteer-based). It does not affect `ENGINE_TYPE=baileys`.
+
+**Symptoms:**
+
+- `GET /api/sessions/{id}/chats` (or another read that walks the whole store) fails on an account
+ with 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 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 one
+`getChats()` over a very large store can run past it. The renderer is still working; only the
+command is dropped. That is also why this is **not** treated as a dead page — a transport death
+answers `503` and takes the session down with it, and this is just a slow command on a live page.
+
+**Solution:** raise the budget for that deployment.
+
+```bash
+# 10 minutes, in .env or the environment
+PUPPETEER_PROTOCOL_TIMEOUT_MS=600000
+```
+
+> Do not set it to `0`. The gateway refuses to boot on a non-positive value: Puppeteer only arms
+> its timer for a truthy one, so `0` drops the bound altogether and a wedged renderer will hold the
+> command, and the request waiting on it, forever. A hung request is worse than a failed one.
+
### Issue: Media Upload Fails
**Symptoms:**
diff --git a/src/config/configuration.ts b/src/config/configuration.ts
index db0da74ce..03c9b7ebe 100644
--- a/src/config/configuration.ts
+++ b/src/config/configuration.ts
@@ -211,6 +211,10 @@ export default () => ({
// uses Puppeteer's bundled Chromium. Required on hosts where the bundled binary
// is missing or incompatible (Alpine, ARM, custom base images).
executablePath: process.env.PUPPETEER_EXECUTABLE_PATH || undefined,
+ // How long one CDP command may take. Above Puppeteer's own 180 000 ms, which a single
+ // `client.getChats()` can exceed on an account with thousands of chats. Bounded, never
+ // disabled — see wwebjs-lifecycle.ts for why a falsy value is not "no limit".
+ protocolTimeoutMs: parseInt(process.env.PUPPETEER_PROTOCOL_TIMEOUT_MS || '300000', 10),
},
sessionDataPath: process.env.SESSION_DATA_PATH || './data/sessions',
// Baileys engine (used when ENGINE_TYPE=baileys). Multi-file auth state base dir; each session
diff --git a/src/config/env-precedence.ts b/src/config/env-precedence.ts
index e2c09ea50..7fb43e09e 100644
--- a/src/config/env-precedence.ts
+++ b/src/config/env-precedence.ts
@@ -111,6 +111,7 @@ export const BLANK_SHADOWED_ENV_KEYS: string[] = [
'PUPPETEER_HEADLESS',
'SESSION_DATA_PATH',
'PUPPETEER_ARGS',
+ 'PUPPETEER_PROTOCOL_TIMEOUT_MS',
// Rate-limit values are blank-forwarded by Compose so a host value can take precedence without an
// empty forward masking the lower-priority loaded .env / data/.env.generated value.
'RATE_LIMIT_SHORT_TTL',
diff --git a/src/config/env.validation.ts b/src/config/env.validation.ts
index 9039a9fa2..abf0a1496 100644
--- a/src/config/env.validation.ts
+++ b/src/config/env.validation.ts
@@ -284,6 +284,9 @@ export function validateEnv(config: EnvConfig): EnvConfig {
'SESSION_LEASE_HEARTBEAT_MS',
'SESSION_TAKEOVER_SWEEP_MS',
'SESSION_PROXY_TIMEOUT_MS',
+ // Positive-only is the POINT here, not a convention: 0 arms no Puppeteer timer at all, so a
+ // wedged renderer holds the request forever (see wwebjs-lifecycle.ts).
+ 'PUPPETEER_PROTOCOL_TIMEOUT_MS',
]) {
checkPositiveInt(key);
}
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 5e2255ab6..23c3e3013 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -76,6 +76,8 @@ export interface WhatsAppWebJsConfig {
headless?: boolean;
args?: string[];
executablePath?: string;
+ /** Per-CDP-command budget handed to Puppeteer. Must be positive — see wwebjs-lifecycle. */
+ protocolTimeoutMs?: number;
};
// Phase 3: Proxy per session
proxy?: {
diff --git a/src/engine/adapters/wwebjs-lifecycle.ts b/src/engine/adapters/wwebjs-lifecycle.ts
index 73a322a21..b3e0e6c39 100644
--- a/src/engine/adapters/wwebjs-lifecycle.ts
+++ b/src/engine/adapters/wwebjs-lifecycle.ts
@@ -339,6 +339,15 @@ export class WwebjsLifecycle {
...(this.host.config.puppeteer?.executablePath
? { executablePath: this.host.config.puppeteer.executablePath }
: {}),
+ // Per-CDP-command budget, spread only for a POSITIVE value so an unset or malformed config
+ // keeps Puppeteer's own 180 000 ms default rather than being handed a falsy one:
+ // `common/CallbackRegistry.js` arms the timer under `if (timeout)`, so 0 or NaN arms none
+ // and a wedged renderer holds the command — and the request behind it — indefinitely.
+ // A dead page must surface as a 503, never as a hang.
+ ...(typeof this.host.config.puppeteer?.protocolTimeoutMs === 'number' &&
+ this.host.config.puppeteer.protocolTimeoutMs > 0
+ ? { protocolTimeout: this.host.config.puppeteer.protocolTimeoutMs }
+ : {}),
},
...(authTimeoutMs !== undefined ? { authTimeoutMs } : {}),
...(proxyAuthentication ? { proxyAuthentication } : {}),
@@ -646,9 +655,22 @@ export class WwebjsLifecycle {
private static readonly PAGE_TRANSPORT_ERROR_PATTERN =
/protocol error|target closed|targetclosederror|detached frame|session closed|connection closed/i;
+ /**
+ * A per-command CDP timeout is NOT a death: the renderer is merely slower than the budget, and
+ * the next command may succeed. On Puppeteer 24.38.0 this message carries none of the signatures
+ * above, so the guard changes no current behaviour — it pins the intent.
+ *
+ * Matched on the FULL puppeteer phrase, not a bare `timed out`: a broad exclusion would also
+ * swallow a genuine death whose message happens to mention a timeout.
+ */
+ private static readonly PROTOCOL_TIMEOUT_PATTERN = /timed out\. increase the 'protocoltimeout'/i;
+
/** Whether the error carries a dead page/transport signature (see PAGE_TRANSPORT_ERROR_PATTERN). */
isPageTransportError(error: unknown): boolean {
const message = error instanceof Error ? error.message : String(error);
+ if (WwebjsLifecycle.PROTOCOL_TIMEOUT_PATTERN.test(message)) {
+ return false;
+ }
return WwebjsLifecycle.PAGE_TRANSPORT_ERROR_PATTERN.test(message);
}
diff --git a/src/engine/adapters/wwebjs-protocol-timeout.spec.ts b/src/engine/adapters/wwebjs-protocol-timeout.spec.ts
new file mode 100644
index 000000000..12f2de109
--- /dev/null
+++ b/src/engine/adapters/wwebjs-protocol-timeout.spec.ts
@@ -0,0 +1,110 @@
+import { Client } from 'whatsapp-web.js';
+import { WhatsAppWebJsAdapter } from './whatsapp-web-js.adapter';
+
+/**
+ * The per-CDP-command budget handed to Puppeteer, and the one error it produces.
+ *
+ * Two invariants worth pinning: the option must never reach Puppeteer falsy (that arms no timer at
+ * all, so a wedged renderer hangs the request — see wwebjs-lifecycle.ts), and a protocol timeout
+ * must never be read as a dead page.
+ */
+describe('whatsapp-web.js protocol timeout', () => {
+ const SESSION_ID = 'sess-protocol-timeout';
+ let clientInitSpy: jest.SpyInstance;
+ let savedWebVersion: string | undefined;
+
+ const launchedPuppeteerOptions = async (
+ protocolTimeoutMs?: number,
+ ): Promise<{ protocolTimeout?: number } | undefined> => {
+ const adapter = new WhatsAppWebJsAdapter({
+ sessionId: SESSION_ID,
+ sessionDataPath: './data/sessions',
+ puppeteer: { protocolTimeoutMs },
+ });
+ await adapter.initialize({});
+ return (adapter as unknown as { client: { options: { puppeteer?: { protocolTimeout?: number } } } }).client.options
+ .puppeteer;
+ };
+
+ beforeEach(() => {
+ // Keep initialize() offline: 'off' skips the wa-version registry fetch in resolveWebVersionPin.
+ savedWebVersion = process.env.WWEBJS_WEB_VERSION;
+ process.env.WWEBJS_WEB_VERSION = 'off';
+ // Build the real wwebjs Client — that is what carries the launch options — but launch no browser.
+ clientInitSpy = jest
+ .spyOn(Client.prototype as unknown as { initialize: () => Promise<void> }, 'initialize')
+ .mockResolvedValue(undefined);
+ });
+
+ afterEach(() => {
+ clientInitSpy.mockRestore();
+ if (savedWebVersion === undefined) {
+ delete process.env.WWEBJS_WEB_VERSION;
+ } else {
+ process.env.WWEBJS_WEB_VERSION = savedWebVersion;
+ }
+ });
+
+ it('hands a configured budget to the Client as puppeteer.protocolTimeout', async () => {
+ expect(await launchedPuppeteerOptions(300_000)).toMatchObject({ protocolTimeout: 300_000 });
+ });
+
+ it('omits the option when unset, leaving Puppeteer its own 180 000 ms default', async () => {
+ const options = await launchedPuppeteerOptions(undefined);
+
+ // Absent, not zero: passing 0 through would DISABLE the timer rather than fall back.
+ expect(options).not.toHaveProperty('protocolTimeout');
+ });
+
+ it.each([
+ ['zero', 0],
+ ['negative', -1],
+ ['NaN, e.g. from a malformed env value', Number.NaN],
+ ])('omits the option for a %s value rather than arming no timer', async (_label, value) => {
+ expect(await launchedPuppeteerOptions(value)).not.toHaveProperty('protocolTimeout');
+ });
+
+ describe('the transport classifier', () => {
+ const classify = (message: string): boolean => {
+ const adapter = new WhatsAppWebJsAdapter({
+ sessionId: SESSION_ID,
+ sessionDataPath: './data/sessions',
+ puppeteer: {},
+ });
+ return (adapter as unknown as { isPageTransportError: (error: unknown) => boolean }).isPageTransportError(
+ new Error(message),
+ );
+ };
+
+ /**
+ * Verbatim from Puppeteer 24.38.0 `common/CallbackRegistry.js`, where the leading label is the
+ * CDP method name. Pinning the real string is the point: a paraphrase would keep passing while
+ * the message the library actually throws drifted out from under the guard.
+ */
+ const PUPPETEER_PROTOCOL_TIMEOUT =
+ "Runtime.callFunctionOn timed out. Increase the 'protocolTimeout' setting in launch/connect calls for a higher timeout if needed.";
+
+ it('does not treat a protocol timeout as a dead page', () => {
+ // The renderer is slower than the budget, not gone — the next command may well succeed.
+ // Reporting death here would tear down a live session and answer 503 for a working page.
+ expect(classify(PUPPETEER_PROTOCOL_TIMEOUT)).toBe(false);
+ });
+
+ it.each([
+ 'Protocol error (Runtime.callFunctionOn): Session closed.',
+ 'Protocol error (Page.navigate): Target closed',
+ 'Attempted to use detached Frame',
+ 'Connection closed',
+ ])('still reports a genuine transport death: %s', message => {
+ // The 503-on-dead-page contract, pinned from the other side: narrowing the classifier for
+ // timeouts must not cost a single real death signature.
+ expect(classify(message)).toBe(true);
+ });
+
+ it('reports a death whose message also mentions a timeout', () => {
+ // Why the guard matches Puppeteer's full phrase instead of a bare /timed out/: the broad
+ // version swallows this, turning a reportable dead page into a silent one.
+ expect(classify('Protocol error (Runtime.callFunctionOn): Session closed. Request timed out')).toBe(true);
+ });
+ });
+});
diff --git a/src/engine/builtin/whatsapp-web-js/index.ts b/src/engine/builtin/whatsapp-web-js/index.ts
index ad59fb33b..5c79fc761 100644
--- a/src/engine/builtin/whatsapp-web-js/index.ts
+++ b/src/engine/builtin/whatsapp-web-js/index.ts
@@ -48,13 +48,14 @@ export class WhatsAppWebJsPlugin implements IEnginePlugin {
// per-call config carries only engine-neutral fields (sessionId, proxy).
const engineConfig = (this.context?.config ?? this.registeredConfig ?? {}) as {
sessionDataPath?: string;
- puppeteer?: { headless?: boolean; args?: string[]; executablePath?: string };
+ puppeteer?: { headless?: boolean; args?: string[]; executablePath?: string; protocolTimeoutMs?: number };
};
const puppeteer = engineConfig.puppeteer ?? {};
const sessionDataPath = engineConfig.sessionDataPath ?? './data/sessions';
const headless = puppeteer.headless ?? true;
const puppeteerArgs = puppeteer.args ?? ['--no-sandbox', '--disable-setuid-sandbox'];
const executablePath = puppeteer.executablePath;
+ const protocolTimeoutMs = puppeteer.protocolTimeoutMs;
return new WhatsAppWebJsAdapter({
sessionId,
@@ -63,6 +64,7 @@ export class WhatsAppWebJsPlugin implements IEnginePlugin {
headless,
args: puppeteerArgs,
executablePath,
+ protocolTimeoutMs,
},
proxy: proxyUrl
? {
diff --git a/src/engine/engine.factory.ts b/src/engine/engine.factory.ts
index ad1426538..e81784e84 100644
--- a/src/engine/engine.factory.ts
+++ b/src/engine/engine.factory.ts
@@ -232,6 +232,7 @@ export class EngineFactory implements OnModuleInit {
headless: this.configService.get<boolean>('engine.puppeteer.headless') ?? true,
args: this.configService.get<string[]>('engine.puppeteer.args') ?? ['--no-sandbox', '--disable-setuid-sandbox'],
executablePath: this.configService.get<string>('engine.puppeteer.executablePath'),
+ protocolTimeoutMs: this.configService.get<number>('engine.puppeteer.protocolTimeoutMs'),
},
proxy: options.proxyUrl
? {