Skip to content

fix: fecha socket anterior antes de recriar cliente Baileys#2656

Open
PhyBruno wants to merge 6 commits into
evolution-foundation:developfrom
PhyBruno:fix/problema-2-qr-nao-conecta
Open

fix: fecha socket anterior antes de recriar cliente Baileys#2656
PhyBruno wants to merge 6 commits into
evolution-foundation:developfrom
PhyBruno:fix/problema-2-qr-nao-conecta

Conversation

@PhyBruno

@PhyBruno PhyBruno commented Jul 24, 2026

Copy link
Copy Markdown

Problema

Mesmo apos gerar o QR Code, as vezes o WhatsApp responde com "Nao foi possivel conectar o dispositivo" ao escanear.

Causa raiz

createClient (em whatsapp.baileys.service.ts) sobrescreve this.client com um novo makeWASocket(socketConfig) sem antes fechar o socket anterior. Em tentativas repetidas de gerar QR (retry manual do usuario, ou reconexao disparada por uma integracao externa), o socket antigo continua "vivo", com seus event handlers ativos disputando a mesma authState/credenciais com o socket novo - corrompendo o handshake da nova sessao.

Mudanca

Antes de this.client = makeWASocket(socketConfig), se ja existir um this.client de uma tentativa anterior, ele e fechado (ws.close() + end(new Error(...))) - mesmo padrao ja usado no proprio arquivo, no handler de connection.update para connection === 'close'. A limpeza fica em try/catch (log em warn) para nao impedir a criacao do novo socket em caso de falha ao fechar o antigo.

Nota: este PR toca o mesmo metodo (createClient) que #2655. Os dois foram gerados/validados de forma independente contra main e cada um builda/lint limpo isoladamente, mas ao mesclar ambos pode ser necessario um rebase simples (proximidade de linha, nao conflito de logica).

Validacao

  • npx tsc --noEmit: sem erros.
  • npx eslint --ext .ts src: sem erros/warnings.
  • Sem alteracao de dependencias.

Summary by Sourcery

Bug Fixes:

  • Close any existing Baileys client socket before creating a new one to avoid multiple active sockets conflicting over the same auth state and causing connection failures.

DavidsonGomes and others added 6 commits May 6, 2026 13:58
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…n-foundation

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
QR Code as vezes era gerado mas o WhatsApp respondia com "Nao foi
possivel conectar o dispositivo". Causa raiz: createClient sobrescrevia
this.client com um novo makeWASocket(...) sem fechar o socket anterior,
deixando handlers de evento antigos vivos e disputando a mesma
authState/credenciais com o socket novo - corrompendo o handshake da
nova sessao.

Antes de criar o socket novo, fecha explicitamente o anterior
(ws.close() + end()), reaproveitando o mesmo padrao ja usado no
handler de connection.update para fechamento de conexao ('close').
@sourcery-ai

sourcery-ai Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor
Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

This PR ensures the previous Baileys WhatsApp socket is cleanly closed before recreating a client, preventing concurrent sockets from corrupting authentication state during QR-based reconnections.

Sequence diagram for recreating Baileys WhatsApp client with socket cleanup

sequenceDiagram
  participant BaileysStartupService
  participant BaileysClient_old as BaileysClient_old
  participant BaileysClient_new as BaileysClient_new

  BaileysStartupService->>BaileysClient_old: ws.close()
  BaileysStartupService->>BaileysClient_old: end(Error)
  BaileysStartupService->>BaileysClient_new: makeWASocket(socketConfig)
  BaileysStartupService->>BaileysStartupService: this.client = BaileysClient_new
Loading

File-Level Changes

Change Details Files
Add defensive cleanup of any existing Baileys client socket before creating a new one in createClient.
  • Check for an existing client instance before socket recreation.
  • Attempt to close the existing WebSocket connection via ws.close().
  • Call end() on the existing client with a descriptive error to terminate the previous session.
  • Wrap cleanup in try/catch so failures to close do not block new client creation.
  • Log cleanup failures at warn level for observability.
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

Possibly linked issues

  • #(unknown): PR fixes stale Baileys sockets corrupting new QR handshakes, matching the reported QR scan connection failure

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've left some high level feedback:

  • Consider extracting the socket cleanup logic (ws.close + end) into a shared helper or method, since the same pattern is already used in the connection.update 'close' handler, to keep behavior consistent and avoid duplication.
  • When logging the error in the cleanup try/catch, you may want to log the full error object or message separately (e.g., this.logger.warn('...', { error })) to preserve stack and structured information for easier debugging.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Consider extracting the socket cleanup logic (ws.close + end) into a shared helper or method, since the same pattern is already used in the connection.update 'close' handler, to keep behavior consistent and avoid duplication.
- When logging the error in the cleanup try/catch, you may want to log the full error object or message separately (e.g., this.logger.warn('...', { error })) to preserve stack and structured information for easier debugging.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@PhyBruno
PhyBruno changed the base branch from main to develop July 24, 2026 20:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants