Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(baileys): keep QR expiry out of reconnect-loop reporting

Yudhi Armyndharis8e9da57e07ab
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 039dae648..1c6a07a79 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,7 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- The Baileys live path drops contentless protocol traffic (sender-key distributions, message-history notices) instead of delivering it as a bodyless `unknown` `message.received`, matching what the history path already does ([#1568](https://github.com/rmyndharis/OpenWA/issues/1568)). Thanks @berodcdev for the report.
-- A Baileys reconnect loop is observable: `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 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.
- 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 re-reads the list once the feed recovers.
- 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 2fc5dcfc7..bdce08ecd 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` is non-null when `status` is `failed` or `action_required`, and while an `initializing` session is retrying a dropped connection on its own; any other status clears it. `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 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`).
`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 555b8a242..ba8e34e6c 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 while the engine is retrying a dropped connection on its own. 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 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.",
"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 99767021e..53f724408 100644
--- a/src/engine/adapters/baileys-lifecycle.ts
+++ b/src/engine/adapters/baileys-lifecycle.ts
@@ -395,6 +395,11 @@ 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.
@@ -490,7 +495,7 @@ 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' and via the stability window below.
+ // not kill the session. The counter resets on 'open', on a QR, 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,
@@ -499,6 +504,10 @@ export class BaileysLifecycle {
action: 'baileys_connection_dropped',
});
+ // 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;
+
// The socket is dead NOW, but the reconnect attempt only runs after the backoff delay below
// (up to 60 s + jitter; connectInner's own setStatus(INITIALIZING) fires just before the new
// socket is created). Staying READY across that window makes probeLiveness() report a live
@@ -520,7 +529,7 @@ export class BaileysLifecycle {
this.reconnectAttempts = 0;
}
this.lastConnectionCloseAt = now;
- this.scheduleReconnect();
+ this.scheduleReconnect(!qrWindowEnded);
}
}
@@ -582,19 +591,27 @@ export class BaileysLifecycle {
* cap, plus up to 1 s jitter). Deliberately NO attempt ceiling: transient drops retry forever —
* 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.
*/
- private scheduleReconnect(): void {
+ private scheduleReconnect(countAttempt = true): 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);
+ if (countAttempt) {
+ this.reconnectAttempts += 1;
+ }
+ const step = Math.max(this.reconnectAttempts - 1, 0);
+ const delay = Math.min(60_000, 1_000 * 2 ** step) + 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);
+ if (countAttempt) {
+ 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.ts
index 6ba8257c5..08d0e3362 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -1106,6 +1106,88 @@ describe('BaileysAdapter reconnect policy — unlimited backoff (I4 hardening)',
await new Promise<void>(r => setImmediate(r));
expect(baileys().default).toHaveBeenCalledTimes(1);
});
+
+ const fireClose = (statusCode: number): void => {
+ fakeSock.fire('connection.update', { connection: 'close', lastDisconnect: { error: { output: { statusCode } } } });
+ };
+
+ /**
+ * 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.
+ */
+ const showQr = async (qr: string): Promise<void> => {
+ fakeSock.fire('connection.update', { connection: 'connecting' });
+ fakeSock.fire('connection.update', { qr });
+ await (qrcode.toDataURL as unknown as jest.Mock).mock.results.at(-1)?.value;
+ };
+
+ // An unpaired socket rotates QRs until its refs run out (60 s, then 20 s per ref), and Baileys then
+ // ends it with a 408: the same code as a lost connection. WhatsApp answered, so the close is no failure.
+ it('a QR window that runs out is not a reconnect attempt: never reported, and the backoff never grows', async () => {
+ const onReconnecting = jest.fn();
+ const adapter = await initWithRealTimers({ onReconnecting });
+ baileys().default.mockClear();
+ jest.useFakeTimers({ doNotFake: ['nextTick', 'setImmediate'] });
+ jest.spyOn(Math, 'random').mockReturnValue(0);
+
+ for (let window = 1; window <= 6; window++) {
+ await showQr(`QR-${window}`);
+ expect(adapter.getStatus()).toBe(EngineStatus.QR_READY);
+ await jest.advanceTimersByTimeAsync(160_000);
+ fireClose(408);
+ expect(adapter.getStatus()).toBe(EngineStatus.INITIALIZING);
+
+ // Always the first backoff step: nothing at 999 ms, the new socket at 1 s.
+ await jest.advanceTimersByTimeAsync(999);
+ expect(baileys().default).toHaveBeenCalledTimes(window - 1);
+ await jest.advanceTimersByTimeAsync(1);
+ expect(baileys().default).toHaveBeenCalledTimes(window);
+ }
+ expect(onReconnecting).not.toHaveBeenCalled();
+
+ // A socket that then fails before any QR opens a fresh episode: attempt 1, not attempt 7.
+ 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 () => {
+ const onReconnecting = jest.fn();
+ await initWithRealTimers({ onReconnecting });
+ jest.useFakeTimers({ doNotFake: ['nextTick', 'setImmediate'] });
+ jest.spyOn(Math, 'random').mockReturnValue(0);
+
+ fireClose(408);
+ await jest.advanceTimersByTimeAsync(1_000);
+ fireClose(503);
+ await jest.advanceTimersByTimeAsync(2_000);
+ await showQr('QR-1');
+ fakeSock.fire('connection.update', { isNewLogin: true });
+ onReconnecting.mockClear();
+
+ fireClose(515);
+ expect(onReconnecting.mock.calls).toEqual([[1, 1_000]]);
+ });
+
+ it('a linked session still reports every attempt of an outage, growing backoff included', async () => {
+ const onReconnecting = jest.fn();
+ await initWithRealTimers({ onReconnecting });
+ fakeSock.fire('connection.update', { connection: 'open' });
+ jest.useFakeTimers();
+ jest.spyOn(Math, 'random').mockReturnValue(0);
+
+ for (const statusCode of [408, 503, 408, 503, 408]) {
+ fireClose(statusCode);
+ await jest.advanceTimersByTimeAsync(60_000); // the reconnected socket never opens
+ }
+
+ expect(onReconnecting.mock.calls).toEqual([
+ [1, 1_000],
+ [2, 2_000],
+ [3, 4_000],
+ [4, 8_000],
+ [5, 16_000],
+ ]);
+ });
});
describe('BaileysAdapter probeLiveness', () => {
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index 105e3dddb..d6aae3150 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -791,7 +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 after a long enough healthy stretch), so attempt 1 always opens a fresh episode.
+ * 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.
* `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 0683381b7..4951da533 100644
--- a/src/modules/session/dto/session-response.dto.ts
+++ b/src/modules/session/dto/session-response.dto.ts
@@ -66,8 +66,9 @@ export class SessionResponseDto {
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 while the ' +
- 'engine is retrying a dropped connection on its own. Cleared on any other status.',
+ '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.',
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 6f1cd7234..ebfac5866 100644
--- a/src/modules/session/session-engine-event-wiring.ts
+++ b/src/modules/session/session-engine-event-wiring.ts
@@ -283,17 +283,20 @@ export class SessionEngineEventWiring {
// 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;
+ if (attempt < RECONNECT_LOOP_ALERT_INTERVAL_ATTEMPTS) 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.
+ // 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}).`,
);
+ if (attempt % RECONNECT_LOOP_ALERT_INTERVAL_ATTEMPTS !== 0) return;
+
// 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.
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 929d0569a..48da42f94 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -2579,6 +2579,29 @@ describe('SessionService', () => {
expect(result.lastError).toMatch(/^Reconnecting after a dropped connection \(attempt 5, down for /);
});
+ it('keeps lastError current on every attempt past the fifth, while the alert stays on its cadence', async () => {
+ const callbacks = await startAndCapture();
+ (webhookService.dispatch as jest.Mock).mockClear();
+ const sessionErrors = (service as unknown as { sessionErrors: SessionErrorStore }).sessionErrors;
+ const start = Date.now();
+ const now = jest.spyOn(Date, 'now');
+ try {
+ for (let attempt = 1; attempt <= 9; attempt++) {
+ now.mockReturnValue(start + (attempt - 1) * 60_000); // one minute between attempts
+ callbacks.onReconnecting?.(attempt, 60_000);
+ if (attempt >= 6) {
+ expect(sessionErrors.get('sess-uuid-1')).toBe(
+ `Reconnecting after a dropped connection (attempt ${attempt}, down for ${attempt - 1}m).`,
+ );
+ }
+ }
+ } finally {
+ now.mockRestore();
+ }
+
+ expect(loopDispatches()).toHaveLength(1);
+ });
+
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();