fix: Correção reconexão após logout — isDeleting e qrcode.count não resetados#2560
Open
iagocotta wants to merge 1 commit into
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"
Conversation
…unt não resetados
Contributor
Reviewer's guide (collapsed on small PRs)Reviewer's GuideResets 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.countsequenceDiagram
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)
File-Level Changes
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Contributor
There was a problem hiding this comment.
Hey - I've left some high level feedback:
- When resetting
this.instance.qrcodeon logout, consider only resetting thecountfield (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, andendSessionis 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()andconnectToWhatsapp()can be invoked concurrently for the same instance, it may be worth reviewing whether settingisDeleting = falseincreateClient()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.Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
1 task
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Descrição
Problema
Após chamar
POST /instance/logoute em seguidaPOST /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 —
isDeletingnunca era resetado após logoutArquivo:
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.tslogoutInstance()setathis.isDeleting = truepara bloquear reconexões automáticas durante o processo de logout. O problema é que essa flag nunca voltava parafalse.Quando o usuário chamava
/instance/connectem 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 eventoconnection.updatecomconnection === 'close'como parte do handshake de autenticação. O handler viaisDeleting === truee abortava silenciosamente:Correção: resetar
this.isDeleting = falseemcreateClient(), junto com o já existentethis.endSession = false, antes de instanciar o socket:O reset foi feito em
createClient()(e não emconnectToWhatsapp()) porquecreateClient()é o ponto de entrada real da criação do socket, cobrindo tambémreloadConnection()— chamado após operações comoupdatePrivacySettingseupdateProfilePicture.Bug 2 —
qrcode.countacumulava entre sessõesArquivo:
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.tsO contador de QR codes (
this.instance.qrcode.count) era zerado no construtor da classe e pelo handler do eventono.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 eventono.connectione bloqueio do fluxo.Correção: resetar o contador ao final de
logoutInstance(), após a atualização do status no banco:O reset foi colocado em
logoutInstance()(e não emconnectToWhatsapp()) porqueconnectToWhatsapp()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 + createfuncionavaO
deletedestrói o objeto da instância em memória (delete waInstances[instanceName]). Ocreateinstancia 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.tsSummary by Sourcery
Reset WhatsApp Baileys instance state on reconnect to ensure clean sessions after logout.
Bug Fixes: