Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(wwjs): wait out the upstream attach budget before reloading a dead event bridge
Yudhi Armyndharis1fe093785324
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 55e13121d..b15498b9c 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- **A group invite code now says why it could not be read** — fetching one is admin-only, but the groups list returns every group the account belongs to whatever its role, so the request lands on ids the caller was just handed: Baileys let WhatsApp's refusal escape as a bare `500` (13 of 16 groups on the test account) while whatsapp-web.js stringified its missing result into `{"inviteCode":"undefined"}` and the link `https://chat.whatsapp.com/undefined` behind a `200` (53 of 101). Both engines now answer `403`, the same status the group writes have answered since they were fixed, and an unanswered query answers `503` instead of the codeless link `https://chat.whatsapp.com/`.- **A catalog read no longer stalls for a minute and then reports an empty catalog** — Baileys answers an unanswered query with `undefined` rather than an error and its catalog parsers are null-safe, so a request WhatsApp never replied to was indistinguishable from a business with no products: `GET /catalog` and `/catalog/products` returned `200` with nothing in them after a silent 60 seconds, and `send-product` reported `404 Product not found` for a product it had simply never heard about. The walk now spends one 30-second budget across every page and answers `503`, and a server that repeats a page cursor instead of advancing no longer spins the walk until the process exhausts its heap.- **A benign whatsapp-web.js rejection no longer reads like a crash** — the same un-awaited `framenavigated` re-injection that already logs at `WARN` when the page goes away was logged at `ERROR` in its other shape, where the navigation lands before WhatsApp Web has defined its module registry; it appears at the first boot after the pinned WhatsApp Web build moves under a warm profile, and the session reaches ready unaided.+- **A slow whatsapp-web.js attach is no longer mistaken for a dead one and reloaded out from under itself** — the event-bridge self-heal could fire on the first reconcile tick, two seconds after `authenticated`, but whatsapp-web.js clears `eventsAttached` in its constructor and sets it only once `attachEventListeners` resolves, with `LoadUtils`, a poll of up to thirty seconds for `window.WWebJS`, `ClientInfo` and `InterfaceController` in between, so a false flag is the ordinary reading for most of a minute on a loaded host. The reload then navigated the page out from under the injection still running on it, whose re-entry died at `getWWebVersion` before re-exposing any of the bridge, and the one-shot guard blocked a second attempt, so the session rode out the readiness deadline and was marked failed — credentials kept, but no way back without a restart. The reload now waits out the upstream attach budget first, which still leaves it half the deadline to reinject when one is genuinely warranted.### Fixeddiff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex e8d89bf9c..8f8db9161 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -12,6 +12,8 @@ import {resolveAuthTimeoutMs,wwebjsAckToDeliveryStatus,extractWwebjsCall,+ READY_RECONCILE_TIMEOUT_MS,+ READY_RECONCILE_BRIDGE_RELOAD_GRACE_MS,} from './whatsapp-web-js.adapter';import { getEffectiveWebVersionInfo, resolveWebVersionPin, __resetWebVersionCache } from '../wa-web-version';import * as fs from 'fs';@@ -1498,6 +1500,70 @@ describe('WhatsAppWebJsAdapter ready reconciliation (#251/#273)', () => {expect(jest.getTimerCount()).toBe(0);});+ // whatsapp-web.js sets `eventsAttached = false` in its constructor (Client.js:109) and flips it only+ // after attachEventListeners() resolves (Client.js:373). Everything in between — LoadUtils, a poll of+ // up to 30s for window.WWebJS (Client.js:334), ClientInfo, InterfaceController — is a legitimately+ // slow attach, not a dead bridge. Reloading inside that window navigates the page out from under the+ // in-flight inject(): the re-inject then dies at getWWebVersion before it re-exposes any of the+ // bridge, and the one-shot guard blocks a retry, so the session is doomed to the deadline (#1081).+ it("does not reload a merely slow attach, so a bridge attaching inside upstream's budget still promotes", async () => {+ jest.useFakeTimers();++ const adapter = newAdapter();+ // A faithful reload: navigating destroys the in-flight injection, so an attach that was about to+ // complete never does. Stubbing it inert — as the surrounding tests do — hides the whole defect.+ const attach = { destroyed: false };+ const reload = jest.fn().mockImplementation(() => {+ attach.destroyed = true;+ return Promise.resolve(undefined);+ });+ const { client, onReady } = attachFakeClient(adapter, {+ eventsAttached: false,+ pupPage: { evaluate: jest.fn().mockResolvedValue(true), reload },+ });++ client.emit('authenticated');++ // Upstream is still well inside its own attach budget at this point.+ await jest.advanceTimersByTimeAsync(20_000);+ expect(reload).not.toHaveBeenCalled();++ // The attach resolves, comfortably within upstream's 30s WWebJS poll.+ if (!attach.destroyed) client.eventsAttached = true;+ await jest.advanceTimersByTimeAsync(2100);++ expect(adapter.getStatus()).toBe(EngineStatus.READY);+ expect(onReady).toHaveBeenCalledTimes(1);+ });++ it('still reloads a genuinely dead bridge once the grace period has elapsed', async () => {+ jest.useFakeTimers();++ const adapter = newAdapter();+ const reload = jest.fn().mockResolvedValue(undefined);+ const { client } = attachFakeClient(adapter, {+ eventsAttached: false,+ pupPage: { evaluate: jest.fn().mockResolvedValue(true), reload },+ });++ client.emit('authenticated');+ await jest.advanceTimersByTimeAsync(READY_RECONCILE_BRIDGE_RELOAD_GRACE_MS + 2100);++ expect(reload).toHaveBeenCalledTimes(1);++ // Upstream's window.WWebJS poll alone is 30s (Client.js:334) and is only one stage of the attach.+ // The grace has to outlast it, or we go back to aborting healthy attaches; and what remains before+ // the deadline has to outlast it too, or a warranted reload could never finish reinjecting.+ const UPSTREAM_WWEBJS_POLL_MS = 30_000;+ expect(READY_RECONCILE_BRIDGE_RELOAD_GRACE_MS).toBeGreaterThan(UPSTREAM_WWEBJS_POLL_MS);+ expect(READY_RECONCILE_TIMEOUT_MS - READY_RECONCILE_BRIDGE_RELOAD_GRACE_MS).toBeGreaterThan(+ UPSTREAM_WWEBJS_POLL_MS,+ );++ client.emit('auth_failure', 'stop test timer');+ expect(jest.getTimerCount()).toBe(0);+ });+it('reloads the page once — and only once — to reinject a dead event bridge, then promotes when it heals', async () => {jest.useFakeTimers();@@ -1509,7 +1575,8 @@ describe('WhatsAppWebJsAdapter ready reconciliation (#251/#273)', () => {});client.emit('authenticated');- await jest.advanceTimersByTimeAsync(2100 * 3);+ // Past the grace period: an attach still unfinished this late is dead, not slow.+ await jest.advanceTimersByTimeAsync(READY_RECONCILE_BRIDGE_RELOAD_GRACE_MS + 2100 * 3);expect(reload).toHaveBeenCalledTimes(1);expect(adapter.getStatus()).toBe(EngineStatus.AUTHENTICATING);diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex cd29e321f..419a515bd 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -117,7 +117,18 @@ export interface WhatsAppWebJsConfig {}const READY_RECONCILE_INTERVAL_MS = 2000;-const READY_RECONCILE_TIMEOUT_MS = 90_000;+export const READY_RECONCILE_TIMEOUT_MS = 90_000;++// How long after `authenticated` the event bridge is allowed to still be attaching before a reload is+// considered. whatsapp-web.js clears `eventsAttached` in its constructor (Client.js:109) and sets it+// only once attachEventListeners() resolves (Client.js:373); in between it evaluates LoadUtils, polls+// up to 30s for window.WWebJS (Client.js:334), then builds ClientInfo and InterfaceController. So a+// false flag is the NORMAL reading for most of a minute on a loaded host, and reloading on it aborts+// a healthy attach — the page navigates out from under the in-flight inject(), which then dies before+// re-exposing the bridge and cannot be retried (#1081). Must exceed upstream's own 30s poll with room+// for the rest of the pipeline, and stay well under READY_RECONCILE_TIMEOUT_MS so a reload that IS+// warranted still has time to reinject before the deadline.+export const READY_RECONCILE_BRIDGE_RELOAD_GRACE_MS = 45_000;// WhatsApp Web states that mean WhatsApp has judged the account or its egress, mapped to the neutral// restriction kinds. This is the ONLY channel the library offers: there is no dedicated event, error@@ -1239,6 +1250,8 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginif (!this.client || !this.lastProbeStateConnected) return;const client = this.client as Client & { eventsAttached?: boolean };if (client.eventsAttached !== false) return;+ // An attach still inside upstream's own budget is slow, not dead — navigating now would abort it.+ if (Date.now() - this.readyReconcileStartedAt < READY_RECONCILE_BRIDGE_RELOAD_GRACE_MS) return;this.readyReconcileReloadAttempted = true;this.logger.warn('WhatsApp Web is connected but its event bridge never attached; reloading the page to reinject', {sessionId: this.config.sessionId,