Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): report INITIALIZING instead of READY while the Baileys socket is in reconnect backoff (#944)
Yudhi Armyndharis3b40fa007825
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 9117b80f4..3454392f2 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -661,6 +661,97 @@ describe('BaileysAdapter reconnect socket teardown (no leak)', () => {});});+describe('BaileysAdapter status honesty across the reconnect backoff', () => {+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion+ const baileys = () => jest.requireMock('@whiskeysockets/baileys') as { default: jest.Mock };++ const fireRecoverableClose = (): void => {+ fakeSock.fire('connection.update', {+ connection: 'close',+ lastDisconnect: { error: { output: { statusCode: 515 } } },+ });+ };++ const initReady = async (over: Partial<EngineEventCallbacks> = {}): Promise<BaileysAdapter> => {+ fakeSock.user = undefined;+ fakeSock.resetEmitter();+ jest.clearAllMocks();+ const adapter = newAdapter();+ await adapter.initialize(noopCallbacks(over));+ fakeSock.fire('connection.update', { connection: 'open' });+ return adapter;+ };++ afterEach(() => {+ jest.useRealTimers();+ jest.restoreAllMocks();+ });++ it('a transient close drops the session to INITIALIZING immediately — no READY across the backoff', async () => {+ const states: EngineStatus[] = [];+ const adapter = await initReady({ onStateChanged: s => states.push(s) });+ expect(adapter.getStatus()).toBe(EngineStatus.READY);+ states.length = 0; // count only the transitions from READY onward++ jest.useFakeTimers();+ fireRecoverableClose();++ // The reconnect timer is still pending (first attempt is ~1 s out, later ones up to 60 s) and+ // the socket is already dead — the session must NOT read READY in this window.+ expect(adapter.getStatus()).toBe(EngineStatus.INITIALIZING);+ await expect(adapter.probeLiveness()).resolves.toBe(false);+ expect(states).toEqual([EngineStatus.INITIALIZING]);+ });++ it('stays INITIALIZING until the reconnected socket actually opens, then reports READY again', async () => {+ const adapter = await initReady({});+ baileys().default.mockClear();+ jest.useFakeTimers();+ jest.spyOn(Math, 'random').mockReturnValue(0); // deterministic 1 s first-attempt delay++ fireRecoverableClose();+ expect(adapter.getStatus()).toBe(EngineStatus.INITIALIZING);++ await jest.advanceTimersByTimeAsync(1_000); // attempt 1 runs → new socket created+ expect(baileys().default).toHaveBeenCalledTimes(1);+ // The new socket exists but has not opened yet — still not READY.+ expect(adapter.getStatus()).toBe(EngineStatus.INITIALIZING);++ fakeSock.fire('connection.update', { connection: 'open' });+ expect(adapter.getStatus()).toBe(EngineStatus.READY);+ await expect(adapter.probeLiveness()).resolves.toBe(true);+ });++ it('back-to-back transient closes do not flap onStateChanged', async () => {+ const states: EngineStatus[] = [];+ await initReady({ onStateChanged: s => states.push(s) });+ states.length = 0; // count only the transitions from READY onward++ jest.useFakeTimers();+ fireRecoverableClose();+ fireRecoverableClose(); // duplicate for the same drop — ignored, no extra transition+ expect(states).toEqual([EngineStatus.INITIALIZING]);++ await jest.advanceTimersByTimeAsync(2_000); // let the pending attempt run (1 s + jitter)+ fireRecoverableClose(); // the next drop lands while already INITIALIZING — still no emission+ expect(states).toEqual([EngineStatus.INITIALIZING]);+ });++ it('a logged-out close still reports DISCONNECTED (terminal behavior unchanged)', async () => {+ const onDisconnected = jest.fn();+ const adapter = await initReady({ onDisconnected });++ fakeSock.fire('connection.update', {+ connection: 'close',+ lastDisconnect: { error: { output: { statusCode: 401 } } },+ });++ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);+ expect(onDisconnected).toHaveBeenCalledWith('logged out');+ await expect(adapter.probeLiveness()).resolves.toBe(false);+ });+});+describe('BaileysAdapter capability gating', () => {it('throws EngineNotSupportedError for still-gated methods (e.g. getChatHistory)', async () => {const adapter = newAdapter();diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex 6403bf797..9e1873af8 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -438,9 +438,16 @@ export class BaileysAdapter implements IWhatsAppEngine {// backoff and NO attempt ceiling — a long network outage must// not kill the session. The counter resets on 'open' and via the stability window below.// Do NOT fire onDisconnected here; this is a transient drop, not a terminal disconnect.- // connect() calls setStatus(INITIALIZING) which fires onStateChanged — that is the correct signal.this.logger.log('Baileys connection dropped; reconnecting', { statusCode });+ // The socket is dead NOW, but the reconnect attempt only runs after the backoff delay below+ // (up to 60 s + jitter; connectInner's own setStatus(INITIALIZING) fires just before the new+ // socket is created). Staying READY across that window makes probeLiveness() report a live+ // session and lets sends fail against the dead socket, so drop to INITIALIZING here — the+ // 'open' branch restores READY. setStatus no-ops on an unchanged status, so the duplicate+ // closes Baileys can emit per drop do not flap onStateChanged.+ this.setStatus(EngineStatus.INITIALIZING);+// Duplicate close while a reconnect timer is already pending — ignore it WITHOUT burning an// attempt (Baileys can emit more than one close per drop; the increment must come after this).if (this.reconnectTimer) {@@ -580,7 +587,8 @@ export class BaileysAdapter implements IWhatsAppEngine {/*** Cheap local liveness check for the session watchdog. Genuine dead-connection detection is owned* by Baileys' built-in keepalive, which surfaces a close event (408) within ~35 s of a silent- * drop and drives the reconnect path above — so READY + a live socket is sufficient here.+ * drop — and the close handler above drops the status to INITIALIZING for the whole reconnect+ * backoff, so READY + a live socket is sufficient here.*/// eslint-disable-next-line @typescript-eslint/require-awaitasync probeLiveness(): Promise<boolean> {