From 92626fa5595afb6f61cbfd13dfd5953cc71fdccb Mon Sep 17 00:00:00 2001 From: Murilo Leal Date: Tue, 4 Nov 2025 13:49:38 -0300 Subject: [PATCH] fix(baileys): resolve incoming message events not working after reconnection - Add cleanup logic in mount() to prevent memory leaks from multiple subscriptions - Recreate messageSubject if it was completed during logout - Remount messageProcessor in connectToWhatsapp() to ensure subscription is active after reconnection This fixes the issue where incoming message events stop working after logout and reconnect, while outgoing message events continue to work normally. The root cause was that onDestroy() calls complete() on the RxJS Subject, making it permanently closed. When reconnecting, the Subject would silently ignore all new messages. The fix ensures that: 1. Old subscriptions are properly cleaned up before creating new ones 2. If the Subject is closed, a new one is created automatically 3. The messageProcessor is remounted on every connection to ensure active subscription --- .../channel/whatsapp/baileysMessage.processor.ts | 16 ++++++++++++++++ .../channel/whatsapp/whatsapp.baileys.service.ts | 5 +++++ 2 files changed, 21 insertions(+) diff --git a/src/api/integrations/channel/whatsapp/baileysMessage.processor.ts b/src/api/integrations/channel/whatsapp/baileysMessage.processor.ts index c2c5931e..fbe1864a 100644 --- a/src/api/integrations/channel/whatsapp/baileysMessage.processor.ts +++ b/src/api/integrations/channel/whatsapp/baileysMessage.processor.ts @@ -19,6 +19,22 @@ export class BaileysMessageProcessor { }>(); mount({ onMessageReceive }: MountProps) { + // Se já existe subscription, fazer cleanup primeiro + if (this.subscription && !this.subscription.closed) { + this.subscription.unsubscribe(); + } + + // Se o Subject foi completado, recriar + if (this.messageSubject.closed) { + this.processorLogs.warn('MessageSubject was closed, recreating...'); + this.messageSubject = new Subject<{ + messages: WAMessage[]; + type: MessageUpsertType; + requestId?: string; + settings: any; + }>(); + } + this.subscription = this.messageSubject .pipe( tap(({ messages }) => { diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 1e3bdcf1..60082c4b 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -710,6 +710,11 @@ export class BaileysStartupService extends ChannelStartupService { this.loadWebhook(); this.loadProxy(); + // Remontar o messageProcessor para garantir que está funcionando após reconexão + this.messageProcessor.mount({ + onMessageReceive: this.messageHandle['messages.upsert'].bind(this), + }); + return await this.createClient(number); } catch (error) { this.logger.error(error);