Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): keep long-lived sessions alive with a liveness watchdog and unlimited reconnect (#798)

Yudhi Armyndharis498c2f2714cb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 290f71aee..9bf374d91 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+
+- Long-lived sessions no longer die permanently after hours of uptime. A dead whatsapp-web.js
+ Chromium (browser process exit, renderer crash, or closed page) is now detected through the
+ puppeteer lifecycle handles and driven through the standard disconnect → reconnect pipeline, and
+ a session watchdog probes READY engines every 60 seconds, treating two consecutive liveness-probe
+ failures as a disconnect. The reconnect budget is now unlimited by default (exponential backoff
+ capped at 1 hour, counter reset after 5 stable minutes) instead of a terminal failure after 5
+ attempts; explicit `maxReconnectAttempts` (`0` = disabled, clamped to 1–20) is unchanged. On the
+ Baileys engine, `connectionReplaced` (440) is now terminal instead of fighting the other instance,
+ duplicate close events no longer burn retry attempts, and a failed reconnect attempt no longer
+ fails the session.
+
## [0.9.0] - 2026-07-18
### Added
diff --git a/docs/08-development-guidelines.md b/docs/08-development-guidelines.md
index 8addc03d2..9ca4aa662 100644
--- a/docs/08-development-guidelines.md
+++ b/docs/08-development-guidelines.md
@@ -404,8 +404,10 @@ import { resolveReconnectConfig } from './session.service';
describe('resolveReconnectConfig', () => {
it('keeps reconnect settings finite and bounded', () => {
+ // Invalid maxReconnectAttempts falls back to the default: unlimited retries (the backoff
+ // parks at the 1h cap); an invalid baseDelay is clamped up to the 1s minimum.
expect(resolveReconnectConfig({ maxReconnectAttempts: 'bad', reconnectBaseDelay: -1 })).toEqual({
- maxAttempts: 5,
+ maxAttempts: Number.POSITIVE_INFINITY,
baseDelay: 1000,
});
});
diff --git a/docs/09-testing-strategy.md b/docs/09-testing-strategy.md
index 65c563dc2..9d15cdb5b 100644
--- a/docs/09-testing-strategy.md
+++ b/docs/09-testing-strategy.md
@@ -105,7 +105,9 @@ describe('resolveReconnectConfig', () => {
maxReconnectAttempts: 'not-a-number',
reconnectBaseDelay: -1,
}),
- ).toEqual({ maxAttempts: 5, baseDelay: 1000 });
+ // non-numeric attempts → the default: unlimited retries (backoff parks at the 1h cap);
+ // negative baseDelay → clamped up to the 1s minimum
+ ).toEqual({ maxAttempts: Number.POSITIVE_INFINITY, baseDelay: 1000 });
});
});
```
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index be2c92435..4a43cc8ec 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -79,7 +79,7 @@ jest.mock('@whiskeysockets/baileys', () => ({
),
// Identity passthrough by default; individual tests may override to simulate unwrapping.
normalizeMessageContent: jest.fn((c: unknown) => c),
- DisconnectReason: { loggedOut: 401, restartRequired: 515 },
+ DisconnectReason: { loggedOut: 401, restartRequired: 515, connectionReplaced: 440 },
proto: {
Message: {
ProtocolMessage: {
@@ -234,14 +234,15 @@ describe('BaileysAdapter lifecycle & status', () => {
const makeWASocket = jest.requireMock('@whiskeysockets/baileys').default as jest.Mock;
makeWASocket.mockClear();
- // Reconnect is now backoff-delayed (1 s on first attempt): use fake timers to advance.
+ // Reconnect is backoff-delayed (1 s + up to 1 s jitter on the first attempt): advance past the
+ // worst-case delay with fake timers.
jest.useFakeTimers({ doNotFake: ['setImmediate'] });
try {
fakeSock.fire('connection.update', {
connection: 'close',
lastDisconnect: { error: { output: { statusCode: 515 } } },
});
- jest.advanceTimersByTime(1_000);
+ jest.advanceTimersByTime(2_000);
await new Promise(r => setImmediate(r)); // let the async connect() body reach makeWASocket
expect(makeWASocket).toHaveBeenCalledTimes(1);
expect(onDisconnected).not.toHaveBeenCalled();
@@ -324,9 +325,10 @@ describe('BaileysAdapter lifecycle & status', () => {
});
});
-describe('BaileysAdapter lifecycle hardening — I4 reconnect backoff', () => {
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
- const baileys = () => jest.requireMock('@whiskeysockets/baileys') as { default: jest.Mock };
+describe('BaileysAdapter reconnect policy — unlimited backoff (I4 hardening)', () => {
+ const baileys = () =>
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
+ jest.requireMock('@whiskeysockets/baileys') as { default: jest.Mock; fetchLatestBaileysVersion: jest.Mock };
const fireRecoverableClose = (): void => {
fakeSock.fire('connection.update', {
@@ -347,66 +349,146 @@ describe('BaileysAdapter lifecycle hardening — I4 reconnect backoff', () => {
};
afterEach(() => {
- // Ensure fake timers are always cleaned up even if a test fails mid-way.
+ // Ensure fake timers / Math.random spies are always cleaned up even if a test fails mid-way.
jest.useRealTimers();
+ jest.restoreAllMocks();
});
- it('I4: after MAX_RECONNECT_ATTEMPTS recoverable closes → FAILED + onError, no more reconnects', async () => {
+ it('unlimited retry: closes beyond the old 5-attempt cap keep reconnecting, backoff capped at 60 s', async () => {
const onError = jest.fn();
const adapter = await initWithRealTimers({ onError });
-
- // Switch to fake timers AFTER initialize() has resolved.
+ baileys().default.mockClear();
jest.useFakeTimers();
+ jest.spyOn(Math, 'random').mockReturnValue(0); // deterministic delays (jitter = 0)
- // Each close increments reconnectAttempts and schedules a timer.
- // After the timer fires, connect() calls makeWASocket() which resets the emitter,
- // so each reconnect cycle has exactly one listener — no accumulation across attempts.
- // Strategy: fire close → run timers (reconnect executes, emitter reset) → fire close again → repeat.
- for (let i = 0; i < 5 /* MAX_RECONNECT_ATTEMPTS */; i++) {
+ // 7 recoverable drops — beyond the old MAX_RECONNECT_ATTEMPTS (5). Each close schedules a
+ // reconnect; consecutive closes land 61 s apart, so the 5-min stability reset never trips
+ // and the attempt counter climbs 1..7 (delays 1/2/4/8/16/32/60 s).
+ for (let i = 0; i < 7; i++) {
fireRecoverableClose();
- await jest.runAllTimersAsync();
+ await jest.advanceTimersByTimeAsync(61_000); // covers any delay up to the 60 s cap
}
+ expect(baileys().default).toHaveBeenCalledTimes(7);
- // The (MAX+1)th close — reconnectAttempts is now MAX (5) → exhausted path:
- // no reconnect scheduled, status → FAILED, onError fired exactly once.
+ // Attempt 8: 2^(8-1) s = 128 s would EXCEED the cap — the scheduled delay must be exactly 60 s
+ // (advancing precisely 60 s fires the timer only when the cap held).
fireRecoverableClose();
- await jest.runAllTimersAsync();
+ await jest.advanceTimersByTimeAsync(60_000);
+ expect(baileys().default).toHaveBeenCalledTimes(8);
- expect(adapter.getStatus()).toBe(EngineStatus.FAILED);
- expect(onError).toHaveBeenCalledTimes(1);
- expect(onError).toHaveBeenCalledWith(expect.stringContaining('exhausted'));
+ // No FAILED, no terminal onError — the "reconnect attempts exhausted" path is gone entirely.
+ expect(adapter.getStatus()).not.toBe(EngineStatus.FAILED);
+ expect(onError).not.toHaveBeenCalled();
});
- it('I4: successful connection resets the reconnect counter (next drop can reconnect again)', async () => {
- const onError = jest.fn();
- const adapter = await initWithRealTimers({ onError });
-
+ it('successful connection resets the reconnect counter (next drop uses the attempt-1 delay)', async () => {
+ const adapter = await initWithRealTimers({});
+ baileys().default.mockClear();
jest.useFakeTimers();
+ jest.spyOn(Math, 'random').mockReturnValue(0);
- // Fire one recoverable drop and reconnect — increments counter to 1
+ // Drop + reconnect — the counter is now 1 (no 'open' yet).
fireRecoverableClose();
- await jest.runAllTimersAsync();
+ await jest.advanceTimersByTimeAsync(1_000);
+ expect(baileys().default).toHaveBeenCalledTimes(1);
- // Simulate a successful open — should reset the reconnect counter to 0
+ // Simulate a successful open — should reset the reconnect counter to 0.
fakeSock.fire('connection.update', { connection: 'open' });
expect(adapter.getStatus()).toBe(EngineStatus.READY);
- // Now exhaust MAX_RECONNECT_ATTEMPTS again — should work because counter was reset
- for (let i = 0; i < 5 /* MAX_RECONNECT_ATTEMPTS */; i++) {
- fireRecoverableClose();
- await jest.runAllTimersAsync();
- }
+ // The next drop must schedule attempt 1 (1 s), not attempt 2 (2 s): 1.5 s settles it.
+ fireRecoverableClose();
+ await jest.advanceTimersByTimeAsync(1_500);
+ expect(baileys().default).toHaveBeenCalledTimes(2);
+ });
- // (MAX+1)th drop after reset → FAILED again, onError fired exactly once
+ it('stability reset: a close >5 min after the previous close restarts the backoff at attempt 1', async () => {
+ await initWithRealTimers({});
+ baileys().default.mockClear();
+ jest.useFakeTimers();
+ jest.spyOn(Math, 'random').mockReturnValue(0);
+
+ // First drop → attempt 1 (1 s); the reconnect succeeds but no 'open' arrives, so the counter
+ // stays at 1 — only the stability window can clear it.
fireRecoverableClose();
- await jest.runAllTimersAsync();
+ await jest.advanceTimersByTimeAsync(1_000);
+ expect(baileys().default).toHaveBeenCalledTimes(1);
- expect(adapter.getStatus()).toBe(EngineStatus.FAILED);
- expect(onError).toHaveBeenCalledTimes(1);
- expect(onError).toHaveBeenCalledWith(expect.stringContaining('exhausted'));
+ // Jump the clock past the 5-minute stability window without running timers (none are pending).
+ jest.setSystemTime(Date.now() + 6 * 60_000);
+
+ // A healthy-then-dropped connection must not inherit the old counter: attempt 1 (1 s), not
+ // attempt 2 (2 s) — 1.5 s settles it.
+ fireRecoverableClose();
+ await jest.advanceTimersByTimeAsync(1_500);
+ expect(baileys().default).toHaveBeenCalledTimes(2);
});
- it('I4: a recoverable close after disconnect() (intentionalClose) does NOT schedule a reconnect', async () => {
+ it('duplicate close while a reconnect timer is pending does NOT burn an attempt', async () => {
+ await initWithRealTimers({});
+ baileys().default.mockClear();
+ jest.useFakeTimers();
+ jest.spyOn(Math, 'random').mockReturnValue(0);
+
+ // Close #1 schedules attempt 1 (1 s); the duplicate close must be ignored WITHOUT incrementing.
+ fireRecoverableClose();
+ fireRecoverableClose();
+ await jest.advanceTimersByTimeAsync(1_000);
+ expect(baileys().default).toHaveBeenCalledTimes(1);
+
+ // The next close must therefore schedule attempt 2 (2 s) — not attempt 3 (4 s), which is what
+ // a burned duplicate increment would produce. 2.5 s settles it.
+ fireRecoverableClose();
+ await jest.advanceTimersByTimeAsync(2_500);
+ expect(baileys().default).toHaveBeenCalledTimes(2);
+ });
+
+ it('a connect() failure inside an attempt schedules the NEXT attempt (no FAILED, no onError)', async () => {
+ const onError = jest.fn();
+ const adapter = await initWithRealTimers({ onError });
+ baileys().default.mockClear();
+ jest.useFakeTimers();
+ jest.spyOn(Math, 'random').mockReturnValue(0);
+
+ // The first reconnect attempt fails inside connect() (e.g. fetchLatestBaileysVersion offline).
+ baileys().fetchLatestBaileysVersion.mockRejectedValueOnce(new Error('network down'));
+
+ fireRecoverableClose(); // attempt 1 (1 s)
+ await jest.advanceTimersByTimeAsync(1_000); // attempt 1 runs and FAILS → must schedule attempt 2 (2 s)
+ expect(adapter.getStatus()).not.toBe(EngineStatus.FAILED);
+ expect(onError).not.toHaveBeenCalled();
+
+ await jest.advanceTimersByTimeAsync(2_000); // attempt 2 runs and succeeds
+ expect(baileys().default).toHaveBeenCalledTimes(1); // one socket from the successful retry
+ expect(adapter.getStatus()).not.toBe(EngineStatus.FAILED);
+ expect(onError).not.toHaveBeenCalled();
+ });
+
+ it('440 connectionReplaced is terminal: FAILED + onError, NO reconnect, auth NOT cleared', async () => {
+ const onError = jest.fn();
+ const adapter = await initWithRealTimers({ onError });
+ baileys().default.mockClear();
+ const rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);
+ try {
+ jest.useFakeTimers();
+
+ fakeSock.fire('connection.update', {
+ connection: 'close',
+ lastDisconnect: { error: { output: { statusCode: 440 } } },
+ });
+ await jest.runAllTimersAsync(); // would run any scheduled reconnect — none must be scheduled
+
+ expect(adapter.getStatus()).toBe(EngineStatus.FAILED);
+ expect(onError).toHaveBeenCalledTimes(1);
+ expect(onError).toHaveBeenCalledWith(expect.stringContaining('Connection replaced by another instance (440)'));
+ expect(baileys().default).not.toHaveBeenCalled(); // no reconnect — would fight the other instance
+ expect(rmSpy).not.toHaveBeenCalled(); // auth survives — unlike loggedOut, the link is still valid
+ } finally {
+ rmSpy.mockRestore();
+ }
+ });
+
+ it('a recoverable close after disconnect() (intentionalClose) does NOT schedule a reconnect', async () => {
const adapter = await initWithRealTimers({});
baileys().default.mockClear();
@@ -421,11 +503,12 @@ describe('BaileysAdapter lifecycle hardening — I4 reconnect backoff', () => {
expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);
});
- it('I4: backoff timers are used — first reconnect is delayed ~1 s (not immediate)', async () => {
+ it('backoff timers are used — first reconnect is delayed ~1 s (not immediate)', async () => {
await initWithRealTimers({});
baileys().default.mockClear();
jest.useFakeTimers({ doNotFake: ['setImmediate'] });
+ jest.spyOn(Math, 'random').mockReturnValue(0); // deterministic delay: exactly 1 s
// First drop: should schedule at delay = 1000 ms (2^0 * 1000)
fireRecoverableClose();
@@ -442,6 +525,36 @@ describe('BaileysAdapter lifecycle hardening — I4 reconnect backoff', () => {
});
});
+describe('BaileysAdapter probeLiveness', () => {
+ beforeEach(() => {
+ fakeSock.user = undefined;
+ fakeSock.resetEmitter();
+ jest.clearAllMocks();
+ });
+
+ it('is false before initialize (no socket, not READY)', async () => {
+ const adapter = newAdapter();
+ await expect(adapter.probeLiveness()).resolves.toBe(false);
+ });
+
+ it('is false while INITIALIZING (socket exists but the connection is not open)', async () => {
+ const adapter = newAdapter();
+ await adapter.initialize(noopCallbacks({}));
+ expect(adapter.getStatus()).toBe(EngineStatus.INITIALIZING);
+ await expect(adapter.probeLiveness()).resolves.toBe(false);
+ });
+
+ it('is true when READY with a live socket, false again after disconnect', async () => {
+ const adapter = newAdapter();
+ await adapter.initialize(noopCallbacks({}));
+ fakeSock.fire('connection.update', { connection: 'open' });
+ await expect(adapter.probeLiveness()).resolves.toBe(true);
+
+ await adapter.disconnect(); // ends the socket → no longer live
+ await expect(adapter.probeLiveness()).resolves.toBe(false);
+ });
+});
+
describe('BaileysAdapter reconnect socket teardown (no leak)', () => {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const baileys = () => jest.requireMock('@whiskeysockets/baileys') as { default: jest.Mock };
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 142f8e817..97ceba150 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -115,7 +115,9 @@ function createBaileysLogger(): BaileysLogger {
}
export class BaileysAdapter implements IWhatsAppEngine {
- private static readonly MAX_RECONNECT_ATTEMPTS = 5;
+ /** A close this long after the previous close means the connection had been healthy in between —
+ * the backoff counter restarts from scratch instead of inheriting an old incident's attempts. */
+ private static readonly RECONNECT_STABILITY_RESET_MS = 5 * 60_000;
private readonly logger = createLogger('BaileysAdapter');
// Bound concurrent inbound media downloads: each materialises a full decrypted buffer in heap, so an
@@ -141,6 +143,8 @@ export class BaileysAdapter implements IWhatsAppEngine {
private connectedAt = 0;
private reconnectAttempts = 0;
private reconnectTimer?: ReturnType<typeof setTimeout>;
+ /** Date.now() of the last close that scheduled a reconnect — input to the stability reset. */
+ private lastConnectionCloseAt = 0;
/** Lazily loaded @whiskeysockets/baileys module (ESM-only; loaded on first connect, not at boot). */
private lib?: typeof BaileysLib;
@@ -370,34 +374,69 @@ export class BaileysAdapter implements IWhatsAppEngine {
return;
}
- // Recoverable (e.g. restartRequired right after pairing, transient drop) — reconnect with backoff.
+ if (statusCode === (this.lib?.DisconnectReason.connectionReplaced ?? 440)) {
+ // Another live instance took over this account (whatsmeow StreamReplaced). Reconnecting
+ // would fight it — two instances endlessly replacing each other — so this is terminal:
+ // the operator stops the other instance, then starts this session again (onError = terminal
+ // + evict in the session service). Auth state is NOT cleared: the link itself is still valid.
+ this.setStatus(EngineStatus.FAILED);
+ this.callbacks.onError?.(
+ 'Connection replaced by another instance (440) — stop the other instance, then start this session again',
+ );
+ return;
+ }
+
+ // Every other close (408/411/428/500/503/515/undefined) is transient: reconnect with capped
+ // backoff and NO attempt ceiling (whatsmeow/evolution-api style) — 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 });
- // I4: capped exponential backoff with in-flight timer guard.
- if (this.reconnectAttempts >= BaileysAdapter.MAX_RECONNECT_ATTEMPTS) {
- this.setStatus(EngineStatus.FAILED);
- this.callbacks.onError?.(`reconnect attempts exhausted (${this.reconnectAttempts})`);
- return;
- }
- this.reconnectAttempts += 1;
- const delay = Math.min(30_000, 1_000 * 2 ** (this.reconnectAttempts - 1));
- // Guard: if a timer is already pending, don't stack another one.
+ // 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) {
return;
}
- this.reconnectTimer = setTimeout(() => {
- this.reconnectTimer = undefined;
- if (this.intentionalClose) {
- return; // stopped while waiting — abort
- }
- void this.connect().catch(err => {
- this.setStatus(EngineStatus.FAILED);
- this.callbacks.onError?.(err instanceof Error ? err.message : String(err));
- });
- }, delay);
+
+ // Stability reset: a close >5 min after the previous one means the connection had been
+ // healthy in between — start the backoff fresh instead of inheriting the old counter.
+ const now = Date.now();
+ if (now - this.lastConnectionCloseAt > BaileysAdapter.RECONNECT_STABILITY_RESET_MS) {
+ this.reconnectAttempts = 0;
+ }
+ this.lastConnectionCloseAt = now;
+ this.scheduleReconnect();
+ }
+ }
+
+ /**
+ * Schedule the next reconnect attempt with capped exponential backoff (1 s doubling up to a 60 s
+ * cap, plus up to 1 s jitter). Deliberately NO attempt ceiling: transient drops retry forever —
+ * only loggedOut (401) and connectionReplaced (440) are terminal. A connect() failure inside the
+ * attempt is just a failed attempt: warn and schedule the next one.
+ */
+ private scheduleReconnect(): void {
+ if (this.intentionalClose || this.reconnectTimer) {
+ return;
}
+ this.reconnectAttempts += 1;
+ const delay = Math.min(60_000, 1_000 * 2 ** (this.reconnectAttempts - 1)) + Math.floor(Math.random() * 1000);
+ this.reconnectTimer = setTimeout(() => {
+ this.reconnectTimer = undefined;
+ if (this.intentionalClose) {
+ return; // stopped while waiting — abort
+ }
+ void this.connect().catch(err => {
+ // A failed attempt (e.g. fetchLatestBaileysVersion offline mid-outage) is NOT terminal —
+ // the outage may outlast any fixed attempt budget, so schedule the following attempt.
+ this.logger.warn('Baileys reconnect attempt failed; will retry', {
+ attempt: this.reconnectAttempts,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ this.scheduleReconnect();
+ });
+ }, delay);
}
/** Render the raw Baileys QR ref to a PNG data URL, then publish it (mirrors the whatsapp-web.js engine). */
@@ -485,6 +524,16 @@ export class BaileysAdapter implements IWhatsAppEngine {
return this.status;
}
+ /**
+ * 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.
+ */
+ // eslint-disable-next-line @typescript-eslint/require-await
+ async probeLiveness(): Promise<boolean> {
+ return this.status === EngineStatus.READY && this.sock != null;
+ }
+
getQRCode(): string | null {
return this.qrCode;
}
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index 0a7b20333..77a684d2e 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -2265,3 +2265,164 @@ describe('WhatsAppWebJsAdapter createGroup (failure shapes)', () => {
expect(res).toEqual({ id: '[email protected]', name: 'team', participantsCount: 2 });
});
});
+
+describe('WhatsAppWebJsAdapter puppeteer death detection (browser/page silent death)', () => {
+ type PuppeteerFakeClient = EventEmitter & {
+ getState: jest.Mock;
+ pupBrowser: EventEmitter;
+ pupPage: EventEmitter;
+ destroy?: jest.Mock;
+ };
+
+ const wireAdapter = (
+ overrides: { status?: EngineStatus; tearingDown?: boolean; client?: Partial<PuppeteerFakeClient> } = {},
+ ): { adapter: WhatsAppWebJsAdapter; client: PuppeteerFakeClient; onDisconnected: jest.Mock } => {
+ const adapter = new WhatsAppWebJsAdapter({
+ sessionId: 'sess-pup-death',
+ sessionDataPath: './data/sessions',
+ puppeteer: {},
+ });
+ const client = Object.assign(new EventEmitter(), {
+ getState: jest.fn().mockResolvedValue(WAState.CONNECTED),
+ pupBrowser: new EventEmitter(),
+ pupPage: new EventEmitter(),
+ ...overrides.client,
+ }) as PuppeteerFakeClient;
+ const onDisconnected = jest.fn();
+ (adapter as unknown as { client: unknown }).client = client;
+ (adapter as unknown as { callbacks: unknown }).callbacks = { onDisconnected };
+ (adapter as unknown as { status: EngineStatus }).status = overrides.status ?? EngineStatus.READY;
+ (adapter as unknown as { tearingDown: boolean }).tearingDown = overrides.tearingDown ?? false;
+ (adapter as unknown as { attachPuppeteerLifecycleListeners: () => void }).attachPuppeteerLifecycleListeners();
+ return { adapter, client, onDisconnected };
+ };
+
+ it('reports the browser process closing or crashing as a disconnect', () => {
+ const { adapter, client, onDisconnected } = wireAdapter();
+
+ client.pupBrowser.emit('disconnected');
+
+ expect(onDisconnected).toHaveBeenCalledTimes(1);
+ expect(onDisconnected).toHaveBeenCalledWith('Browser process closed or crashed');
+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);
+ });
+
+ it('reports a renderer crash (page error) as a disconnect', () => {
+ const { adapter, client, onDisconnected } = wireAdapter();
+
+ client.pupPage.emit('error', new Error('Page crashed!'));
+
+ expect(onDisconnected).toHaveBeenCalledTimes(1);
+ expect(onDisconnected).toHaveBeenCalledWith('Page crashed');
+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);
+ });
+
+ it('reports the page being closed as a disconnect', () => {
+ const { adapter, client, onDisconnected } = wireAdapter();
+
+ client.pupPage.emit('close');
+
+ expect(onDisconnected).toHaveBeenCalledTimes(1);
+ expect(onDisconnected).toHaveBeenCalledWith('Page closed');
+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);
+ });
+
+ it('does not double-report when page error and browser disconnected fire together', () => {
+ const { client, onDisconnected } = wireAdapter();
+
+ client.pupPage.emit('error', new Error('Page crashed!'));
+ client.pupBrowser.emit('disconnected');
+ client.pupPage.emit('close');
+
+ expect(onDisconnected).toHaveBeenCalledTimes(1);
+ expect(onDisconnected).toHaveBeenCalledWith('Page crashed');
+ });
+
+ it.each([
+ ['pupBrowser', 'disconnected'],
+ ['pupPage', 'error'],
+ ['pupPage', 'close'],
+ ] as const)('ignores %s %s during an intentional teardown', (handle, event) => {
+ const { client, onDisconnected } = wireAdapter({ tearingDown: true });
+
+ client[handle].emit(event, new Error('boom'));
+
+ expect(onDisconnected).not.toHaveBeenCalled();
+ });
+
+ it('ignores the death events once the status is already DISCONNECTED', () => {
+ const { client, onDisconnected } = wireAdapter({ status: EngineStatus.DISCONNECTED });
+
+ client.pupBrowser.emit('disconnected');
+ client.pupPage.emit('error', new Error('boom'));
+ client.pupPage.emit('close');
+
+ expect(onDisconnected).not.toHaveBeenCalled();
+ });
+
+ it('ignores the browser disconnected event raised by a deliberate disconnect()', async () => {
+ const destroy = jest.fn().mockResolvedValue(undefined);
+ const { adapter, client, onDisconnected } = wireAdapter({ client: { destroy } });
+
+ await adapter.disconnect(); // sets tearingDown + DISCONNECTED, then destroys the client
+ client.pupBrowser.emit('disconnected');
+
+ expect(destroy).toHaveBeenCalledTimes(1);
+ expect(onDisconnected).not.toHaveBeenCalled();
+ });
+});
+
+describe('WhatsAppWebJsAdapter.probeLiveness (session watchdog probe)', () => {
+ const adapterWith = (client: unknown, status: EngineStatus = EngineStatus.READY): WhatsAppWebJsAdapter => {
+ const adapter = new WhatsAppWebJsAdapter({ sessionId: 's', sessionDataPath: './data/sessions', puppeteer: {} });
+ (adapter as unknown as { status: EngineStatus }).status = status;
+ (adapter as unknown as { client: unknown }).client = client;
+ return adapter;
+ };
+
+ it('resolves true when getState() reports CONNECTED', async () => {
+ const adapter = adapterWith({ getState: jest.fn().mockResolvedValue(WAState.CONNECTED) });
+
+ await expect(adapter.probeLiveness()).resolves.toBe(true);
+ });
+
+ it('resolves false when getState() rejects (page already gone)', async () => {
+ const adapter = adapterWith({ getState: jest.fn().mockRejectedValue(new Error('Target closed')) });
+
+ await expect(adapter.probeLiveness()).resolves.toBe(false);
+ });
+
+ it('resolves false when getState() reports a non-CONNECTED state', async () => {
+ const adapter = adapterWith({ getState: jest.fn().mockResolvedValue(WAState.OPENING) });
+
+ await expect(adapter.probeLiveness()).resolves.toBe(false);
+ });
+
+ it('resolves false without touching the client when the adapter is not READY', async () => {
+ const getState = jest.fn();
+ const adapter = adapterWith({ getState }, EngineStatus.AUTHENTICATING);
+
+ await expect(adapter.probeLiveness()).resolves.toBe(false);
+ expect(getState).not.toHaveBeenCalled();
+ });
+
+ it('resolves false when there is no client', async () => {
+ await expect(adapterWith(null).probeLiveness()).resolves.toBe(false);
+ });
+
+ it('resolves false when getState() hangs past the 10s timeout, leaving no dangling timer', async () => {
+ jest.useFakeTimers();
+ try {
+ const adapter = adapterWith({ getState: jest.fn().mockReturnValue(new Promise<never>(() => {})) });
+
+ const probe = adapter.probeLiveness();
+ const assertion = expect(probe).resolves.toBe(false);
+ await jest.advanceTimersByTimeAsync(10_000);
+
+ await assertion;
+ expect(jest.getTimerCount()).toBe(0);
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+});
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 595888cfd..8d76dbd73 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -459,6 +459,10 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
return;
}
await this.client.initialize();
+ // whatsapp-web.js 1.34.x never observes the Chromium process/page it drives, so a crashed
+ // browser leaves the client looking READY forever ("silent death"). Attach death listeners
+ // to the puppeteer handles so a dead browser surfaces as a normal disconnect → reconnect.
+ this.attachPuppeteerLifecycleListeners();
} catch (error) {
this.setStatus(EngineStatus.FAILED);
const reason = error instanceof Error ? error.message : String(error);
@@ -732,6 +736,39 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
});
}
+ /**
+ * Attach to the loosely-typed whatsapp-web.js puppeteer handles (same cast pattern as
+ * isClientRuntimeReady/forceDestroy). whatsapp-web.js itself never listens to these, so without
+ * this a dead Chromium is invisible: browser process death, renderer crash ("Aw Snap"), and a
+ * closed tab all mean the session is gone, no matter what status the client still reports.
+ */
+ private attachPuppeteerLifecycleListeners(): void {
+ if (!this.client) return;
+ const { pupBrowser, pupPage } = this.client as unknown as {
+ pupBrowser?: { on: (event: 'disconnected', cb: () => void) => void };
+ pupPage?: { on: (event: 'error' | 'close', cb: () => void) => void };
+ };
+ pupBrowser?.on('disconnected', () => this.handlePuppeteerDeath('Browser process closed or crashed'));
+ pupPage?.on('error', () => this.handlePuppeteerDeath('Page crashed'));
+ pupPage?.on('close', () => this.handlePuppeteerDeath('Page closed'));
+ }
+
+ /**
+ * Route a Chromium/page death (detected via the puppeteer handles) through the exact same path as
+ * the client's own 'disconnected' event. A deliberate teardown also fires the browser's
+ * 'disconnected', and a real crash usually fires page 'error' and browser 'disconnected' together
+ * — so ignore calls during teardown or once the status already is DISCONNECTED/FAILED (first
+ * signal wins, no double-report).
+ */
+ private handlePuppeteerDeath(reason: string): void {
+ if (this.tearingDown || this.status === EngineStatus.DISCONNECTED || this.status === EngineStatus.FAILED) {
+ return;
+ }
+ this.clearReadyReconcile();
+ this.setStatus(EngineStatus.DISCONNECTED);
+ this.callbacks.onDisconnected?.(reason);
+ }
+
private markReadyFromClientInfo(): void {
if ([EngineStatus.READY, EngineStatus.DISCONNECTED, EngineStatus.FAILED].includes(this.status)) return;
this.clearReadyReconcile();
@@ -962,6 +999,33 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
return this.status;
}
+ /**
+ * Active liveness probe for the session watchdog: race a real getState() round-trip against a 10s
+ * timeout. Probe failure or timeout means dead — a wedged page can keep reporting CONNECTED
+ * (whatsapp-web.js #5728), so turning consecutive probe failures into a reconnect decision stays
+ * the calling watchdog's job.
+ */
+ async probeLiveness(): Promise<boolean> {
+ if (this.status !== EngineStatus.READY || !this.client) return false;
+
+ let timeout: ReturnType<typeof setTimeout> | undefined;
+ try {
+ const state = await Promise.race([
+ this.client.getState(),
+ new Promise<never>((_, reject) => {
+ timeout = setTimeout(() => reject(new Error('liveness probe timed out')), 10_000);
+ timeout.unref?.();
+ }),
+ ]);
+ return state === WAState.CONNECTED;
+ } catch {
+ return false;
+ } finally {
+ // Never leave the timeout dangling when getState() settles first (Jest open-handle hygiene).
+ if (timeout) clearTimeout(timeout);
+ }
+ }
+
getQRCode(): string | null {
return this.qrCode;
}
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index 60f5ac73c..a66dd1440 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -454,6 +454,15 @@ export interface IWhatsAppEngine {
// Status
getStatus(): EngineStatus;
+ /**
+ * Active liveness probe: performs a real round-trip against the engine's connection and
+ * resolves true only when the session is genuinely alive. Implementations must treat probe
+ * failure/timeout as "dead" — a wedged connection can keep reporting READY (cached status),
+ * so getStatus() alone is not proof of life. Optional: engines whose transport already
+ * self-detects death (e.g. Baileys keepalive emits a close event within ~35s) may return a
+ * cheap local check. Polled periodically by the session watchdog.
+ */
+ probeLiveness?(): Promise<boolean>;
getQRCode(): string | null;
/** Request an 8-char pairing code to link via phone number instead of scanning the QR. */
requestPairingCode(phoneNumber: string): Promise<string>;
diff --git a/src/modules/session/reconnect-config.spec.ts b/src/modules/session/reconnect-config.spec.ts
index 143033594..213681509 100644
--- a/src/modules/session/reconnect-config.spec.ts
+++ b/src/modules/session/reconnect-config.spec.ts
@@ -2,18 +2,20 @@ import { resolveReconnectConfig, clampReconnectDelay } from './session.service';
// an OPERATOR-supplied session.config flows into the reconnect backoff math unchecked.
// config:{reconnectBaseDelay:'x'} makes the delay NaN -> setTimeout(fn, NaN) fires at 0 (relaunch
-// storm); config:{maxReconnectAttempts:'x'} makes the terminal guard `n >= NaN` always false, so the
-// loop never caps. These helpers coerce + clamp the config so the math is always finite and bounded.
+// storm); config:{maxReconnectAttempts:'x'} would poison the terminal guard (`n >= NaN` is always
+// false). These helpers coerce + clamp the config so the math is always finite and bounded.
describe('resolveReconnectConfig', () => {
- it('uses the 5000ms / 5-attempt defaults for absent or empty config', () => {
- expect(resolveReconnectConfig(null)).toEqual({ baseDelay: 5000, maxAttempts: 5 });
- expect(resolveReconnectConfig({})).toEqual({ baseDelay: 5000, maxAttempts: 5 });
+ it('defaults to a 5000ms base delay and UNLIMITED attempts for absent or empty config', () => {
+ // A long-lived session must keep retrying forever (the backoff parks at the 1h cap) instead of
+ // dying permanently after ~2.5 minutes like the old 5-attempt default did.
+ expect(resolveReconnectConfig(null)).toEqual({ baseDelay: 5000, maxAttempts: Number.POSITIVE_INFINITY });
+ expect(resolveReconnectConfig({})).toEqual({ baseDelay: 5000, maxAttempts: Number.POSITIVE_INFINITY });
});
- it('falls back to defaults for non-numeric (NaN) values', () => {
+ it('falls back to the defaults for non-numeric (NaN) values', () => {
expect(resolveReconnectConfig({ reconnectBaseDelay: 'x', maxReconnectAttempts: 'y' })).toEqual({
baseDelay: 5000,
- maxAttempts: 5,
+ maxAttempts: Number.POSITIVE_INFINITY,
});
});
@@ -26,7 +28,7 @@ describe('resolveReconnectConfig', () => {
expect(resolveReconnectConfig({ reconnectBaseDelay: 0 }).baseDelay).toBe(1000);
});
- it('clamps maxAttempts to the 0..20 range and floors fractions', () => {
+ it('clamps an explicit maxAttempts to the 0..20 range and floors fractions', () => {
expect(resolveReconnectConfig({ maxReconnectAttempts: 999 }).maxAttempts).toBe(20);
expect(resolveReconnectConfig({ maxReconnectAttempts: -3 }).maxAttempts).toBe(0);
expect(resolveReconnectConfig({ maxReconnectAttempts: 3.9 }).maxAttempts).toBe(3);
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index cf825b513..ed7ae113d 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -3,7 +3,12 @@ import { getRepositoryToken, getDataSourceToken } from '@nestjs/typeorm';
import { Repository, DataSource, In } from 'typeorm';
import { NotFoundException, ConflictException, BadRequestException, HttpException, HttpStatus } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
-import { SessionService, ACK_RECONCILE_DELAY_MS } from './session.service';
+import {
+ SessionService,
+ ACK_RECONCILE_DELAY_MS,
+ SESSION_WATCHDOG_INTERVAL_MS,
+ SESSION_WATCHDOG_PROBE_TIMEOUT_MS,
+} from './session.service';
import { Session, SessionStatus } from './entities/session.entity';
import { Message, MessageStatus } from '../message/entities/message.entity';
import { MessageBatch } from '../message/entities/message-batch.entity';
@@ -796,6 +801,115 @@ describe('SessionService', () => {
});
});
+ describe('scheduleReconnect (reconnect policy)', () => {
+ type PolicyInternals = {
+ reconnectStates: Map<
+ string,
+ {
+ attempts: number;
+ timer: NodeJS.Timeout | null;
+ maxAttempts: number;
+ baseDelay: number;
+ lastAttemptAt?: number;
+ }
+ >;
+ sessionErrors: Map<string, string>;
+ scheduleReconnect: (id: string, session: Session) => void;
+ executeReconnect: (...args: unknown[]) => Promise<void>;
+ };
+ const internals = (): PolicyInternals => service as unknown as PolicyInternals;
+
+ it('keeps scheduling past the old 5-attempt budget by default (unlimited), the backoff parking at the 1h cap', () => {
+ jest.useFakeTimers();
+ try {
+ const i = internals();
+ // What start() seeds when session.config sets no maxReconnectAttempts.
+ const state = { attempts: 0, timer: null, maxAttempts: Number.POSITIVE_INFINITY, baseDelay: 5000 };
+ i.reconnectStates.set('sess-uuid-1', state);
+ const exec = jest.spyOn(i, 'executeReconnect').mockResolvedValue(undefined);
+
+ // Twelve consecutive disconnects — the pre-fix default (5) would have wedged FAILED at the
+ // 6th; with the unlimited default every one schedules another attempt.
+ for (let k = 0; k < 12; k++) {
+ i.scheduleReconnect('sess-uuid-1', createMockSession());
+ }
+
+ expect(state.attempts).toBe(12);
+ expect(i.sessionErrors.has('sess-uuid-1')).toBe(false); // never terminally FAILED
+ expect(jest.getTimerCount()).toBe(1); // still exactly one pending timer
+
+ // The 12th schedule computed its delay with attempts=11: 5000*2^11 ≈ 10.24M ms, clamped to
+ // the 1h cap — the timer fires exactly at the cap, not earlier.
+ jest.advanceTimersByTime(3_599_999);
+ expect(exec).not.toHaveBeenCalled();
+ jest.advanceTimersByTime(1);
+ expect(exec).toHaveBeenCalledTimes(1);
+ } finally {
+ jest.clearAllTimers();
+ jest.useRealTimers();
+ }
+ });
+
+ it('resets the attempt budget after a 5-minute stable stretch (transient drops must not accrue)', () => {
+ jest.useFakeTimers();
+ try {
+ const i = internals();
+ const state = {
+ attempts: 4,
+ timer: null,
+ maxAttempts: Number.POSITIVE_INFINITY,
+ baseDelay: 5000,
+ lastAttemptAt: Date.now(),
+ };
+ i.reconnectStates.set('sess-uuid-1', state);
+ const exec = jest.spyOn(i, 'executeReconnect').mockResolvedValue(undefined);
+
+ // A drop 299s after the last attempt is still the same bad stretch: the budget keeps accruing.
+ jest.advanceTimersByTime(299_999);
+ i.scheduleReconnect('sess-uuid-1', createMockSession());
+ expect(state.attempts).toBe(5); // 4 -> 5, no reset
+
+ // ≥5 min since the last attempt means the session demonstrably stayed up — the budget
+ // restarts at 0 (the first schedule's 80s timer fires during this advance; irrelevant here).
+ jest.advanceTimersByTime(300_000);
+ i.scheduleReconnect('sess-uuid-1', createMockSession());
+ expect(state.attempts).toBe(1);
+
+ // ...so the backoff restarts at the base delay (~5s), not 2^4 × base (80s).
+ const callsBefore = exec.mock.calls.length;
+ jest.advanceTimersByTime(4_999);
+ expect(exec.mock.calls.length).toBe(callsBefore);
+ jest.advanceTimersByTime(1_001);
+ expect(exec.mock.calls.length).toBe(callsBefore + 1);
+ } finally {
+ jest.clearAllTimers();
+ jest.useRealTimers();
+ }
+ });
+
+ it('still wedges FAILED once an EXPLICIT cap is exhausted', () => {
+ jest.useFakeTimers();
+ try {
+ const i = internals();
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ const state = { attempts: 2, timer: null, maxAttempts: 3, baseDelay: 5000 };
+ i.reconnectStates.set('sess-uuid-1', state);
+
+ i.scheduleReconnect('sess-uuid-1', createMockSession()); // attempt 3/3 still schedules
+ expect(state.attempts).toBe(3);
+ expect(i.sessionErrors.has('sess-uuid-1')).toBe(false);
+
+ i.scheduleReconnect('sess-uuid-1', createMockSession()); // budget exhausted → terminal FAILED
+ expect(state.attempts).toBe(3); // no further attempt consumed
+ expect(i.sessionErrors.get('sess-uuid-1')).toMatch(/Reconnection failed after 3 attempts/);
+ expect(repository.update).toHaveBeenCalledWith('sess-uuid-1', { status: SessionStatus.FAILED });
+ } finally {
+ jest.clearAllTimers();
+ jest.useRealTimers();
+ }
+ });
+ });
+
describe('start() stale reconnect timer', () => {
it('cancels a pending reconnect timer before recreating the engine', async () => {
const i = service as unknown as {
@@ -993,6 +1107,181 @@ describe('SessionService', () => {
});
});
+ describe('liveness watchdog', () => {
+ type WatchdogInternals = {
+ engines: Map<string, unknown>;
+ reconnectStates: Map<
+ string,
+ { attempts: number; timer: NodeJS.Timeout | null; maxAttempts: number; baseDelay: number }
+ >;
+ livenessFailures: Map<string, number>;
+ watchdogTimer: NodeJS.Timeout | null;
+ scheduleReconnect: (id: string, session: Session) => void;
+ };
+ const internals = (): WatchdogInternals => service as unknown as WatchdogInternals;
+
+ // Auto-start is OFF in these tests — the watchdog must start regardless.
+ const originalFlag = process.env.AUTO_START_SESSIONS;
+ beforeEach(() => {
+ delete process.env.AUTO_START_SESSIONS;
+ });
+ afterEach(() => {
+ if (originalFlag === undefined) delete process.env.AUTO_START_SESSIONS;
+ else process.env.AUTO_START_SESSIONS = originalFlag;
+ });
+
+ const seedReadySession = (engine: unknown): void => {
+ internals().engines.set('sess-uuid-1', engine);
+ internals().reconnectStates.set('sess-uuid-1', {
+ attempts: 0,
+ timer: null,
+ maxAttempts: Number.POSITIVE_INFINITY,
+ baseDelay: 5000,
+ });
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ };
+
+ it('treats a READY engine failing the probe twice in a row as a disconnect (webhook + WS + DISCONNECTED + reconnect)', async () => {
+ jest.useFakeTimers();
+ try {
+ const engine = {
+ getStatus: jest.fn().mockReturnValue(EngineStatus.READY),
+ probeLiveness: jest.fn().mockResolvedValue(false),
+ };
+ seedReadySession(engine);
+ const scheduleSpy = jest.spyOn(internals(), 'scheduleReconnect');
+
+ await service.onApplicationBootstrap();
+
+ // Tick 1: the first failure stays below the 2-consecutive-failures threshold — nothing happens.
+ await jest.advanceTimersByTimeAsync(SESSION_WATCHDOG_INTERVAL_MS);
+ expect(scheduleSpy).not.toHaveBeenCalled();
+ expect(repository.update).not.toHaveBeenCalledWith('sess-uuid-1', {
+ status: SessionStatus.DISCONNECTED,
+ });
+
+ // Tick 2: the second CONSECUTIVE failure routes through the exact engine-disconnect path.
+ await jest.advanceTimersByTimeAsync(SESSION_WATCHDOG_INTERVAL_MS);
+ expect(scheduleSpy).toHaveBeenCalledWith('sess-uuid-1', expect.objectContaining({ id: 'sess-uuid-1' }));
+ expect(repository.update).toHaveBeenCalledWith('sess-uuid-1', { status: SessionStatus.DISCONNECTED });
+ expect(webhookService.dispatch).toHaveBeenCalledWith(
+ 'sess-uuid-1',
+ 'session.disconnected',
+ expect.objectContaining({ reason: 'liveness probe failed (watchdog)' }),
+ );
+ expect(eventsGateway.emitSessionDisconnected).toHaveBeenCalledWith('sess-uuid-1', {
+ reason: 'liveness probe failed (watchdog)',
+ });
+ } finally {
+ jest.clearAllTimers();
+ jest.useRealTimers();
+ }
+ });
+
+ it('resets the failure counter after a successful probe (no disconnect from non-consecutive failures)', async () => {
+ jest.useFakeTimers();
+ try {
+ const engine = {
+ getStatus: jest.fn().mockReturnValue(EngineStatus.READY),
+ // fail → succeed → fail: never two IN A ROW, so the session must survive all three ticks.
+ probeLiveness: jest
+ .fn()
+ .mockResolvedValueOnce(false)
+ .mockResolvedValueOnce(true)
+ .mockResolvedValueOnce(false),
+ };
+ seedReadySession(engine);
+ const scheduleSpy = jest.spyOn(internals(), 'scheduleReconnect');
+
+ await service.onApplicationBootstrap();
+ await jest.advanceTimersByTimeAsync(SESSION_WATCHDOG_INTERVAL_MS * 3);
+
+ expect(engine.probeLiveness).toHaveBeenCalledTimes(3);
+ expect(scheduleSpy).not.toHaveBeenCalled();
+ expect(webhookService.dispatch).not.toHaveBeenCalledWith(
+ 'sess-uuid-1',
+ 'session.disconnected',
+ expect.anything(),
+ );
+ } finally {
+ jest.clearAllTimers();
+ jest.useRealTimers();
+ }
+ });
+
+ it('skips engines that are not READY and engines that do not implement probeLiveness', async () => {
+ jest.useFakeTimers();
+ try {
+ const notReady = {
+ getStatus: jest.fn().mockReturnValue(EngineStatus.INITIALIZING),
+ probeLiveness: jest.fn().mockResolvedValue(false),
+ };
+ // READY but no probe method: the watchdog must feature-detect and leave it to engine events.
+ const noProbe = { getStatus: jest.fn().mockReturnValue(EngineStatus.READY) };
+ internals().engines.set('sess-not-ready', notReady);
+ internals().engines.set('sess-no-probe', noProbe);
+
+ await service.onApplicationBootstrap();
+ await jest.advanceTimersByTimeAsync(SESSION_WATCHDOG_INTERVAL_MS * 2);
+
+ expect(notReady.probeLiveness).not.toHaveBeenCalled();
+ expect(webhookService.dispatch).not.toHaveBeenCalledWith(
+ expect.anything(),
+ 'session.disconnected',
+ expect.anything(),
+ );
+ } finally {
+ jest.clearAllTimers();
+ jest.useRealTimers();
+ }
+ });
+
+ it('counts a hung probe (timeout) as a failure and clears it on the next successful probe', async () => {
+ jest.useFakeTimers();
+ try {
+ const engine = {
+ getStatus: jest.fn().mockReturnValue(EngineStatus.READY),
+ probeLiveness: jest
+ .fn()
+ .mockImplementationOnce(() => new Promise<boolean>(() => undefined)) // hangs → probe timeout
+ .mockResolvedValueOnce(true),
+ };
+ seedReadySession(engine);
+
+ await service.onApplicationBootstrap();
+ await jest.advanceTimersByTimeAsync(SESSION_WATCHDOG_INTERVAL_MS); // tick 1: probe hangs
+ expect(internals().livenessFailures.get('sess-uuid-1')).toBeUndefined(); // not counted yet
+ await jest.advanceTimersByTimeAsync(SESSION_WATCHDOG_PROBE_TIMEOUT_MS); // 15s → timeout failure
+ expect(internals().livenessFailures.get('sess-uuid-1')).toBe(1);
+
+ await jest.advanceTimersByTimeAsync(SESSION_WATCHDOG_INTERVAL_MS); // tick 2: success
+ expect(internals().livenessFailures.get('sess-uuid-1')).toBeUndefined(); // counter reset
+ } finally {
+ jest.clearAllTimers();
+ jest.useRealTimers();
+ }
+ });
+
+ it('clears the watchdog timer in onModuleDestroy (idempotent, no open handle)', async () => {
+ jest.useFakeTimers();
+ try {
+ await service.onApplicationBootstrap();
+ expect(internals().watchdogTimer).not.toBeNull();
+ expect(jest.getTimerCount()).toBe(1); // the interval itself
+
+ await service.onModuleDestroy();
+ expect(internals().watchdogTimer).toBeNull();
+ expect(jest.getTimerCount()).toBe(0);
+
+ await expect(service.onModuleDestroy()).resolves.toBeUndefined(); // safe to call twice
+ } finally {
+ jest.clearAllTimers();
+ jest.useRealTimers();
+ }
+ });
+ });
+
describe('engine onError', () => {
type EngineCallbacks = { onError?: (reason: string) => void; onReady?: (phone: string, name: string) => void };
@@ -2783,9 +3072,12 @@ describe('SessionService', () => {
describe('onApplicationBootstrap', () => {
const originalFlag = process.env.AUTO_START_SESSIONS;
- afterEach(() => {
+ afterEach(async () => {
if (originalFlag === undefined) delete process.env.AUTO_START_SESSIONS;
else process.env.AUTO_START_SESSIONS = originalFlag;
+ // Bootstrap always starts the (unref'd) liveness watchdog interval now — clear it so no
+ // timer outlives the test.
+ await service.onModuleDestroy();
});
it('does nothing when AUTO_START_SESSIONS is not enabled', async () => {
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index edba9a33e..7335adf90 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -54,6 +54,8 @@ interface ReconnectState {
timer: NodeJS.Timeout | null;
maxAttempts: number;
baseDelay: number;
+ /** When the last attempt was scheduled (epoch ms) — feeds the stability reset in scheduleReconnect. */
+ lastAttemptAt?: number;
}
// Reconnect-backoff bounds. An OPERATOR-supplied session.config feeds this math, so the values
@@ -63,6 +65,23 @@ const RECONNECT_BASE_DELAY_MIN_MS = 1000;
const RECONNECT_BASE_DELAY_MAX_MS = 300_000;
const RECONNECT_MAX_ATTEMPTS_CAP = 20;
const RECONNECT_DELAY_CAP_MS = 3_600_000;
+/**
+ * A reconnect-attempt budget covers one CONTINUOUS bad stretch: once this much time has passed
+ * since the last scheduled attempt the session demonstrably stayed up, so `attempts` resets to 0.
+ * Without it a long-lived session would slowly accrue attempts toward an explicit cap across
+ * unrelated transient drops and one day wedge FAILED for no current reason.
+ */
+const RECONNECT_STABILITY_RESET_MS = 300_000;
+/**
+ * Session liveness watchdog. The engine layer is event-driven, so an engine that dies WITHOUT
+ * firing an event (a silent Chromium crash) is never noticed: the row sits READY forever and never
+ * reconnects. Every INTERVAL the watchdog actively probes each READY engine (feature-detected
+ * `probeLiveness`, raced against TIMEOUT); MAX_FAILURES consecutive failures route the session
+ * through the exact engine-disconnect path.
+ */
+export const SESSION_WATCHDOG_INTERVAL_MS = 60_000;
+export const SESSION_WATCHDOG_PROBE_TIMEOUT_MS = 15_000;
+export const SESSION_WATCHDOG_MAX_FAILURES = 2;
/**
* Delay before retrying an ack UPDATE that matched 0 rows. A fast delivered/read ack can arrive before
* the send's 2nd save (which writes waMessageId) has committed, so the first UPDATE finds no row. One
@@ -72,8 +91,10 @@ export const ACK_RECONCILE_DELAY_MS = 750;
const clampNumber = (n: number, min: number, max: number): number => Math.min(Math.max(n, min), max);
-/** Coerce + clamp the untyped session.config reconnect knobs to finite, bounded values. Defaults
- * (5000ms / 5 attempts) are preserved; a legitimate `maxReconnectAttempts: 0` (disable) is kept. */
+/** Coerce + clamp the untyped session.config reconnect knobs to finite, bounded values. Defaults are
+ * a 5000ms base delay and UNLIMITED attempts (`Infinity`): a long-lived session must keep retrying
+ * (the backoff parks at the 1h cap) instead of dying permanently after ~2.5 minutes. An EXPLICIT
+ * `maxReconnectAttempts: 0` (disable) is preserved, and 1..20 clamps as before. */
export function resolveReconnectConfig(
config: { maxReconnectAttempts?: unknown; reconnectBaseDelay?: unknown } | null,
): { maxAttempts: number; baseDelay: number } {
@@ -84,9 +105,9 @@ export function resolveReconnectConfig(
RECONNECT_BASE_DELAY_MAX_MS,
);
const attemptsRaw = Number(config?.maxReconnectAttempts);
- const maxAttempts = Math.floor(
- clampNumber(Number.isFinite(attemptsRaw) ? attemptsRaw : 5, 0, RECONNECT_MAX_ATTEMPTS_CAP),
- );
+ const maxAttempts = Number.isFinite(attemptsRaw)
+ ? Math.floor(clampNumber(attemptsRaw, 0, RECONNECT_MAX_ATTEMPTS_CAP))
+ : Number.POSITIVE_INFINITY;
return { maxAttempts, baseDelay };
}
@@ -154,6 +175,14 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
// Reconnection state per session
private reconnectStates: Map<string, ReconnectState> = new Map();
+ // Consecutive liveness-probe failures per session (watchdog). Reset on a successful probe, on a
+ // non-READY tick, on onReady, and when the threshold routes the session to the disconnect path.
+ private readonly livenessFailures = new Map<string, number>();
+
+ // The single watchdog interval handle. Unref'd so it never keeps the process alive on its own;
+ // cleared (and nulled) in onModuleDestroy, so teardown stays idempotent.
+ private watchdogTimer: NodeJS.Timeout | null = null;
+
// Last session.status value broadcast per session. Some engines signal one transition via BOTH
// onStateChanged and a dedicated callback (onQRCode/onDisconnected), so this guards both the WS emit
// and the webhook POST against firing the same status twice. Cleared on delete().
@@ -225,6 +254,10 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
}
async onApplicationBootstrap(): Promise<void> {
+ // Start the liveness watchdog FIRST: it must run even when auto-start is disabled (sessions can
+ // be started via the API at any time), so it can't sit behind the auto-start early-return below.
+ this.startWatchdog();
+
if (!resolveFeatureFlags(this.configService).autoStartSessions) return;
const sessions = await this.sessionRepository.find({
@@ -261,6 +294,14 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
}
async onModuleDestroy(): Promise<void> {
+ // Stop the watchdog FIRST (before any teardown below can hang): no new probe/disconnect handling
+ // may start mid-shutdown. Nulling the handle keeps a second onModuleDestroy call safe.
+ if (this.watchdogTimer) {
+ clearInterval(this.watchdogTimer);
+ this.watchdogTimer = null;
+ }
+ this.livenessFailures.clear();
+
// Stop reconnect timers FIRST so nothing reschedules mid-teardown, and so this always runs even
// if an engine.destroy() below hangs or throws.
for (const [, state] of this.reconnectStates) {
@@ -743,6 +784,8 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
if (reconnectState) {
reconnectState.attempts = 0;
}
+ // A fresh READY stretch starts the watchdog's failure budget clean too.
+ this.livenessFailures.delete(id);
this.sessionErrors.delete(id);
void this.sessionRepository
@@ -1117,29 +1160,10 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
},
onDisconnected: (reason: string): void => {
if (!this.isLiveEngine(id, engine)) return;
- this.logger.warn(`Session disconnected: ${reason}`, {
- sessionId: id,
- reason,
- action: 'disconnected',
- });
-
- void this.webhookService.dispatch(id, 'session.disconnected', { sessionId: id, reason });
- this.eventsGateway.emitSessionDisconnected(id, { reason });
-
- // Execute hook for disconnected event
- void this.hookManager.execute(
- 'session:disconnected',
- { reason },
- {
- sessionId: id,
- source: 'Engine',
- },
- );
-
- void this.updateStatus(id, SessionStatus.DISCONNECTED);
-
- // Attempt to reconnect
- this.scheduleReconnect(id, session);
+ // Shared with the liveness watchdog (see handleEngineDisconnected). The handler re-reads the
+ // session row itself — this closure's `session` snapshot can be stale by the time a
+ // disconnect lands — so the reconnect always re-initializes from the current row.
+ void this.handleEngineDisconnected(id, reason);
},
onStateChanged: (engineState: EngineStatus): void => {
if (!this.isLiveEngine(id, engine)) return;
@@ -1342,6 +1366,142 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
void this.webhookService.dispatch(id, 'message.edited', editedPayload);
}
+ /**
+ * Shared disconnect handling for BOTH the engine's onDisconnected callback and the liveness
+ * watchdog: notify consumers (webhook + WS + hook), persist DISCONNECTED, then schedule a
+ * reconnect. The session row is re-read here rather than trusting a caller-held snapshot — the
+ * watchdog detects death long after the last state change, and even the callback's closure
+ * snapshot can be stale — so the reconnect always re-initializes from the current row. Never
+ * throws: a DB hiccup must not turn a disconnect into an unhandled rejection.
+ */
+ private async handleEngineDisconnected(id: string, reason: string): Promise<void> {
+ this.logger.warn(`Session disconnected: ${reason}`, {
+ sessionId: id,
+ reason,
+ action: 'disconnected',
+ });
+
+ void this.webhookService.dispatch(id, 'session.disconnected', { sessionId: id, reason });
+ this.eventsGateway.emitSessionDisconnected(id, { reason });
+
+ // Execute hook for disconnected event
+ void this.hookManager.execute(
+ 'session:disconnected',
+ { reason },
+ {
+ sessionId: id,
+ source: 'Engine',
+ },
+ );
+
+ void this.updateStatus(id, SessionStatus.DISCONNECTED);
+
+ let session: Session | null;
+ try {
+ session = await this.sessionRepository.findOne({ where: { id } });
+ } catch (err) {
+ this.logger.error('Failed to reload the session for reconnect scheduling', String(err), {
+ sessionId: id,
+ action: 'reconnect_schedule_error',
+ });
+ return;
+ }
+ // A session deleted just before this ran has nothing left to reconnect; skip it.
+ if (!session) return;
+
+ // Attempt to reconnect
+ this.scheduleReconnect(id, session);
+ }
+
+ /** Start the liveness watchdog (idempotent). One unref'd interval probes every registered engine. */
+ private startWatchdog(): void {
+ if (this.watchdogTimer) return;
+ this.watchdogTimer = setInterval(() => {
+ // allSettled inside the tick keeps a failing session from ever throwing into the timer.
+ void this.runWatchdogTick();
+ }, SESSION_WATCHDOG_INTERVAL_MS);
+ // The watchdog must never keep the process alive on its own.
+ this.watchdogTimer.unref();
+ }
+
+ /** Probe all live engines in parallel; a slow/failed probe must not delay or abort the others. */
+ private async runWatchdogTick(): Promise<void> {
+ // Mid-shutdown the disconnect path would schedule a reconnect racing onModuleDestroy's teardown
+ // (same guard as scheduleReconnect) — leave the sessions to the drain instead.
+ if (this.shutdownService?.isShuttingDown()) {
+ return;
+ }
+ await Promise.allSettled([...this.engines].map(([id, engine]) => this.probeSessionLiveness(id, engine)));
+ }
+
+ /**
+ * Actively probe one engine. Only READY sessions are expected to answer (anything else is owned by
+ * the QR/reconnect flows); engines without `probeLiveness` keep relying on engine events alone.
+ * MAX_FAILURES consecutive failures treat the session exactly like an engine-reported disconnect.
+ */
+ private async probeSessionLiveness(id: string, engine: IWhatsAppEngine): Promise<void> {
+ if (engine.getStatus() !== EngineStatus.READY) {
+ // Not expected to answer right now — and any accrued failures belong to a previous READY
+ // stretch, so the next one starts clean.
+ this.livenessFailures.delete(id);
+ return;
+ }
+ // Feature-detect: an engine whose transport already self-detects death may skip the probe.
+ if (typeof engine.probeLiveness !== 'function') {
+ return;
+ }
+
+ // A wedged connection can hang the probe itself, so race it against a timeout; a timeout or a
+ // probe error both count as "not proven alive".
+ let alive: boolean;
+ let probeTimer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ alive = await Promise.race([
+ engine.probeLiveness(),
+ new Promise<never>((_, reject) => {
+ probeTimer = setTimeout(
+ () => reject(new Error('liveness probe timed out')),
+ SESSION_WATCHDOG_PROBE_TIMEOUT_MS,
+ );
+ }),
+ ]);
+ } catch {
+ alive = false;
+ } finally {
+ if (probeTimer) clearTimeout(probeTimer);
+ }
+
+ // The session may have been stopped/restarted (engine superseded) while the probe was in flight;
+ // a stale result must not touch it (mirrors the isLiveEngine gate on engine callbacks).
+ if (!this.isLiveEngine(id, engine)) {
+ return;
+ }
+
+ if (alive) {
+ this.livenessFailures.delete(id);
+ return;
+ }
+
+ const failures = (this.livenessFailures.get(id) ?? 0) + 1;
+ if (failures < SESSION_WATCHDOG_MAX_FAILURES) {
+ this.livenessFailures.set(id, failures);
+ this.logger.warn('Liveness probe failed; will treat the session as dead after repeated failures', {
+ sessionId: id,
+ failures,
+ action: 'watchdog_probe_failed',
+ });
+ return;
+ }
+
+ this.livenessFailures.delete(id);
+ this.logger.warn('Liveness probe failed repeatedly; handling the session as disconnected', {
+ sessionId: id,
+ failures,
+ action: 'watchdog_disconnect',
+ });
+ await this.handleEngineDisconnected(id, 'liveness probe failed (watchdog)');
+ }
+
private scheduleReconnect(id: string, session: Session): void {
// Don't launch a fresh engine (Chromium) mid-shutdown: a disconnect during the drain window would
// otherwise schedule a reconnect that races onModuleDestroy's teardown and could orphan a browser.
@@ -1355,6 +1515,14 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
const state = this.reconnectStates.get(id);
if (!state) return;
+ // Stability reset: the attempt budget covers one CONTINUOUS bad stretch. When the session stayed
+ // up ≥5 min since the last scheduled attempt it demonstrably recovered, so the next drop
+ // restarts the budget — unrelated transient drops must not accrue toward an explicit cap over
+ // the session's lifetime.
+ if (state.lastAttemptAt !== undefined && Date.now() - state.lastAttemptAt >= RECONNECT_STABILITY_RESET_MS) {
+ state.attempts = 0;
+ }
+
if (state.attempts >= state.maxAttempts) {
this.logger.error(`Max reconnect attempts reached for session: ${session.name}`, undefined, {
sessionId: id,
@@ -1376,15 +1544,18 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
}
// Exponential backoff: baseDelay * 2^attempts (with jitter), clamped finite + within
- // setTimeout's safe range so the timer can't overflow and fire immediately.
+ // setTimeout's safe range so the timer can't overflow and fire immediately. With the default
+ // unlimited budget the delay parks at RECONNECT_DELAY_CAP_MS once the exponent outgrows it.
const delay = clampReconnectDelay(
state.baseDelay * Math.pow(2, state.attempts) + Math.random() * 1000,
state.baseDelay,
);
state.attempts++;
+ state.lastAttemptAt = Date.now();
+ const maxAttemptsLabel = Number.isFinite(state.maxAttempts) ? String(state.maxAttempts) : '∞';
this.logger.log(
- `Scheduling reconnect attempt ${state.attempts}/${state.maxAttempts} in ${Math.round(delay / 1000)}s`,
+ `Scheduling reconnect attempt ${state.attempts}/${maxAttemptsLabel} in ${Math.round(delay / 1000)}s`,
{
sessionId: id,
attempt: state.attempts,