Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): reconcile whatsapp-web.js ready after auth (#415)

aeyeiof9f85757502c
diff --git a/.env.example b/.env.example
index 3890700fb..8d993b371 100644
--- a/.env.example
+++ b/.env.example
@@ -57,13 +57,12 @@ PUPPETEER_ARGS=--no-sandbox,--disable-setuid-sandbox,--disable-dev-shm-usage,--d
# Required in the Docker image and on hosts without a bundled browser (e.g. Alpine/ARM).
# PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium
-# Pin the WhatsApp Web client version. If sessions get stuck at "authenticating" and never
-# reach "ready" (a whatsapp-web.js version-sync hang), set this to a known-good version from
-# https://github.com/wppconnect-team/wa-version (browse the html/ folder). Leave unset (or
-# "latest") to let whatsapp-web.js auto-select. WWEBJS_WEB_VERSION_REMOTE_PATH overrides the
-# URL template (use {version} as the placeholder) if you self-host the version HTML.
-# 2.3000.1023204257 is confirmed to reach "ready" (incl. ARM64 / Raspberry Pi 5) — uncomment it:
-# WWEBJS_WEB_VERSION=2.3000.1023204257
+# Optional WhatsApp Web client version pin. Leave unset (or use "latest", "auto", or "off") to
+# let whatsapp-web.js auto-select. If sessions get stuck at "authenticating" after scanning the QR,
+# set this to a known-good version from https://github.com/wppconnect-team/wa-version (browse the
+# html/ folder). WWEBJS_WEB_VERSION_REMOTE_PATH overrides the URL template (use {version} as the
+# placeholder) if you self-host the version HTML.
+# WWEBJS_WEB_VERSION=2.3000.1040641150-alpha
# Extend the initial boot/inject wait (milliseconds) before QR generation. On slow first boots
# (WSL2 or low-resource containers) the default 30000ms can expire before WhatsApp Web finishes
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index c1e3e2c84..230440243 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -49,10 +49,9 @@ services:
- SESSION_DATA_PATH=/app/data/sessions
- PUPPETEER_HEADLESS=true
- PUPPETEER_ARGS=--no-sandbox,--disable-setuid-sandbox,--disable-dev-shm-usage,--disable-gpu
- # Pin the WhatsApp Web version if a session hangs at "authenticating" after scanning the QR
- # (whatsapp-web.js 1.34.x can stall on an incompatible auto-selected WA-Web version, #251/#273).
- # Empty = auto-select (default). Set WWEBJS_WEB_VERSION in .env to a known-good version — see
- # docs/12-troubleshooting-faq.md.
+ # Optional WhatsApp Web version override. Leave empty for whatsapp-web.js auto-selection.
+ # If a session hangs at "authenticating", set WWEBJS_WEB_VERSION to a known-good cached build
+ # from wppconnect-team/wa-version; latest|auto|off also forces auto-selection.
- WWEBJS_WEB_VERSION=${WWEBJS_WEB_VERSION:-}
- WWEBJS_WEB_VERSION_REMOTE_PATH=${WWEBJS_WEB_VERSION_REMOTE_PATH:-}
# Raise whatsapp-web.js's first-boot init wait (default 30000ms) on slow boots. Empty = default.
diff --git a/docker-compose.yml b/docker-compose.yml
index c88330552..ee5ee2156 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -93,10 +93,9 @@ services:
- 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}
- # Pin the WhatsApp Web version if a session hangs at "authenticating" after scanning the QR
- # (whatsapp-web.js 1.34.x can stall on an incompatible auto-selected WA-Web version, #251/#273).
- # Empty = auto-select (default). Set WWEBJS_WEB_VERSION in .env to a known-good version — see
- # docs/12-troubleshooting-faq.md. (Without this line the var in .env never reaches the container.)
+ # Optional WhatsApp Web version override. Leave empty for whatsapp-web.js auto-selection.
+ # If a session hangs at "authenticating", set WWEBJS_WEB_VERSION to a known-good cached build
+ # from wppconnect-team/wa-version; latest|auto|off also forces auto-selection.
- WWEBJS_WEB_VERSION=${WWEBJS_WEB_VERSION:-}
- WWEBJS_WEB_VERSION_REMOTE_PATH=${WWEBJS_WEB_VERSION_REMOTE_PATH:-}
# Raise whatsapp-web.js's first-boot init wait (default 30000ms) on slow boots — e.g. WSL2 or
diff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.md
index 8bf34e291..5273cc288 100644
--- a/docs/12-troubleshooting-faq.md
+++ b/docs/12-troubleshooting-faq.md
@@ -209,16 +209,20 @@ stuck. Often seen on ARM64 (e.g. Raspberry Pi) after upgrading to v0.2.x.
stalls the post-link sync. (If you also see `chrome_crashpad_handler: --database is required` *and the
session never starts at all*, that is a different problem — see "Session fails to launch …" below.)
-**Fix:** pin a known-good WhatsApp Web version with `WWEBJS_WEB_VERSION`:
+**Fix:** OpenWA reconciles a missed `ready` event when WhatsApp Web is connected, the injected
+runtime is available, and whatsapp-web.js has populated the linked account identity. If your
+environment still hits a WA-Web compatibility hang, pin a known-good WA-Web version with
+`WWEBJS_WEB_VERSION`:
```bash
-# Confirmed to reach "ready" (incl. ARM64 / Raspberry Pi 5):
-WWEBJS_WEB_VERSION=2.3000.1023204257
+# Optional workaround:
+WWEBJS_WEB_VERSION=2.3000.1040641150-alpha
```
-Restart the container after setting it. Browse newer versions at
-[wppconnect-team/wa-version](https://github.com/wppconnect-team/wa-version) (the `html/` folder).
-Set `WWEBJS_WEB_VERSION=latest` (or leave it unset) to restore the default auto-version behavior.
+Restart the container after changing it. Browse newer versions at
+[wppconnect-team/wa-version](https://github.com/wppconnect-team/wa-version) (the `html/` folder). Set
+`WWEBJS_WEB_VERSION=latest`, `auto`, or `off` (or leave it unset) to use whatsapp-web.js
+auto-version behavior.
### Issue: QR generation times out on slow first boot (WSL2 / low-resource)
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index ccd4c812c..decb2218c 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -1,4 +1,5 @@
-import { MessageMedia } from 'whatsapp-web.js';
+import { MessageMedia, WAState } from 'whatsapp-web.js';
+import { EventEmitter } from 'events';
import {
WhatsAppWebJsAdapter,
extractLinkedParentJID,
@@ -292,6 +293,277 @@ describe('WhatsAppWebJsAdapter.forceDestroy (recover a wedged session, #351)', (
});
});
+describe('WhatsAppWebJsAdapter ready reconciliation (#251/#273)', () => {
+ const newAdapter = (): WhatsAppWebJsAdapter =>
+ new WhatsAppWebJsAdapter({ sessionId: 'sess-1', sessionDataPath: './data/sessions', puppeteer: {} });
+ type FakeClient = EventEmitter & {
+ info?: { wid?: { user?: string }; pushname?: string };
+ getState: jest.Mock;
+ pupPage: { evaluate: jest.Mock };
+ destroy?: jest.Mock;
+ logout?: jest.Mock;
+ pupBrowser?: { process?: jest.Mock };
+ };
+ const attachFakeClient = (
+ adapter: WhatsAppWebJsAdapter,
+ overrides: Partial<FakeClient> = {},
+ ): { client: FakeClient; onReady: jest.Mock; onStateChanged: jest.Mock } => {
+ const client = Object.assign(new EventEmitter(), {
+ info: { wid: { user: '628123' }, pushname: 'Tester' },
+ getState: jest.fn().mockResolvedValue(WAState.CONNECTED),
+ pupPage: {
+ evaluate: jest.fn().mockResolvedValue(true),
+ },
+ ...overrides,
+ }) as FakeClient;
+ const onReady = jest.fn();
+ const onStateChanged = jest.fn();
+
+ (adapter as unknown as { client: unknown }).client = client;
+ (adapter as unknown as { callbacks: unknown }).callbacks = { onReady, onStateChanged };
+ (adapter as unknown as { setupEventHandlers: () => void }).setupEventHandlers();
+
+ return { client, onReady, onStateChanged };
+ };
+ const deferredVoid = (): { promise: Promise<void>; resolve: () => void } => {
+ let resolve = (): void => undefined;
+ const promise = new Promise<void>(res => {
+ resolve = res;
+ });
+ return { promise, resolve };
+ };
+ const expectNoReadyDuringTeardown = async (
+ configureClient: (client: FakeClient, teardownWait: Promise<void>) => void,
+ startTeardown: (adapter: WhatsAppWebJsAdapter) => Promise<void>,
+ ): Promise<void> => {
+ jest.useFakeTimers();
+
+ const adapter = newAdapter();
+ const teardownWait = deferredVoid();
+ const { client, onReady, onStateChanged } = attachFakeClient(adapter);
+ configureClient(client, teardownWait.promise);
+
+ client.emit('authenticated');
+ expect(adapter.getStatus()).toBe(EngineStatus.AUTHENTICATING);
+ expect(jest.getTimerCount()).toBe(1);
+
+ const teardown = startTeardown(adapter);
+
+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);
+ expect(onStateChanged).toHaveBeenLastCalledWith(EngineStatus.DISCONNECTED);
+ expect(jest.getTimerCount()).toBe(0);
+
+ client.emit('ready');
+ await jest.advanceTimersByTimeAsync(2100);
+
+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);
+ expect(onReady).not.toHaveBeenCalled();
+ expect(jest.getTimerCount()).toBe(0);
+
+ teardownWait.resolve();
+ await teardown;
+
+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);
+ expect(onReady).not.toHaveBeenCalled();
+ expect(jest.getTimerCount()).toBe(0);
+ };
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ it('marks the adapter ready when authenticated runtime is connected but the ready event is missed', async () => {
+ jest.useFakeTimers();
+
+ const adapter = newAdapter();
+ const { client, onReady } = attachFakeClient(adapter);
+
+ client.emit('authenticated');
+ expect(adapter.getStatus()).toBe(EngineStatus.AUTHENTICATING);
+
+ await jest.advanceTimersByTimeAsync(2100);
+
+ expect(adapter.getStatus()).toBe(EngineStatus.READY);
+ expect(onReady).toHaveBeenCalledWith('628123', 'Tester');
+ expect(onReady).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not promote while the runtime is connected but client info is not populated yet', async () => {
+ jest.useFakeTimers();
+
+ const adapter = newAdapter();
+ const { client, onReady } = attachFakeClient(adapter, { info: undefined });
+
+ client.emit('authenticated');
+ await jest.advanceTimersByTimeAsync(2100);
+
+ expect(adapter.getStatus()).toBe(EngineStatus.AUTHENTICATING);
+ expect(onReady).not.toHaveBeenCalled();
+
+ client.emit('auth_failure', 'stop test timer');
+ expect(jest.getTimerCount()).toBe(0);
+ });
+
+ it('deduplicates the genuine ready event after reconciliation promotes the adapter', async () => {
+ jest.useFakeTimers();
+
+ const adapter = newAdapter();
+ const { client, onReady } = attachFakeClient(adapter);
+
+ client.emit('authenticated');
+ await jest.advanceTimersByTimeAsync(2100);
+ client.emit('ready');
+
+ expect(adapter.getStatus()).toBe(EngineStatus.READY);
+ expect(onReady).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([['disconnected', EngineStatus.DISCONNECTED] as const, ['auth_failure', EngineStatus.FAILED] as const])(
+ 'does not promote if %s fires during an in-flight probe tick',
+ async (event, expectedStatus) => {
+ jest.useFakeTimers();
+
+ const adapter = newAdapter();
+ const { client, onReady } = attachFakeClient(adapter);
+ client.pupPage.evaluate.mockImplementation(() => {
+ client.emit(event, 'test teardown');
+ return Promise.resolve(true);
+ });
+
+ client.emit('authenticated');
+ await jest.advanceTimersByTimeAsync(2100);
+
+ expect(adapter.getStatus()).toBe(expectedStatus);
+ expect(onReady).not.toHaveBeenCalled();
+ expect(jest.getTimerCount()).toBe(0);
+ },
+ );
+
+ it('keeps repeated authenticated events to one timer chain and ignores authenticated after ready', async () => {
+ jest.useFakeTimers();
+
+ const adapter = newAdapter();
+ const { client, onReady } = attachFakeClient(adapter);
+
+ client.emit('authenticated');
+ expect(jest.getTimerCount()).toBe(1);
+ client.emit('authenticated');
+ expect(jest.getTimerCount()).toBe(1);
+
+ await jest.advanceTimersByTimeAsync(2100);
+ client.emit('authenticated');
+
+ expect(adapter.getStatus()).toBe(EngineStatus.READY);
+ expect(jest.getTimerCount()).toBe(0);
+ expect(onReady).toHaveBeenCalledTimes(1);
+ });
+
+ it('disables ready reconciliation before disconnect awaits client teardown', async () => {
+ await expectNoReadyDuringTeardown(
+ (client, teardownWait) => {
+ client.destroy = jest.fn().mockReturnValue(teardownWait);
+ },
+ adapter => adapter.disconnect(),
+ );
+ });
+
+ it('disables ready reconciliation before logout awaits client teardown', async () => {
+ await expectNoReadyDuringTeardown(
+ (client, teardownWait) => {
+ client.logout = jest.fn().mockReturnValue(teardownWait);
+ client.destroy = jest.fn().mockResolvedValue(undefined);
+ },
+ adapter => adapter.logout(),
+ );
+ });
+
+ it('disables ready reconciliation before destroy awaits client teardown', async () => {
+ await expectNoReadyDuringTeardown(
+ (client, teardownWait) => {
+ client.destroy = jest.fn().mockReturnValue(teardownWait);
+ },
+ adapter => adapter.destroy(),
+ );
+ });
+
+ it('disables ready reconciliation before forceDestroy awaits client teardown', async () => {
+ await expectNoReadyDuringTeardown(
+ (client, teardownWait) => {
+ client.pupBrowser = { process: jest.fn().mockReturnValue({ kill: jest.fn() }) };
+ client.destroy = jest.fn().mockReturnValue(teardownWait);
+ },
+ adapter => adapter.forceDestroy(),
+ );
+ });
+
+ // A re-fired 'authenticated' (whatsapp-web.js can emit it again on a resume/resync before 'ready')
+ // must NOT restart the 90s reconcile window, or a flapping link keeps the probe alive forever.
+ it('does not reset the 90s reconcile deadline when authenticated re-fires mid-probe', async () => {
+ jest.useFakeTimers();
+
+ const adapter = newAdapter();
+ // Runtime never reports the WWebJS global, so the probe never promotes and ticks to the deadline.
+ const { client } = attachFakeClient(adapter, { pupPage: { evaluate: jest.fn().mockResolvedValue(false) } });
+
+ client.emit('authenticated');
+ await jest.advanceTimersByTimeAsync(80_000);
+ expect(adapter.getStatus()).toBe(EngineStatus.AUTHENTICATING);
+
+ client.emit('authenticated'); // re-fire 80s in — must not restart the window
+ await jest.advanceTimersByTimeAsync(11_000); // 91s total since the FIRST authenticated
+
+ expect(adapter.getStatus()).toBe(EngineStatus.AUTHENTICATING);
+ expect(jest.getTimerCount()).toBe(0); // gave up at 90s; not reset by the re-fire
+ });
+
+ // beginClientTeardown sets DISCONNECTED before the awaited destroy/logout; an 'authenticated' event
+ // arriving in that window must not resurrect the adapter to AUTHENTICATING.
+ it('ignores an authenticated event fired during teardown (status stays disconnected)', async () => {
+ jest.useFakeTimers();
+
+ const adapter = newAdapter();
+ const teardownWait = deferredVoid();
+ const { client, onReady } = attachFakeClient(adapter);
+ client.destroy = jest.fn().mockReturnValue(teardownWait.promise);
+
+ client.emit('authenticated');
+ expect(adapter.getStatus()).toBe(EngineStatus.AUTHENTICATING);
+
+ const teardown = adapter.disconnect();
+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);
+ expect(jest.getTimerCount()).toBe(0);
+
+ client.emit('authenticated'); // must NOT revive to AUTHENTICATING / re-arm the probe
+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);
+ expect(jest.getTimerCount()).toBe(0);
+
+ teardownWait.resolve();
+ await teardown;
+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);
+ expect(onReady).not.toHaveBeenCalled();
+ });
+
+ // A wedged page can make getState() hang (the exact #251/#273 condition). The probe must keep its
+ // own cadence (a hung probe can't stall the loop) and still honor the 90s give-up deadline.
+ it('keeps probing and still times out when getState hangs instead of stalling forever', async () => {
+ jest.useFakeTimers();
+
+ const adapter = newAdapter();
+ const { client } = attachFakeClient(adapter, { getState: jest.fn().mockReturnValue(new Promise<never>(() => {})) });
+
+ client.emit('authenticated');
+ await jest.advanceTimersByTimeAsync(50_000);
+ expect(jest.getTimerCount()).toBe(1); // chain still alive despite the hung probe
+
+ await jest.advanceTimersByTimeAsync(45_000); // ~95s total
+ expect(adapter.getStatus()).toBe(EngineStatus.AUTHENTICATING); // never falsely promoted
+ expect(jest.getTimerCount()).toBe(0); // gave up at the 90s deadline
+ // The at-most-one-in-flight guard must keep the single hung probe from piling up: getState is
+ // issued once and not re-issued while it's still pending (a guard-less per-tick probe would be ~45).
+ expect(client.getState).toHaveBeenCalledTimes(1);
+ });
+});
+
describe('WhatsAppWebJsAdapter.resolveContactPhone (@lid -> phone, #263)', () => {
// Stub a "ready" adapter with a fake client so we exercise the mapping without a real browser.
const readyAdapter = (getContactLidAndPhone: jest.Mock): WhatsAppWebJsAdapter => {
@@ -328,23 +600,24 @@ describe('resolveWebVersionPin (#251 — opt-in WA-Web version pin)', () => {
else process.env.WWEBJS_WEB_VERSION_REMOTE_PATH = orig.p;
});
- it('returns undefined (default auto-version) when unset / "latest" / "off"', () => {
+ it('returns undefined (default auto-version) when unset / "latest" / "off" / "auto"', () => {
delete process.env.WWEBJS_WEB_VERSION;
expect(resolveWebVersionPin()).toBeUndefined();
- process.env.WWEBJS_WEB_VERSION = 'latest';
- expect(resolveWebVersionPin()).toBeUndefined();
- process.env.WWEBJS_WEB_VERSION = 'off';
- expect(resolveWebVersionPin()).toBeUndefined();
+ for (const value of ['latest', 'off', 'auto']) {
+ process.env.WWEBJS_WEB_VERSION = value;
+ expect(resolveWebVersionPin()).toBeUndefined();
+ }
});
it('pins a remote webVersionCache from the version when set', () => {
delete process.env.WWEBJS_WEB_VERSION_REMOTE_PATH;
- process.env.WWEBJS_WEB_VERSION = '2.3000.1023204257';
+ process.env.WWEBJS_WEB_VERSION = '2.3000.1041203030-alpha';
expect(resolveWebVersionPin()).toEqual({
- webVersion: '2.3000.1023204257',
+ webVersion: '2.3000.1041203030-alpha',
webVersionCache: {
type: 'remote',
- remotePath: 'https://raw.githubusercontent.com/wppconnect-team/wa-version/main/html/2.3000.1023204257.html',
+ remotePath:
+ 'https://raw.githubusercontent.com/wppconnect-team/wa-version/main/html/2.3000.1041203030-alpha.html',
},
});
});
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index b731d2834..8ef2eb896 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -1,5 +1,5 @@
import { EventEmitter } from 'events';
-import { Client, LocalAuth, MessageMedia, MessageTypes } from 'whatsapp-web.js';
+import { Client, LocalAuth, MessageMedia, MessageTypes, WAState } from 'whatsapp-web.js';
import * as qrcode from 'qrcode';
import * as path from 'path';
import {
@@ -115,19 +115,21 @@ export interface WhatsAppWebJsConfig {
};
}
+const READY_RECONCILE_INTERVAL_MS = 2000;
+const READY_RECONCILE_TIMEOUT_MS = 90_000;
+
/**
* Optional pin for the WhatsApp Web client version. whatsapp-web.js 1.34.x can get stuck at
- * "authenticating" (the post-link sync never completes) when the auto-fetched WA-Web version is
- * incompatible (#251). Set WWEBJS_WEB_VERSION to a known-good version string (browse
- * https://github.com/wppconnect-team/wa-version) to pin it; WWEBJS_WEB_VERSION_REMOTE_PATH
+ * "authenticating" when the auto-fetched WA-Web version is incompatible (#251/#273). Set
+ * WWEBJS_WEB_VERSION to a known-good version string to pin it; WWEBJS_WEB_VERSION_REMOTE_PATH
* overrides the URL template (use `{version}` as the placeholder) if you self-host the HTML.
- * Unset (or `latest`/`off`) keeps whatsapp-web.js's default auto-version behavior.
+ * Unset (or `latest`/`off`/`auto`) keeps whatsapp-web.js's default auto-version behavior.
*/
export function resolveWebVersionPin():
| { webVersion: string; webVersionCache: { type: 'remote'; remotePath: string } }
| undefined {
const version = process.env.WWEBJS_WEB_VERSION?.trim();
- if (!version || version.toLowerCase() === 'off' || version.toLowerCase() === 'latest') {
+ if (!version || ['off', 'latest', 'auto'].includes(version.toLowerCase())) {
return undefined;
}
const template =
@@ -184,6 +186,12 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
private phoneNumber: string | null = null;
private pushName: string | null = null;
private callbacks: EngineEventCallbacks = {};
+ private readyReconcileTimer: ReturnType<typeof setTimeout> | null = null;
+ private readyReconcileStartedAt = 0;
+ private readyReconcileProbeInFlight = false;
+ // Set once teardown begins so a late 'authenticated' can't resurrect a disconnecting adapter. Not
+ // reset — an adapter is single-use after teardown (the session creates a fresh one to reconnect).
+ private tearingDown = false;
constructor(private readonly config: WhatsAppWebJsConfig) {
super();
@@ -275,22 +283,25 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
});
this.client.on('authenticated', () => {
+ // Only the first authentication starts the reconcile window. Ignore a re-fired 'authenticated'
+ // while already AUTHENTICATING (so it can't restart the 90s deadline), once READY/FAILED, or any
+ // time during/after teardown (so a late event can't resurrect a disconnecting adapter). The
+ // initial status is DISCONNECTED, so teardown is distinguished by the flag, not by DISCONNECTED.
+ if (
+ this.tearingDown ||
+ this.status === EngineStatus.AUTHENTICATING ||
+ this.status === EngineStatus.READY ||
+ this.status === EngineStatus.FAILED
+ ) {
+ return;
+ }
this.setStatus(EngineStatus.AUTHENTICATING);
this.qrCode = null;
+ this.scheduleReadyReconcile();
});
this.client.on('ready', () => {
- try {
- const info = this.client?.info;
- this.phoneNumber = info?.wid?.user || null;
- this.pushName = info?.pushname || null;
- this.setStatus(EngineStatus.READY);
- this.callbacks.onReady?.(this.phoneNumber || '', this.pushName || '');
- } catch (error) {
- this.logger.error('Error getting client info', String(error));
- this.setStatus(EngineStatus.READY);
- this.callbacks.onReady?.('', '');
- }
+ this.markReadyFromClientInfo();
});
// eslint-disable-next-line @typescript-eslint/no-misused-promises
@@ -423,11 +434,13 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
});
this.client.on('disconnected', reason => {
+ this.clearReadyReconcile();
this.setStatus(EngineStatus.DISCONNECTED);
this.callbacks.onDisconnected?.(reason);
});
this.client.on('auth_failure', (message?: string) => {
+ this.clearReadyReconcile();
this.setStatus(EngineStatus.FAILED);
// Authentication failure is terminal: the stored credentials are invalid and
// reconnecting will not help — the operator must re-scan the QR code. Route it
@@ -436,51 +449,156 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
});
}
+ private markReadyFromClientInfo(): void {
+ if ([EngineStatus.READY, EngineStatus.DISCONNECTED, EngineStatus.FAILED].includes(this.status)) return;
+ this.clearReadyReconcile();
+ try {
+ const info = this.client?.info;
+ this.phoneNumber = info?.wid?.user || null;
+ this.pushName = info?.pushname || null;
+ this.setStatus(EngineStatus.READY);
+ this.callbacks.onReady?.(this.phoneNumber || '', this.pushName || '');
+ } catch (error) {
+ this.logger.error('Error getting client info', String(error));
+ this.setStatus(EngineStatus.READY);
+ this.callbacks.onReady?.('', '');
+ }
+ }
+
+ private scheduleReadyReconcile(): void {
+ this.clearReadyReconcile();
+ this.readyReconcileStartedAt = Date.now();
+
+ const tick = (): void => {
+ if (!this.client || this.status !== EngineStatus.AUTHENTICATING) {
+ this.clearReadyReconcile();
+ return;
+ }
+
+ // Deadline checked at the TOP of every tick (not after the probe) so a slow/hung getState() — a
+ // wedged page can make it never resolve, the very #251/#273 condition — can't defeat the 90s ceiling.
+ if (Date.now() - this.readyReconcileStartedAt >= READY_RECONCILE_TIMEOUT_MS) {
+ this.logger.warn('Timed out waiting for WhatsApp Web runtime readiness after authentication');
+ this.clearReadyReconcile();
+ return;
+ }
+
+ // Schedule the next tick up front, independent of the probe, so a hung probe can never stall the
+ // loop. The probe runs fire-and-forget with at-most-one in flight: if the previous one is still
+ // pending (hung), skip this round — the loop keeps ticking and gives up at the deadline above.
+ this.readyReconcileTimer = setTimeout(tick, READY_RECONCILE_INTERVAL_MS);
+ this.readyReconcileTimer.unref?.();
+
+ if (this.readyReconcileProbeInFlight) return;
+ this.readyReconcileProbeInFlight = true;
+ void this.isClientRuntimeReady()
+ .then(ready => {
+ if (ready && this.client && this.status === EngineStatus.AUTHENTICATING) {
+ this.logger.warn('WhatsApp Web ready event was missed; reconciling from connected runtime state');
+ this.markReadyFromClientInfo();
+ }
+ })
+ .catch(error => this.logger.debug('Ready reconciliation probe failed', { error: String(error) }))
+ .finally(() => {
+ this.readyReconcileProbeInFlight = false;
+ });
+ };
+
+ this.readyReconcileTimer = setTimeout(tick, READY_RECONCILE_INTERVAL_MS);
+ this.readyReconcileTimer.unref?.();
+ }
+
+ private clearReadyReconcile(): void {
+ if (this.readyReconcileTimer) {
+ clearTimeout(this.readyReconcileTimer);
+ this.readyReconcileTimer = null;
+ }
+ this.readyReconcileStartedAt = 0;
+ this.readyReconcileProbeInFlight = false;
+ }
+
+ private async isClientRuntimeReady(): Promise<boolean> {
+ if (!this.client) return false;
+ if ((await this.client.getState()) !== WAState.CONNECTED) return false;
+ if (!this.client.info?.wid?.user) return false;
+
+ const page = (this.client as unknown as { pupPage?: { evaluate: <T>(fn: () => T) => Promise<T> } }).pupPage;
+ const hasWWebJS = await page?.evaluate(
+ () => typeof (window as unknown as { WWebJS?: unknown }).WWebJS !== 'undefined',
+ );
+ return hasWWebJS === true;
+ }
+
private setStatus(status: EngineStatus): void {
this.status = status;
this.callbacks.onStateChanged?.(status);
this.emit('stateChanged', status);
}
- async disconnect(): Promise<void> {
- if (this.client) {
- try {
- // Use destroy instead of logout to preserve session data
- // This allows reconnecting without needing to scan QR again
- await this.client.destroy();
- } catch (error) {
- this.logger.warn('Destroy client failed:', String(error));
- // Already destroyed or not initialized - ignore
- }
- this.client = null;
+ private beginClientTeardown(): Client | null {
+ const client = this.client;
+ if (!client) return null;
+
+ this.tearingDown = true;
+ this.clearReadyReconcile();
+ if (this.status !== EngineStatus.DISCONNECTED) {
this.setStatus(EngineStatus.DISCONNECTED);
}
+
+ return client;
+ }
+
+ private finishClientTeardown(client: Client): void {
+ if (this.client === client) {
+ this.client = null;
+ }
+ this.clearReadyReconcile();
+ }
+
+ async disconnect(): Promise<void> {
+ const client = this.beginClientTeardown();
+ if (!client) return;
+
+ try {
+ // Use destroy instead of logout to preserve session data
+ // This allows reconnecting without needing to scan QR again
+ await client.destroy();
+ } catch (error) {
+ this.logger.warn('Destroy client failed:', String(error));
+ // Already destroyed or not initialized - ignore
+ } finally {
+ this.finishClientTeardown(client);
+ }
}
async logout(): Promise<void> {
- if (this.client) {
+ const client = this.beginClientTeardown();
+ if (!client) return;
+
+ try {
+ // Logout clears session data - user will need to scan QR again
+ await client.logout();
+ } catch (error) {
+ this.logger.warn('Logout failed:', String(error));
+ // Fall back to destroy if logout fails
try {
- // Logout clears session data - user will need to scan QR again
- await this.client.logout();
- } catch (error) {
- this.logger.warn('Logout failed:', String(error));
- // Fall back to destroy if logout fails
- try {
- await this.client.destroy();
- } catch (destroyError) {
- this.logger.warn('Client destroy also failed during logout fallback', String(destroyError));
- }
+ await client.destroy();
+ } catch (destroyError) {
+ this.logger.warn('Client destroy also failed during logout fallback', String(destroyError));
}
- this.client = null;
- this.setStatus(EngineStatus.DISCONNECTED);
+ } finally {
+ this.finishClientTeardown(client);
}
}
async destroy(): Promise<void> {
- if (this.client) {
- await this.client.destroy();
- this.client = null;
- this.setStatus(EngineStatus.DISCONNECTED);
+ const client = this.beginClientTeardown();
+ if (!client) return;
+
+ try {
+ await client.destroy();
+ } finally {
+ this.finishClientTeardown(client);
}
}
@@ -491,7 +609,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
* can't prevent the engine from being torn down and the status reset.
*/
async forceDestroy(): Promise<void> {
- const client = this.client;
+ const client = this.beginClientTeardown();
if (!client) return;
try {
@@ -508,10 +626,9 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
await client.destroy();
} catch (err) {
this.logger.warn('forceDestroy: client.destroy() failed after the kill (continuing)', { error: String(err) });
+ } finally {
+ this.finishClientTeardown(client);
}
-
- this.client = null;
- this.setStatus(EngineStatus.DISCONNECTED);
}
getStatus(): EngineStatus {