Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(baileys): count every close at QR_READY except the QR expiry

Yudhi Armyndharis9d118e254fce
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d93ea542c..cd052bc24 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -22,7 +22,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- The Baileys live path drops a message made only of sender-key distributions or message-history notices instead of delivering it as a bodyless `unknown` `message.received`; other messages it cannot type still arrive as `unknown` ([#1568](https://github.com/rmyndharis/OpenWA/issues/1568)). Thanks @berodcdev for the report.
-- A Baileys reconnect loop is observable for a linked session, not while waiting for a QR scan: `lastError` on the session, a `session.reconnect_loop` webhook every fifth attempt, and reconnect metrics; a connection attempt refused at the WebSocket upgrade is closed and retried instead of leaving the session at `initializing` ([#1546](https://github.com/rmyndharis/OpenWA/issues/1546)). Thanks @OdaiAhmed99 for the report.
+- A Baileys reconnect loop is observable through `lastError` on the session, a `session.reconnect_loop` webhook every fifth attempt and reconnect metrics; a QR left unscanned is not reported as one ([#1546](https://github.com/rmyndharis/OpenWA/issues/1546)). Thanks @OdaiAhmed99 for the report.
+- A Baileys connection attempt refused at the WebSocket upgrade is closed and retried instead of leaving the session at `initializing` ([#1546](https://github.com/rmyndharis/OpenWA/issues/1546)). Thanks @OdaiAhmed99 for the report.
- The dashboard session card keeps the phone number, session id and last-active time while a linked session reconnects, instead of the pairing placeholder ([#1546](https://github.com/rmyndharis/OpenWA/issues/1546)). Thanks @OdaiAhmed99 for the report.
- The Sessions page reports a dead live-event feed, and both it and the Chats page re-read their data once the feed recovers, including a feed that never connected.
- A Baileys media download aborted at `MEDIA_DOWNLOAD_MAX_BYTES` reports the bytes received as `sizeBytes`, and a timed-out one its declared size, instead of the cap.
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 2d41bee9d..2f3938d43 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -227,7 +227,7 @@ List all sessions, scoped to the API key's `allowedSessions`, ordered `createdAt
]
```
-`lastError` can be non-null only when `status` is `failed` or `action_required`, or `initializing` from the fifth consecutive reconnect attempt of a linked session whose engine retries a dropped connection on its own (Baileys); any other status clears it. It is held in memory per process, so it reads `null` after a restart and on a node not running the session. `config` and the raw `proxyUrl` / `proxyType` columns are not present (stripped by `fromEntity`).
+`lastError` can be non-null only when `status` is `failed` or `action_required`, or `initializing` from the fifth consecutive reconnect attempt of a session whose engine retries a dropped connection on its own (Baileys), until the session is ready or a QR arrives (a QR window that runs out unscanned is not an attempt); any other status clears it. It is held in memory per process, so it reads `null` after a restart and on a node not running the session. `config` and the raw `proxyUrl` / `proxyType` columns are not present (stripped by `fromEntity`).
`restriction` reports a limit **WhatsApp itself** has placed on the account, as opposed to `lastError`, which describes a fault on the gateway's side of the link. It is `null` when there is none, and otherwise `{ kind, code, expiresAt }`:
diff --git a/openapi.json b/openapi.json
index ba8e34e6c..ad0def342 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), ACTION_REQUIRED (the engine is running but something needs a human), or INITIALIZING from the fifth consecutive attempt of a linked session whose engine retries a dropped connection on its own. Held in memory by the process running the session. 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 from the fifth consecutive reconnect attempt of a session whose engine retries a dropped connection on its own, until the session is ready or a QR arrives. A QR window that runs out unscanned is not an attempt. Held in memory by the process running the session. 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.ts
index 53f724408..9bc52f2e8 100644
--- a/src/engine/adapters/baileys-lifecycle.ts
+++ b/src/engine/adapters/baileys-lifecycle.ts
@@ -395,11 +395,6 @@ export class BaileysLifecycle {
}): void {
const { connection, qr, isNewLogin, lastDisconnect, reachoutTimeLock } = update;
- // A QR is WhatsApp answering, so whatever streak of failed attempts came before it is over.
- if (qr) {
- this.reconnectAttempts = 0;
- }
-
// Arrives on its own update (no `connection` key) both when WhatsApp pushes a change and when
// probeAccountRestriction() pulls the current state — Baileys routes its own query result back
// through this same event, so one handler covers both channels.
@@ -419,8 +414,10 @@ export class BaileysLifecycle {
// WhatsApp accepted the QR scan or pairing code. It asks for a restart next (a 515 close, which
// the branch below turns into INITIALIZING) and the reconnect opens READY. Left at QR_READY, a
// repeat pairing request in that window would pass the guard and overwrite the just-linked
- // creds.me. AUTHENTICATING is what whatsapp-web.js reports at the same point.
+ // creds.me. AUTHENTICATING is what whatsapp-web.js reports at the same point. The link worked, so
+ // that restart is attempt 1 whatever failed before the scan.
this.qrCode = null;
+ this.reconnectAttempts = 0;
this.setStatus(EngineStatus.AUTHENTICATING);
}
@@ -495,7 +492,8 @@ export class BaileysLifecycle {
// Every other close (408/411/428/500/503/515/undefined) is transient: reconnect with capped
// backoff and NO attempt ceiling — a long network outage must
- // not kill the session. The counter resets on 'open', on a QR, and via the stability window below.
+ // not kill the session. The counter resets on 'open', on a scan, when a QR window runs out, 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', {
sessionId: this.host.config.sessionId,
@@ -505,8 +503,10 @@ export class BaileysLifecycle {
});
// Baileys ends an unscanned socket with a 408 once its QR refs run out, the same code as a lost
- // connection, so only the status the close found (read before it changes below) tells them apart.
- const qrWindowEnded = this.status === EngineStatus.QR_READY;
+ // connection, so only its message tells them apart. Every other close while a QR waits (503, 500,
+ // 428, a lost connection) is a failure like any other. Should Baileys reword the message, the
+ // expiry counts too, which backs off rather than loops.
+ const qrWindowEnded = (lastDisconnect?.error as Error | undefined)?.message === 'QR refs attempts ended';
// 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
@@ -524,8 +524,10 @@ export class BaileysLifecycle {
// 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.
+ // A QR window that ran out resets it too: WhatsApp answered, and a QR left unscanned for hours
+ // must not add up to a reconnect loop.
const now = Date.now();
- if (now - this.lastConnectionCloseAt > BaileysLifecycle.RECONNECT_STABILITY_RESET_MS) {
+ if (qrWindowEnded || now - this.lastConnectionCloseAt > BaileysLifecycle.RECONNECT_STABILITY_RESET_MS) {
this.reconnectAttempts = 0;
}
this.lastConnectionCloseAt = now;
@@ -592,8 +594,8 @@ export class BaileysLifecycle {
* only loggedOut (401), forbidden (403), and connectionReplaced (440) are terminal. A connect()
* failure inside the attempt is just a failed attempt: warn and schedule the next one.
*
- * `countAttempt` false is a session waiting to be paired whose QR window ran out: the connection
- * worked, so the reconnect is neither an attempt nor reported, and it waits only the first step.
+ * `countAttempt` false is only the close that ends an unscanned QR window: the connection worked,
+ * so the reconnect is neither an attempt nor reported, and after the reset it waits the first step.
*/
private scheduleReconnect(countAttempt = true): void {
if (this.intentionalClose || this.reconnectTimer) {
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index ec9bbb2ab..5e6424b44 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -1119,10 +1119,16 @@ describe('BaileysAdapter reconnect policy — unlimited backoff (I4 hardening)',
expect(baileys().default).toHaveBeenCalledTimes(1);
});
- const fireClose = (statusCode: number): void => {
- fakeSock.fire('connection.update', { connection: 'close', lastDisconnect: { error: { output: { statusCode } } } });
+ const fireClose = (statusCode: number, message?: string): void => {
+ fakeSock.fire('connection.update', {
+ connection: 'close',
+ lastDisconnect: { error: { message, output: { statusCode } } },
+ });
};
+ // The Boom Baileys ends an unscanned socket with (Socket/socket.js, genPairQR).
+ const QR_REFS_ENDED = 'QR refs attempts ended';
+
/**
* Deliver a QR on the current socket and wait for the lifecycle to publish it. The renderer's PNG
* encoder runs on nextTick and setImmediate, so a test using this must leave both unfaked.
@@ -1142,11 +1148,11 @@ describe('BaileysAdapter reconnect policy — unlimited backoff (I4 hardening)',
jest.useFakeTimers({ doNotFake: ['nextTick', 'setImmediate'] });
jest.spyOn(Math, 'random').mockReturnValue(0);
- for (let window = 1; window <= 6; window++) {
+ for (let window = 1; window <= 8; window++) {
await showQr(`QR-${window}`);
expect(adapter.getStatus()).toBe(EngineStatus.QR_READY);
await jest.advanceTimersByTimeAsync(160_000);
- fireClose(408);
+ fireClose(408, QR_REFS_ENDED);
expect(adapter.getStatus()).toBe(EngineStatus.INITIALIZING);
// Always the first backoff step: nothing at 999 ms, the new socket at 1 s.
@@ -1157,12 +1163,59 @@ describe('BaileysAdapter reconnect policy — unlimited backoff (I4 hardening)',
}
expect(onReconnecting).not.toHaveBeenCalled();
- // A socket that then fails before any QR opens a fresh episode: attempt 1, not attempt 7.
+ // A socket that then fails before any QR opens a fresh episode: attempt 1, not attempt 9.
fireClose(408);
expect(onReconnecting.mock.calls).toEqual([[1, 1_000]]);
});
- it('a QR ends the streak: the restart WhatsApp asks for after a scan is attempt 1 again', async () => {
+ it('a QR window that runs out ends the streak, so a QR left unscanned never reaches the loop alert', async () => {
+ const onReconnecting = jest.fn();
+ await initWithRealTimers({ onReconnecting });
+ jest.useFakeTimers({ doNotFake: ['nextTick', 'setImmediate'] });
+ jest.spyOn(Math, 'random').mockReturnValue(0);
+
+ for (let window = 1; window <= 6; window++) {
+ await showQr(`QR-${window}a`);
+ fireClose(428);
+ await jest.advanceTimersByTimeAsync(1_000);
+ await showQr(`QR-${window}b`);
+ fireClose(408, QR_REFS_ENDED);
+ await jest.advanceTimersByTimeAsync(1_000);
+ }
+
+ expect(onReconnecting.mock.calls).toEqual(Array.from({ length: 6 }, () => [1, 1_000]));
+ });
+
+ // Only the QR expiry is exempt. WhatsApp or a proxy shedding the socket after it served a QR is a
+ // failure like any other, and left uncounted it would open a new registration every second, unseen.
+ it.each([
+ { reason: '503', statusCode: 503, message: undefined },
+ { reason: '500', statusCode: 500, message: undefined },
+ { reason: '428', statusCode: 428, message: undefined },
+ { reason: 'lost connection 408', statusCode: 408, message: 'Connection was lost' },
+ ])('a $reason close while a QR waits counts and backs off', async ({ statusCode, message }) => {
+ const onReconnecting = jest.fn();
+ await initWithRealTimers({ onReconnecting });
+ baileys().default.mockClear();
+ jest.useFakeTimers({ doNotFake: ['nextTick', 'setImmediate'] });
+ jest.spyOn(Math, 'random').mockReturnValue(0);
+
+ const delays = [1_000, 2_000, 4_000, 8_000, 16_000];
+ for (const [cycle, delay] of delays.entries()) {
+ await showQr(`QR-${cycle}`);
+ expect(onReconnecting).toHaveBeenCalledTimes(cycle);
+ fireClose(statusCode, message);
+ await jest.advanceTimersByTimeAsync(delay - 1);
+ expect(baileys().default).toHaveBeenCalledTimes(cycle);
+ await jest.advanceTimersByTimeAsync(1);
+ expect(baileys().default).toHaveBeenCalledTimes(cycle + 1);
+ }
+
+ // Attempt 5 is the one the session layer turns into the reconnect-loop alert.
+ expect(onReconnecting.mock.calls).toEqual(delays.map((delay, cycle) => [cycle + 1, delay]));
+ });
+
+ it('a scan ends the streak: the restart WhatsApp asks for after it is attempt 1 again', async () => {
const onReconnecting = jest.fn();
await initWithRealTimers({ onReconnecting });
jest.useFakeTimers({ doNotFake: ['nextTick', 'setImmediate'] });
@@ -1170,9 +1223,10 @@ describe('BaileysAdapter reconnect policy — unlimited backoff (I4 hardening)',
fireClose(408);
await jest.advanceTimersByTimeAsync(1_000);
+ await showQr('QR-1');
fireClose(503);
await jest.advanceTimersByTimeAsync(2_000);
- await showQr('QR-1');
+ await showQr('QR-2');
fakeSock.fire('connection.update', { isNewLogin: true });
onReconnecting.mockClear();
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index d6aae3150..6230285e3 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -791,9 +791,9 @@ export interface EngineEventCallbacks {
* 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 WhatsApp answers with a QR (or after a long enough healthy stretch), so attempt 1
- * always opens a fresh episode. A session waiting to be paired is not reconnecting: the close that
- * ends an unscanned QR window is never reported.
+ * is back, a QR is scanned or a QR window runs out (or after a long enough healthy stretch), so
+ * attempt 1 always opens a fresh episode. The close that ends an unscanned QR window is not a reconnect
+ * and is never reported; any other close while a QR waits is.
* `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
diff --git a/src/modules/session/dto/session-response.dto.ts b/src/modules/session/dto/session-response.dto.ts
index 4951da533..e5e402073 100644
--- a/src/modules/session/dto/session-response.dto.ts
+++ b/src/modules/session/dto/session-response.dto.ts
@@ -67,7 +67,8 @@ export class SessionResponseDto {
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 from the ' +
- 'fifth consecutive attempt of a linked session whose engine retries a dropped connection on its own. ' +
+ 'fifth consecutive reconnect attempt of a session whose engine retries a dropped connection on its own, ' +
+ 'until the session is ready or a QR arrives. A QR window that runs out unscanned is not an attempt. ' +
'Held in memory by the process running the session. 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.ts
index ebfac5866..d6791bd6f 100644
--- a/src/modules/session/session-engine-event-wiring.ts
+++ b/src/modules/session/session-engine-event-wiring.ts
@@ -26,6 +26,9 @@ import { type createLogger } from '../../common/services/logger.service';
import { userPart } from '../../engine/identity/wa-id';
import { SessionEngineLeafEvents } from './session-engine-leaf-events';
+/** The lastError an engine-internal reconnect episode records; onQRCode clears only this one. */
+const RECONNECT_LOOP_REASON = 'Reconnecting after a dropped connection';
+
/**
* The call-ins SessionEngineEventWiring needs from the lifecycle core. Built ONCE in the
* lifecycle's constructor. Only the CLOSURE members are live-read: the arrow closures bind the
@@ -173,6 +176,11 @@ export class SessionEngineEventWiring {
);
}
+ // A QR shows WhatsApp answered. Left in place, the recorded reconnect text would reappear in every
+ // INITIALIZING gap between QR windows of a session waiting to be paired; if closes keep failing
+ // after the QR, the next attempt from the fifth on writes it again. Any other reason stays.
+ if (host.sessionErrors.get(id)?.startsWith(RECONNECT_LOOP_REASON)) host.sessionErrors.clear(id);
+
void host.webhookService.dispatch(id, 'session.qr', { sessionId: id, qr });
// Push the QR to subscribed dashboard clients over the WebSocket (the `session.qr` event is
@@ -291,10 +299,7 @@ export class SessionEngineEventWiring {
// 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. Rewritten on every
// attempt from here on, so the attempt and the downtime it shows never lag the episode.
- host.sessionErrors.set(
- id,
- `Reconnecting after a dropped connection (attempt ${attempt}, down for ${downFor}).`,
- );
+ host.sessionErrors.set(id, `${RECONNECT_LOOP_REASON} (attempt ${attempt}, down for ${downFor}).`);
if (attempt % RECONNECT_LOOP_ALERT_INTERVAL_ATTEMPTS !== 0) return;
// Same cadence, same log shape and the same already-documented webhook the service-level
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index c835a02b4..b4f475908 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -2712,6 +2712,30 @@ describe('SessionService', () => {
expect(loopDispatches()).toHaveLength(1);
});
+ // A QR is WhatsApp answering, so the outage is over. Left in place, the old text would come back
+ // at every INITIALIZING gap between QR windows of a session that is only waiting to be paired.
+ it('clears the reconnect lastError once a QR arrives', async () => {
+ const callbacks = await startAndCapture();
+
+ for (let attempt = 1; attempt <= 5; attempt++) callbacks.onReconnecting?.(attempt, 60_000);
+ callbacks.onQRCode?.('qr-data');
+
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession({ status: SessionStatus.INITIALIZING }));
+ const result = await service.findOne('sess-uuid-1');
+
+ expect(result.lastError).toBeUndefined();
+ });
+
+ it('a QR leaves any other lastError alone', async () => {
+ const callbacks = await startAndCapture();
+ const sessionErrors = (service as unknown as { sessionErrors: SessionErrorStore }).sessionErrors;
+
+ callbacks.onActionRequired?.('Dismiss the onboarding dialog on the phone');
+ callbacks.onQRCode?.('qr-data');
+
+ expect(sessionErrors.get('sess-uuid-1')).toBe('Dismiss the onboarding dialog on the phone');
+ });
+
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();