Skip to content

Commit b76325d

Browse files
author
octo-patch
committed
fix(baileys): prevent healthy instances from being killed after stream:error 515
When WhatsApp sends stream:error code=515 (Connection Replaced), Baileys handles the reconnect correctly and fires connection.update with state='open'. However, WhatsApp then sends a 401 (loggedOut) to clean up the old session slot, which Evolution API incorrectly treated as a real logout, killing the newly-connected healthy instance. The fix tracks when a stream:error 515 node arrives via the CB:stream:error WebSocket event. If a loggedOut (401) close event fires within 30 seconds of a 515, it is treated as a transient reconnect rather than a real logout. Fixes #2498
1 parent cd800f2 commit b76325d

1 file changed

Lines changed: 11 additions & 1 deletion

File tree

src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,7 @@ export class BaileysStartupService extends ChannelStartupService {
251251
private endSession = false;
252252
private logBaileys = this.configService.get<Log>('LOG').BAILEYS;
253253
private eventProcessingQueue: Promise<void> = Promise.resolve();
254+
private _lastStream515At = 0;
254255

255256
// Cache TTL constants (in seconds)
256257
private readonly MESSAGE_CACHE_TTL_SECONDS = 5 * 60; // 5 minutes - avoid duplicate message processing
@@ -426,7 +427,10 @@ export class BaileysStartupService extends ChannelStartupService {
426427
if (connection === 'close') {
427428
const statusCode = (lastDisconnect?.error as Boom)?.output?.statusCode;
428429
const codesToNotReconnect = [DisconnectReason.loggedOut, DisconnectReason.forbidden, 402, 406];
429-
const shouldReconnect = !codesToNotReconnect.includes(statusCode);
430+
const recentStream515 = Date.now() - this._lastStream515At < 30_000;
431+
const shouldReconnect =
432+
!codesToNotReconnect.includes(statusCode) ||
433+
(statusCode === DisconnectReason.loggedOut && recentStream515);
430434
if (shouldReconnect) {
431435
await this.connectToWhatsapp(this.phoneNumber);
432436
} else {
@@ -715,6 +719,12 @@ export class BaileysStartupService extends ChannelStartupService {
715719
this.sendDataWebhook(Events.CALL, payload, true, ['websocket']);
716720
});
717721

722+
this.client.ws.on('CB:stream:error', (node: any) => {
723+
if (node?.attrs?.code === '515') {
724+
this._lastStream515At = Date.now();
725+
}
726+
});
727+
718728
this.phoneNumber = number;
719729

720730
return this.client;

0 commit comments

Comments
 (0)