Skip to content

fix(whatsmeow): rotear Chat para DestinationJID em mensagens enviadas por aparelhos vinculados (multi-device) - #191

Open
douglasanpa wants to merge 2 commits into
evolution-foundation:mainfrom
douglasanpa:fix/multi-device-destination-jid
Open

fix(whatsmeow): rotear Chat para DestinationJID em mensagens enviadas por aparelhos vinculados (multi-device)#191
douglasanpa wants to merge 2 commits into
evolution-foundation:mainfrom
douglasanpa:fix/multi-device-destination-jid

Conversation

@douglasanpa

@douglasanpa douglasanpa commented Sep 8, 2026

Copy link
Copy Markdown

Descrição do Problema

Quando uma mensagem é enviada a partir de um aparelho vinculado (celular físico primário da conta ou WhatsApp Web multi-device), a biblioteca WhatsMeow emite o evento *events.Message com IsFromMe = true.

Nesse fluxo do WhatsMeow:

  1. evt.Info.Chat é preenchido com o JID da própria instância/empresa (o remetente), e não com o contato de destino.
  2. O contato real de destino fica armazenado exclusivamente em evt.Info.DeviceSentMeta.DestinationJID.

Impacto

No payload JSON entregue pelos webhooks:

  • O campo Chat chega com o próprio número do WhatsApp conectado em vez do número do cliente que recebeu a mensagem.
  • O campo Recipient fica ausente ou não reflete o destinatário.
  • Plataformas de CRM, sistemas de atendimento e bots que monitoram mensagens enviadas manualmente por atendentes para ativar handover humano ou registrar o histórico da conversa não conseguem identificar para qual contato a mensagem foi enviada.

O que esta alteração faz

  1. Roteamento de Destino: Se a mensagem for outbound (IsFromMe = true), contiver metadados multi-device (DeviceSentMeta != nil) e for uma conversa privada (!IsGroup), converte o DestinationJID em types.JID e atualiza evt.Info.Chat para o destinatário real.
  2. Campos no Webhook: Popula explicitamente Recipient e recipient com o DestinationJID, além de garantir que Chat reflita o destinatário no dataMap.
  3. Preservação de Grupos: Mensagens enviadas para grupos (@g.us) não são alteradas, preservando o JID do grupo em Chat.

Como foi testado

  • Validado com stanzas reais de sincronização multi-device do WhatsMeow.
  • Testado tanto com destinatários em formato tradicional (@s.whatsapp.net) quanto com identificadores LID (@lid).
  • Confirmado que o webhook agora envia o JID correto do lead em Chat e Recipient, permitindo a conciliação imediata da conversa.

Summary by Sourcery

Direcione mensagens outbound de multi-dispositivo ao destinatário correto nos eventos e webhooks, preservando o comportamento para grupos.

Bug Fixes:

  • Corrija o roteamento de mensagens enviadas por aparelhos vinculados para identificar o destinatário real em conversas privadas.
  • Preencha os campos Chat e Recipient dos webhooks com o JID de destino, incluindo destinatários em formato tradicional e LID.

Enhancements:

  • Preserve o JID original de grupos e adicione tratamento de destinos inválidos sem interromper o processamento.

@sourcery-ai

sourcery-ai Bot commented Sep 8, 2026

Copy link
Copy Markdown

Reviewer's Guide

Updates WhatsMeow event handling so outbound private messages synchronized from linked devices use DeviceSentMeta.DestinationJID as the conversation and recipient JID in webhook payloads, while preserving group-chat routing and supporting standard WhatsApp and LID identifiers.

File-Level Changes

Change Details Files
Reroutes private outbound multi-device messages to the actual destination JID.
  • Detects from-me events with valid DeviceSentMeta destination data.
  • Parses and assigns DestinationJID to evt.Info.Chat while preserving invalid-JID behavior.
  • Excludes group messages from Chat replacement.
pkg/whatsmeow/service/whatsmeow.go
Exposes the multi-device destination consistently in webhook payloads.
  • Populates both recipient and Recipient with DestinationJID.
  • Synchronizes chat and Chat with the resolved destination for private messages.
pkg/whatsmeow/service/whatsmeow.go

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

Choose a reason for hiding this comment

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

Hey - I've found 1 issue

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="pkg/whatsmeow/service/whatsmeow.go" line_range="1230" />
<code_context>
+		// O whatsmeow preenche evt.Info.Chat como o próprio número da empresa e armazena o lead de destino
+		// em evt.Info.DeviceSentMeta.DestinationJID.
+		if evt.Info.IsFromMe && evt.Info.DeviceSentMeta != nil && evt.Info.DeviceSentMeta.DestinationJID != "" && !evt.Info.IsGroup {
+			if destJID, err := types.ParseJID(evt.Info.DeviceSentMeta.DestinationJID); err == nil && !destJID.IsEmpty() {
+				mycli.loggerWrapper.GetLogger(mycli.userID).LogInfo("[%s] Outbound multi-device message detected - routing Chat from %s to DestinationJID %s",
+					mycli.userID, evt.Info.Chat.String(), destJID.String())
</code_context>
<issue_to_address>
**issue (bug_risk):** When `DestinationJID` is non-empty but malformed, `types.ParseJID` fails and the code silently leaves `evt.Info.Chat` pointing to the company JID while still publishing the invalid raw value in both `Recipient` fields. Consumers receive contradictory routing data instead of a rejected or clearly invalid event.

**Triggers:** When WhatsMeow emits an invalid or unsupported `DestinationJID`.

**Suggested fix:** Validate the destination once and only populate `Recipient` or rewrite `Chat` after successful parsing; otherwise log the parse error and retain the original fields without claiming the invalid value is the recipient.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 1 finding to address first, and if the destination JID is routed incorrectly, an outbound message can be associated with the wrong chat and the emitted recipient/chat data can remain in stored records or downstream events after a revert. The impact is bounded and repairable by correcting or replaying affected message data; no money movement, deletion, or access decision is introduced.

Blocking findings: pkg/whatsmeow/service/whatsmeow.go:1230


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread pkg/whatsmeow/service/whatsmeow.go
@douglasanpa

Copy link
Copy Markdown
Author

Corrigido no commit f58565c: a validação de DestinationJID via types.ParseJID agora é executada uma única vez. Se o JID for inválido, registra um warning nos logs sem sobrescrever Chat e sem popular Recipient com valor malformado. Os campos de destinatário no webhook (Recipient, recipient, Chat, chat) só são preenchidos após a validação bem-sucedida do JID.

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