Skip to content

fix: Correção reconexão após logout — isDeleting e qrcode.count não resetados#2560

Open
iagocotta wants to merge 1 commit into
evolution-foundation:developfrom
iagocotta:fix--corrigir-reconexão-após-logout-—-isDeleting-e-qrcode.count-não-resetados

Hidden character warning

The head ref may contain hidden characters: "fix--corrigir-reconex\u00e3o-ap\u00f3s-logout-\u2014-isDeleting-e-qrcode.count-n\u00e3o-resetados"
Open

fix: Correção reconexão após logout — isDeleting e qrcode.count não resetados#2560
iagocotta wants to merge 1 commit into
evolution-foundation:developfrom
iagocotta:fix--corrigir-reconexão-após-logout-—-isDeleting-e-qrcode.count-não-resetados

Conversation

@iagocotta
Copy link
Copy Markdown

@iagocotta iagocotta commented May 22, 2026

Descrição

Problema

Após chamar POST /instance/logout e em seguida POST /instance/connect, o QR code era exibido mas a conexão nunca se completava ao escanear. O fluxo só funcionava corretamente se a instância fosse deletada (/instance/delete) e recriada (/instance/create).


Bug 1 — isDeleting nunca era resetado após logout

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

logoutInstance() seta this.isDeleting = true para bloquear reconexões automáticas durante o processo de logout. O problema é que essa flag nunca voltava para false.

Quando o usuário chamava /instance/connect em seguida, o socket do Baileys era criado normalmente e o QR era gerado — mas ao escanear o QR com o celular, o Baileys emite um evento connection.update com connection === 'close' como parte do handshake de autenticação. O handler via isDeleting === true e abortava silenciosamente:

if (this.isDeleting || this.endSession) {
  this.logger.info('Instance is being deleted/ended, skipping reconnection attempt');
  return; // ← autenticação do celular era descartada aqui
}

Correção: resetar this.isDeleting = false em createClient(), junto com o já existente this.endSession = false, antes de instanciar o socket:

this.endSession = false;
this.isDeleting = false; // ← adicionado
this.client = makeWASocket(socketConfig);

O reset foi feito em createClient() (e não em connectToWhatsapp()) porque createClient() é o ponto de entrada real da criação do socket, cobrindo também reloadConnection() — chamado após operações como updatePrivacySettings e updateProfilePicture.


Bug 2 — qrcode.count acumulava entre sessões

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

O contador de QR codes (this.instance.qrcode.count) era zerado no construtor da classe e pelo handler do evento no.connection (quando o limite era atingido), mas não era resetado no logout. Isso fazia com que sessões consecutivas de logout + connect consumissem o limite de QR codes mais rapidamente, podendo resultar no disparo prematuro do evento no.connection e bloqueio do fluxo.

Correção: resetar o contador ao final de logoutInstance(), após a atualização do status no banco:

await this.prismaRepository.instance.update({
  where: { id: this.instanceId },
  data: { connectionStatus: 'close' },
});

this.instance.qrcode = { count: 0 }; // ← adicionado

O reset foi colocado em logoutInstance() (e não em connectToWhatsapp()) porque connectToWhatsapp() também é invocado pelo loop de auto-reconexão interna — resetar o contador nesse ponto burlaria o limite de QR codes em reconexões inesperadas.


Por que delete + create funcionava

O delete destrói o objeto da instância em memória (delete waInstances[instanceName]). O create instancia um objeto completamente novo, com todos os valores padrão da classe (isDeleting = false, qrcode.count = 0). As correções reproduzem esse estado limpo sem exigir a destruição e recriação do objeto.


Arquivos alterados

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

Summary by Sourcery

Reset WhatsApp Baileys instance state on reconnect to ensure clean sessions after logout.

Bug Fixes:

  • Reset the isDeleting flag when creating a new WhatsApp client so reconnections after logout can complete successfully.
  • Reset the QR code counter on logout so QR usage does not accumulate across sessions and prematurely trigger connection blocking.

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented May 22, 2026

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Resets internal Baileys WhatsApp service flags and QR-code counters on client (re)creation and logout to ensure clean reconnection flows after /instance/logout + /instance/connect without requiring delete + create of the instance.

Sequence diagram for logout + reconnect flow with reset of isDeleting and qrcode.count

sequenceDiagram
  actor User
  participant Api as ApiServer
  participant Service as BaileysStartupService
  participant Baileys as BaileysSocket
  participant DB as PrismaRepository

  User->>Api: POST /instance/logout
  Api->>Service: logoutInstance()
  Service->>Baileys: endSession (close socket)
  Service->>DB: instance.update(connectionStatus: close)
  Service->>Service: this.instance.qrcode = { count: 0 }

  User->>Api: POST /instance/connect
  Api->>Service: connectToWhatsapp()
  Service->>Service: createClient()
  Service->>Service: this.endSession = false
  Service->>Service: this.isDeleting = false
  Service->>Baileys: makeWASocket(socketConfig)
  Baileys-->>Service: connection.update(connection: close)
  Service->>Service: [isDeleting === false and endSession === false]
  Service->>Baileys: continue authentication
  Baileys-->>Service: connection.update(connection: open)
Loading

File-Level Changes

Change Details Files
Ensure logout clears QR-code attempt counter so new sessions start with a fresh QR limit.
  • After updating the instance connectionStatus to 'close' on logout, reset the in-memory QR code tracking object to count = 0 so subsequent connects don’t inherit the previous session’s usage.
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
Ensure client creation resets deletion flag so Baileys connection.update events are processed normally after logout.
  • In the client creation flow, clear endSession and isDeleting flags before instantiating a new Baileys socket so that connection updates from QR scans are no longer ignored after a logout.
  • Centralize the isDeleting reset in createClient() so it also covers reconnections triggered by reloadConnection() and similar flows.
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

Possibly linked issues

  • #0: O PR corrige exatamente o problema 1 do issue: impossibilidade de reconectar após chamar /instance/logout.
  • #0: PR fixes Baileys sessions where QR is scanned but authentication is aborted after logout, matching reported behavior

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

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

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:

  • When resetting this.instance.qrcode on logout, consider only resetting the count field (e.g. this.instance.qrcode.count = 0) instead of replacing the whole object, to avoid accidentally dropping any other properties that might be attached now or in the future.
  • The interplay between logoutInstance(), createClient(), isDeleting, and endSession is becoming more stateful; consider extracting a small helper (e.g. resetInstanceStateOnConnect() / resetInstanceStateOnLogout()) so it’s easier to reason about and less error‑prone when new flags are added.
  • If logoutInstance() and connectToWhatsapp() can be invoked concurrently for the same instance, it may be worth reviewing whether setting isDeleting = false in createClient() can race with an in‑progress logout and allow an unintended reconnection.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- When resetting `this.instance.qrcode` on logout, consider only resetting the `count` field (e.g. `this.instance.qrcode.count = 0`) instead of replacing the whole object, to avoid accidentally dropping any other properties that might be attached now or in the future.
- The interplay between `logoutInstance()`, `createClient()`, `isDeleting`, and `endSession` is becoming more stateful; consider extracting a small helper (e.g. `resetInstanceStateOnConnect()` / `resetInstanceStateOnLogout()`) so it’s easier to reason about and less error‑prone when new flags are added.
- If `logoutInstance()` and `connectToWhatsapp()` can be invoked concurrently for the same instance, it may be worth reviewing whether setting `isDeleting = false` in `createClient()` can race with an in‑progress logout and allow an unintended reconnection.

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.

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.

1 participant