Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): report an engine-internal reconnect loop
Yudhi Armyndharis9053e998e31e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d26abc2d5..f46c3b6cc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Fixed++- A Baileys session retrying a dropped connection now reports the loop: `lastError` on+ `GET /sessions/{sessionId}` says which attempt it is on and how long it has been down, the+ `session.reconnect_loop` webhook fires every fifth attempt, and the reconnect metrics move. The+ engine retries internally and never reported a disconnect, so an operator had nothing to look at+ while a session sat at `initializing` for hours+ ([#1546](https://github.com/rmyndharis/OpenWA/issues/1546)). Thanks @OdaiAhmed99 for the report.+- The dashboard session card keeps showing the phone number, session id and last-active time while a+ linked session reconnects, instead of the pairing placeholder that read as an unlinked account+ ([#1546](https://github.com/rmyndharis/OpenWA/issues/1546)). Thanks @OdaiAhmed99 for the report.+## [0.23.4] - 2026-09-05### Addeddiff --git a/dashboard/src/pages/Sessions.tsx b/dashboard/src/pages/Sessions.tsxindex 65177ba9f..30733730f 100644--- a/dashboard/src/pages/Sessions.tsx+++ b/dashboard/src/pages/Sessions.tsx@@ -26,6 +26,7 @@ import {import { queryKeys } from '../hooks/queries';import { useDocumentTitle } from '../hooks/useDocumentTitle';import {+ awaitsPairing,canForceKillSession,canUnlinkSession,classifyUnlinkError,@@ -1038,7 +1039,7 @@ export function Sessions() {<span className={`status-pill ${session.status}`}>{formatStatus(session.status)}</span></div>- {session.status === 'initializing' || session.status === 'qr_ready' ? (+ {awaitsPairing(session) ? (<div className="qr-placeholder"><QrCode size={80} className="qr-icon" /><p>{session.status === 'qr_ready' ? t('sessions.qr.scanToConnect') : t('sessions.qr.preparing')}</p>diff --git a/dashboard/src/utils/sessionActions.test.ts b/dashboard/src/utils/sessionActions.test.tsindex e0cd48494..c958d8376 100644--- a/dashboard/src/utils/sessionActions.test.ts+++ b/dashboard/src/utils/sessionActions.test.ts@@ -1,6 +1,7 @@import { test } from 'node:test';import assert from 'node:assert/strict';import {+ awaitsPairing,canForceKillSession,canUnlinkSession,classifyUnlinkError,@@ -191,3 +192,28 @@ test('classifyUnlinkError: everything else is generic', () => {assert.equal(classifyUnlinkError(new Error('network down')), 'generic'); // no status at allassert.equal(classifyUnlinkError(undefined), 'generic');});++// The card body: a session that has never been paired gets the QR placeholder, a linked one that is+// merely reconnecting keeps its identity rows. `initializing` is the status that means both.+test('awaitsPairing: qr_ready always awaits pairing, phone or not', () => {+ assert.equal(awaitsPairing(makeSession({ status: 'qr_ready', phone: null })), true);+ assert.equal(awaitsPairing(makeSession({ status: 'qr_ready', phone: '+155512345' })), true);+});++test('awaitsPairing: initializing without a phone is a first pairing', () => {+ assert.equal(awaitsPairing(makeSession({ status: 'initializing', phone: null })), true);+ assert.equal(awaitsPairing(makeSession({ status: 'initializing', phone: '' })), true);+});++test('awaitsPairing: initializing WITH a phone is a linked session reconnecting', () => {+ // The regression this guards: a Baileys transient close parks a still-linked session at+ // INITIALIZING for the whole backoff, and the card used to paint it as an unpaired account.+ assert.equal(awaitsPairing(makeSession({ status: 'initializing', phone: '+155512345' })), false);+});++test('awaitsPairing: no other status ever takes the placeholder', () => {+ for (const status of ['created', 'authenticating', 'ready', 'disconnected', 'action_required', 'failed'] as const) {+ assert.equal(awaitsPairing(makeSession({ status, phone: null })), false, status);+ assert.equal(awaitsPairing(makeSession({ status, phone: '+155512345' })), false, status);+ }+});diff --git a/dashboard/src/utils/sessionActions.ts b/dashboard/src/utils/sessionActions.tsindex f1834bde1..a8b5d9b44 100644--- a/dashboard/src/utils/sessionActions.ts+++ b/dashboard/src/utils/sessionActions.ts@@ -19,6 +19,23 @@ export function isSessionStarted(session: Pick<Session, 'status' | 'engineLoadedreturn session.engineLoaded ?? STARTED_STATUSES_FALLBACK.has(session.status);}+// Which body the session card gets: the pairing placeholder, or the session's identity rows.+//+// `qr_ready` always means a code is on offer, so it always gets the placeholder. `initializing` is the+// ambiguous one: it covers a never-linked session walking up to its first QR, and it also covers a+// LINKED session inside the engine's own reconnect backoff (Baileys drops to INITIALIZING on every+// transient close). The second is still paired to a number, and showing it "Preparing QR code" reads+// as an account that has been unlinked.+//+// `phone` is the discriminator because it tracks the link and nothing else: it is written by a+// successful ready and cleared exactly when the link dies, on a WhatsApp-side unlink and on logout().+// `connectedAt` is never cleared, so it would keep claiming "linked" for a session unlinked an hour+// ago, and `engineLoaded` is dropped to undefined by the Sessions page on every websocket status push,+// which is the very transition that lands a card here.+export function awaitsPairing(session: Pick<Session, 'status' | 'phone'>): boolean {+ return session.status === 'qr_ready' || (session.status === 'initializing' && !session.phone);+}+// Unlink calls POST /sessions/:id/logout, which needs a live engine to send the unlink through — the// same precondition as Stop, and what the API's own 400 tells the operator.export function canUnlinkSession(session: Pick<Session, 'status' | 'engineLoaded'>, canWrite: boolean): boolean {diff --git a/openapi.json b/openapi.jsonindex a78e1ff3f..7121dbb63 100644--- a/openapi.json+++ b/openapi.json@@ -10199,7 +10199,7 @@},"lastError": {"type": "string",- "description": "Human-readable reason carried while the status is FAILED (a terminal engine failure) or ACTION_REQUIRED (the engine is running but something needs a human). Cleared on any other status.",+ "description": "Human-readable reason carried while the status is FAILED (a terminal engine failure), ACTION_REQUIRED (the engine is running but something needs a human), or INITIALIZING while the engine is retrying a dropped connection on its own. Cleared on any other status.","example": "Failed to launch the browser process: spawn /usr/bin/chromium ENOENT","nullable": true},diff --git a/src/engine/adapters/baileys-lifecycle.ts b/src/engine/adapters/baileys-lifecycle.tsindex ccba3d33d..d799e196e 100644--- a/src/engine/adapters/baileys-lifecycle.ts+++ b/src/engine/adapters/baileys-lifecycle.ts@@ -96,6 +96,8 @@ export interface BaileysLifecycleHost {getOnReady(): EngineEventCallbacks['onReady'];/** The currently-registered onDisconnected callback, if any (assigned at initialize()). */getOnDisconnected(): EngineEventCallbacks['onDisconnected'];+ /** The currently-registered onReconnecting callback, if any (assigned at initialize()). */+ getOnReconnecting(): EngineEventCallbacks['onReconnecting'];/** The currently-registered onError callback, if any (assigned at initialize()). */getOnError(): EngineEventCallbacks['onError'];/** The currently-registered onStateChanged callback, if any (assigned at initialize()). */@@ -461,7 +463,11 @@ export class BaileysLifecycle {// 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.- this.host.logger.log('Baileys connection dropped; reconnecting', { statusCode });+ this.host.logger.log('Baileys connection dropped; reconnecting', {+ sessionId: this.host.config.sessionId,+ statusCode,+ action: 'baileys_connection_dropped',+ });// 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@@ -553,6 +559,12 @@ export class BaileysLifecycle {}this.reconnectAttempts += 1;const delay = Math.min(60_000, 1_000 * 2 ** (this.reconnectAttempts - 1)) + Math.floor(Math.random() * 1000);+ // The consumer is never told about this drop through onDisconnected (deliberately: the session is+ // still linked), and the status it does see is INITIALIZING for the whole episode. So this is the+ // only signal that a retry loop is running. Fired here rather than in the close handler because+ // this is the one place every scheduled attempt passes through, including the reschedule from the+ // failed-attempt catch below, and it is already past the duplicate-close guard above.+ this.host.getOnReconnecting()?.(this.reconnectAttempts, delay);this.reconnectTimer = setTimeout(() => {this.reconnectTimer = undefined;if (this.intentionalClose) {diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 894f56ffb..7c1305ffd 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -566,6 +566,54 @@ describe('BaileysAdapter lifecycle & status', () => {}});+ it('on a recoverable close: reports the scheduled attempt through onReconnecting', async () => {+ // The only signal a consumer gets for an engine-internal retry loop: onDisconnected is+ // deliberately silent here and the status sits at INITIALIZING for the whole episode, so without+ // this callback an operator cannot tell a one-second blip from an hour-long outage.+ const onReconnecting = jest.fn();+ const onDisconnected = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize(noopCallbacks({ onReconnecting, onDisconnected }));++ jest.useFakeTimers({ doNotFake: ['setImmediate'] });+ try {+ fakeSock.fire('connection.update', {+ connection: 'close',+ lastDisconnect: { error: { output: { statusCode: 515 } } },+ });+ expect(onDisconnected).not.toHaveBeenCalled();+ expect(onReconnecting).toHaveBeenCalledTimes(1);+ const [attempt, nextDelayMs] = onReconnecting.mock.calls[0] as [number, number];+ expect(attempt).toBe(1);+ // First attempt: the 1 s base plus up to 1 s of jitter.+ expect(nextDelayMs).toBeGreaterThanOrEqual(1_000);+ expect(nextDelayMs).toBeLessThan(2_000);+ } finally {+ jest.useRealTimers();+ }+ });++ it('a duplicate close while a reconnect is already pending does not inflate the attempt count', async () => {+ // Baileys can emit more than one close per drop. The attempt number rides `lastError` and the+ // reconnect_loop alert cadence, so double-counting would report a loop that is not happening.+ const onReconnecting = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize(noopCallbacks({ onReconnecting }));++ jest.useFakeTimers({ doNotFake: ['setImmediate'] });+ try {+ const close = {+ connection: 'close',+ lastDisconnect: { error: { output: { statusCode: 515 } } },+ };+ fakeSock.fire('connection.update', close);+ fakeSock.fire('connection.update', close);+ expect(onReconnecting).toHaveBeenCalledTimes(1);+ } finally {+ jest.useRealTimers();+ }+ });+it('disconnect() ends the socket and does not reconnect', async () => {const adapter = newAdapter();await adapter.initialize(noopCallbacks({}));diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex dc6083374..6daf60dc6 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -191,6 +191,7 @@ export class BaileysAdapter implements IWhatsAppEngine {getOnQRCode: () => this.callbacks.onQRCode,getOnReady: () => this.callbacks.onReady,getOnDisconnected: () => this.callbacks.onDisconnected,+ getOnReconnecting: () => this.callbacks.onReconnecting,getOnError: () => this.callbacks.onError,getOnStateChanged: () => this.callbacks.onStateChanged,getOnCredentialTeardownStarted: () => this.callbacks.onCredentialTeardownStarted,diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex 6777d2a9e..281178577 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -758,6 +758,23 @@ export interface EngineEventCallbacks {*/onHistoryMessages?: (messages: IncomingMessage[]) => void;onDisconnected?: (reason: string) => void;+ /**+ * Fired each time the engine schedules an INTERNAL reconnect attempt: a drop it retries on its own+ * and deliberately does NOT report through `onDisconnected`, because the session is still linked and+ * the credentials are still good. Purely informational, so a consumer must not tear anything down on+ * it; the engine keeps owning the retry.+ *+ * `attempt` is the 1-based number of the attempt being scheduled, and it resets once the connection+ * is back (or after a long enough healthy stretch), so attempt 1 always opens a fresh episode.+ * `nextDelayMs` is how long the engine waits before making it. Together they are what a consumer+ * needs to tell a one-second blip from a session that has been down for an hour, which the status+ * alone cannot: the engine reports INITIALIZING for the whole episode, exactly as it does for a+ * session that has never been paired.+ *+ * Optional: an engine that hands every drop to its consumer instead of retrying internally+ * (whatsapp-web.js does) simply never invokes this, because that consumer already has the drop.+ */+ onReconnecting?: (attempt: number, nextDelayMs: number) => void;onStateChanged?: (state: EngineStatus) => void;/*** Fired when the engine needs an operator action to keep the session healthy — currently only thediff --git a/src/modules/session/dto/session-response.dto.ts b/src/modules/session/dto/session-response.dto.tsindex 83138fa39..0683381b7 100644--- a/src/modules/session/dto/session-response.dto.ts+++ b/src/modules/session/dto/session-response.dto.ts@@ -65,8 +65,9 @@ export class SessionResponseDto {@ApiPropertyOptional({type: String,description:- 'Human-readable reason carried while the status is FAILED (a terminal engine failure) or ' +- 'ACTION_REQUIRED (the engine is running but something needs a human). Cleared on any other status.',+ 'Human-readable reason carried while the status is FAILED (a terminal engine failure), ' ++ 'ACTION_REQUIRED (the engine is running but something needs a human), or INITIALIZING while the ' ++ 'engine is retrying a dropped connection on its own. Cleared on any other status.',example: 'Failed to launch the browser process: spawn /usr/bin/chromium ENOENT',nullable: true,})diff --git a/src/modules/session/session-engine-event-wiring.ts b/src/modules/session/session-engine-event-wiring.tsindex 366b622ac..6f1cd7234 100644--- a/src/modules/session/session-engine-event-wiring.ts+++ b/src/modules/session/session-engine-event-wiring.ts@@ -1,4 +1,9 @@import { SessionStatus } from './entities/session.entity';+import { RECONNECT_LOOP_ALERT_INTERVAL_ATTEMPTS } from './reconnect-policy';+import {+ incrementSessionReconnectAttempts,+ incrementSessionReconnectLoopAlerts,+} from '../../common/metrics/session-reconnect-metrics';import { MessageProjector } from './message-projector.service';import { SessionErrorStore } from './session-error-store.service';import { SessionRestrictionStore } from './session-restriction-store.service';@@ -118,6 +123,11 @@ export class SessionEngineEventWiring {// presence is the relink signal used below; its value gates onReady's account-binding check.const previouslyLinked = Boolean(previousPhone);let relinkWarned = false;+ // Start of the current engine-internal reconnect episode (epoch ms), stamped on attempt 1.+ // Closure state rather than a Map: it is scoped to this engine instance, which is exactly the+ // lifetime of an episode. A service-level reconnect builds a new engine and a new callback table,+ // so nothing has to be cleaned up and a previous episode's clock can never be inherited.+ let reconnectingSince = 0;/*** Persist an engine-driven status, but only while this node still owns the session.*@@ -262,6 +272,45 @@ export class SessionEngineEventWiring {// Opt-in auto-reject runs AFTER the dispatch so a reject failure can never eat the event.void host.leafEvents.maybeAutoRejectCall(id, engine, event.callId);},+ onReconnecting: (attempt: number, nextDelayMs: number): void => {+ if (!host.isLiveEngine(id, engine)) return;+ // Count it whichever layer scheduled it: the counter's published meaning is "reconnect+ // attempts scheduled across all sessions", and an engine that retries internally was simply+ // never counted, so the series read 0 on Baileys however long a session looped.+ incrementSessionReconnectAttempts();+ if (attempt === 1) reconnectingSince = Date.now();++ // Below the loop threshold this is a blip, not an episode: the 515 restart WhatsApp asks for+ // right after a successful pairing is one attempt, and so is any drop that comes straight+ // back. Reporting those would put "reconnecting" on a session that is linking normally.+ if (attempt % RECONNECT_LOOP_ALERT_INTERVAL_ATTEMPTS !== 0) return;++ const downForSeconds = Math.round((Date.now() - reconnectingSince) / 1000);+ const downFor = downForSeconds >= 120 ? `${Math.round(downForSeconds / 60)}m` : `${downForSeconds}s`;+ // The engine holds the session at INITIALIZING for the whole episode, which is the same thing+ // it reports for a session waiting to be paired. Record why, so `lastError` says so on+ // GET /sessions/:id, the only durable operator surface this path reaches.+ host.sessionErrors.set(+ id,+ `Reconnecting after a dropped connection (attempt ${attempt}, down for ${downFor}).`,+ );+ // Same cadence, same log shape and the same already-documented webhook the service-level+ // reconnect path emits, so an operator watching for a stuck session does not have to know+ // which layer happens to be doing the retrying.+ this.logger.warn(`Session is reconnect-looping: attempt ${attempt} scheduled`, {+ sessionId: id,+ attempts: attempt,+ nextDelayMs,+ downForSeconds,+ action: 'reconnect_loop',+ });+ incrementSessionReconnectLoopAlerts();+ void host.webhookService.dispatch(id, 'session.reconnect_loop', {+ sessionId: id,+ attempts: attempt,+ nextDelayMs,+ });+ },onDisconnected: (reason: string): void => {if (!host.isLiveEngine(id, engine)) return;// Shared with the liveness watchdog (see handleEngineDisconnected). Pass the captureddiff --git a/src/modules/session/session-error-store.service.ts b/src/modules/session/session-error-store.service.tsindex 38ac928bb..0fe3faa04 100644--- a/src/modules/session/session-error-store.service.ts+++ b/src/modules/session/session-error-store.service.ts@@ -36,14 +36,21 @@ export class SessionErrorStore {}/**- * Populate the transient `lastError` field. A FAILED session always carries its failure reason, and- * an ACTION_REQUIRED session carries what the operator must do (e.g. the whatsapp-web.js- * onboarding-modal fallback, #982); any other status clears it, so a recovered session never shows- * a stale reason even while the entry is still held.+ * Populate the transient `lastError` field. A FAILED session always carries its failure reason, an+ * ACTION_REQUIRED session carries what the operator must do (e.g. the whatsapp-web.js+ * onboarding-modal fallback, #982), and an INITIALIZING one carries the engine-internal reconnect+ * episode it is stuck in: that status is otherwise identical to a session that has never been+ * paired, and an engine that retries forever never reaches FAILED, so there is no later status at+ * which the reason would surface. INITIALIZING is safe to include because the lifecycle clears this+ * map immediately before every fresh engine start and again on ready, so an ordinary startup has+ * nothing to show. Any other status clears it, so a recovered session never shows a stale reason+ * even while the entry is still held.*/attachTo(session: Session): Session {session.lastError =- session.status === SessionStatus.FAILED || session.status === SessionStatus.ACTION_REQUIRED+ session.status === SessionStatus.FAILED ||+ session.status === SessionStatus.ACTION_REQUIRED ||+ session.status === SessionStatus.INITIALIZING? this.errors.get(session.id): undefined;return session;diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex bdd36e410..8d0f04f5a 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -2451,6 +2451,69 @@ describe('SessionService', () => {});});+ // An engine that retries a dropped connection ON ITS OWN never reaches the service-level reconnect+ // loop, so before this wiring a Baileys session could sit at INITIALIZING for hours with no+ // webhook, no lastError and a flat reconnect counter. #1546 was reported with an empty logs box for+ // exactly that reason.+ describe('engine-internal reconnect reporting', () => {+ const startAndCapture = async (): Promise<EngineEventCallbacks> => {+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ await service.start('sess-uuid-1');+ const calls = mockEngine.initialize.mock.calls as [EngineEventCallbacks][];+ return calls[0][0];+ };++ const loopDispatches = (): unknown[][] =>+ ((webhookService.dispatch as jest.Mock).mock.calls as unknown[][]).filter(c => c[1] === 'session.reconnect_loop');++ it('stays quiet below the alert threshold: a blip is not an outage', async () => {+ const callbacks = await startAndCapture();+ (webhookService.dispatch as jest.Mock).mockClear();++ for (let attempt = 1; attempt <= 4; attempt++) callbacks.onReconnecting?.(attempt, 1_000);++ expect(loopDispatches()).toHaveLength(0);+ const sessionErrors = (service as unknown as { sessionErrors: Map<string, string> }).sessionErrors;+ expect(sessionErrors.get('sess-uuid-1')).toBeUndefined();+ });++ it('alerts on every fifth attempt, with the attempt number and the next delay', async () => {+ const callbacks = await startAndCapture();+ (webhookService.dispatch as jest.Mock).mockClear();++ for (let attempt = 1; attempt <= 10; attempt++) callbacks.onReconnecting?.(attempt, 60_000);++ const dispatches = loopDispatches();+ expect(dispatches).toHaveLength(2);+ expect(dispatches[0][2]).toEqual({ sessionId: 'sess-uuid-1', attempts: 5, nextDelayMs: 60_000 });+ expect(dispatches[1][2]).toEqual({ sessionId: 'sess-uuid-1', attempts: 10, nextDelayMs: 60_000 });+ });++ it('records the loop on lastError, so GET /sessions/:id says why it is stuck at initializing', async () => {+ const callbacks = await startAndCapture();++ for (let attempt = 1; attempt <= 5; attempt++) callbacks.onReconnecting?.(attempt, 60_000);++ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession({ status: SessionStatus.INITIALIZING }));+ const result = await service.findOne('sess-uuid-1');++ expect(result.lastError).toMatch(/^Reconnecting after a dropped connection \(attempt 5, down for /);+ });++ it('never fires onDisconnected: the session is still linked and the engine owns the retry', async () => {+ const callbacks = await startAndCapture();+ (repository.update as jest.Mock).mockClear();++ for (let attempt = 1; attempt <= 5; attempt++) callbacks.onReconnecting?.(attempt, 60_000);++ const statusWrites = ((repository.update as jest.Mock).mock.calls as unknown[][]).filter(+ c => (c[1] as { status?: SessionStatus }).status === SessionStatus.DISCONNECTED,+ );+ expect(statusWrites).toHaveLength(0);+ });+ });+// A restriction is WhatsApp judging the account, not a fault on our side, so it has its own// channel: a webhook, a field on the session, and a gauge — never a status change. Both engines// repeat themselves (whatsapp-web.js on every reconnect attempt, the Baileys probe on every