Skip to content

Conversation

@muriloleal13
Copy link

@muriloleal13 muriloleal13 commented Nov 26, 2025

📋 Description

Corrige perda de mensagens do WhatsApp que não eram salvas no banco de dados, especialmente mensagens de canais/newsletters (@lid) e mensagens com criptografia complexa.

🔍 Causa Raiz

O WhatsApp/Baileys envia mensagens criptografadas em duas etapas:

  1. Primeiro: Envia um "stub" (placeholder) com messageStubParameters: ['Message absent from node'] enquanto descriptografa a mensagem
  2. Depois: Envia a mensagem real com o conteúdo descriptografado

O problema ocorria porque:

  • ❌ O stub chegava primeiro e era adicionado ao cache de mensagens duplicadas
  • ✅ O stub era descartado (corretamente) por não ter conteúdo (!received?.message)
  • ❌ A mensagem real chegava depois, mas era ignorada como duplicata porque o ID já estava no cache
  • Resultado: mensagem nunca era salva no banco de dados

✅ Solução Implementada

  • Detectar stubs do WhatsApp através de messageStubParameters contendo 'Message absent from node'
  • Não adicionar stubs ao cache de mensagens duplicadas
  • Permitir que a mensagem real seja processada quando chegar
  • Manter o descarte do stub para evitar salvar placeholders vazios

🔗 Related Issue

🧪 Type of Change

  • 🐛 Bug fix (non-breaking change which fixes an issue)
  • ✨ New feature (non-breaking change which adds functionality)
  • 💥 Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • 📚 Documentation update
  • 🔧 Refactoring (no functional changes)
  • ⚡ Performance improvement
  • 🧹 Code cleanup
  • 🔒 Security fix

🧪 Testing

  • Manual testing completed
  • Functionality verified in development environment
  • No breaking changes introduced
  • Tested with different connection types (Baileys)

Cenários Testados:

  • ✅ Mensagens de canais/newsletters (@lid)
  • ✅ Mensagens com criptografia complexa
  • ✅ Mensagens normais (não afetadas pela mudança)
  • ✅ Verificado que stubs não são salvos no banco
  • ✅ Verificado que mensagens reais são salvas corretamente

✅ Checklist

  • My code follows the project's style guidelines
  • I have performed a self-review of my code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have manually tested my changes thoroughly
  • I have verified the changes work with different scenarios
  • Any dependent changes have been merged and published

📝 Additional Notes

O que é "Message absent from node"?

É um placeholder/stub que o WhatsApp envia quando:

  • 🔐 A mensagem está criptografada mas o dispositivo ainda não tem as chaves necessárias
  • 📡 Sincronização de sessão - O WhatsApp está negociando as chaves de criptografia
  • ⏳ Mensagem pendente de descriptografia - O conteúdo real ainda não foi descriptografado

Impacto da Mudança

  • Positivo: Mensagens que antes eram perdidas agora são salvas corretamente
  • Sem impacto negativo: Stubs continuam sendo descartados (não são salvos)
  • Performance: Mudança mínima, apenas uma verificação adicional antes de adicionar ao cache

Summary by Sourcery

Bug Fixes:

  • Exclude WhatsApp stub messages marked as 'Message absent from node' from the duplicate-message cache to prevent loss of the subsequent real message.

Mensagens do WhatsApp estavam sendo perdidas e não eram salvas no banco de dados, especialmente mensagens de canais/newsletters (@lid) e mensagens com criptografia complexa.

O WhatsApp/Baileys envia mensagens criptografadas em duas etapas:

1. Primeiro: Envia um stub (placeholder) com messageStubParameters: ['Message absent from node'] enquanto descriptografa a mensagem

2. Depois: Envia a mensagem real com o conteúdo descriptografado

O problema ocorria porque:

- O stub chegava primeiro e era adicionado ao cache de mensagens duplicadas

- O stub era descartado (corretamente) por não ter conteúdo (!received?.message)

- A mensagem real chegava depois, mas era ignorada como duplicata porque o ID já estava no cache

- Resultado: mensagem nunca era salva no banco de dados

Solução:

- Detectar stubs do WhatsApp através de messageStubParameters contendo 'Message absent from node'

- Não adicionar stubs ao cache de mensagens duplicadas

- Permitir que a mensagem real seja processada quando chegar

- Manter o descarte do stub para evitar salvar placeholders vazios
@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Nov 26, 2025

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Extends the WhatsApp Baileys decryption error-handling logic to recognize Baileys placeholder stub messages ("Message absent from node") so they are treated as transient decryption issues and not added to the duplicate-message cache, preventing loss of the subsequent real message.

Sequence diagram for WhatsApp stub placeholder handling in Baileys

sequenceDiagram
    participant WhatsAppServer
    participant BaileysLibrary
    participant BaileysStartupService
    participant DuplicateMessageCache
    participant Database

    rect rgb(235, 245, 255)
        Note over WhatsAppServer,BaileysStartupService: Stub placeholder message (Message absent from node)
        WhatsAppServer->>BaileysLibrary: sendEncryptedStubMessage
        BaileysLibrary->>BaileysStartupService: onMessage(stubWithMessageStubParameters)
        BaileysStartupService->>BaileysStartupService: detectStub(messageStubParameters contains Message_absent_from_node)
        BaileysStartupService-->>DuplicateMessageCache: doNotAddStubToCache
        BaileysStartupService-->>Database: doNotPersistStub
    end

    rect rgb(235, 255, 235)
        Note over WhatsAppServer,BaileysStartupService: Real decrypted message arrives later with same message ID
        WhatsAppServer->>BaileysLibrary: sendDecryptedMessage
        BaileysLibrary->>BaileysStartupService: onMessage(realMessage)
        BaileysStartupService->>DuplicateMessageCache: isDuplicate(messageId)?
        DuplicateMessageCache-->>BaileysStartupService: notFound
        BaileysStartupService->>Database: saveMessage(realMessage)
        BaileysStartupService->>DuplicateMessageCache: addMessageIdToCache
    end
Loading

Class diagram for updated BaileysStartupService decryption error handling

classDiagram
    class ChannelStartupService {
    }

    class BaileysStartupService {
        - duplicateMessageCache
        + handleIncomingMessage(rawMessage)
        + isDecryptionStub(messageStubParameters) bool
        + shouldSkipDuplicateCache(messageStubParameters) bool
    }

    class DuplicateMessageCache {
        + has(messageId) bool
        + add(messageId)
    }

    class IncomingMessage {
        + id
        + message
        + messageStubParameters
    }

    ChannelStartupService <|-- BaileysStartupService
    BaileysStartupService --> DuplicateMessageCache
    BaileysStartupService --> IncomingMessage

    %% Highlight of logic change
    BaileysStartupService : isDecryptionStub(messageStubParameters) checks for
    BaileysStartupService : 'Invalid PreKey ID'
    BaileysStartupService : 'No session record'
    BaileysStartupService : 'No session found to decrypt message'
    BaileysStartupService : 'Message absent from node'  %% newly added

    BaileysStartupService : if isDecryptionStub then
    BaileysStartupService :   skip adding to duplicateMessageCache
    BaileysStartupService :   do not persist placeholder message
    BaileysStartupService : else
    BaileysStartupService :   normal duplicate check and persistence flow
Loading

File-Level Changes

Change Details Files
Treat WhatsApp "Message absent from node" placeholders as decryption-related stubs that should be ignored without affecting duplicate-message detection.
  • Extend the list of Baileys decryption/session error markers to include the "Message absent from node" stub identifier in the error-parameter matching logic.
  • Ensure that messages flagged with this marker are handled like other transient decryption issues, avoiding their insertion into duplicate-message caches so the later real message can be processed and persisted.
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

Possibly linked issues


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
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 there - I've reviewed your changes - here's some feedback:

  • Since this list of Baileys/WhatsApp stub error substrings is growing, consider extracting it to a named constant (e.g., WHATSAPP_STUB_MESSAGE_ERRORS) with a short comment explaining the semantics, to make future additions and maintenance clearer.
  • If Baileys or WhatsApp ever localize or slightly change these stub messages, the current includes-based matching on fixed English strings may fail silently; it might be worth centralizing this logic with tests or adding a brief note about the dependency on these exact message texts.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Since this list of Baileys/WhatsApp stub error substrings is growing, consider extracting it to a named constant (e.g., `WHATSAPP_STUB_MESSAGE_ERRORS`) with a short comment explaining the semantics, to make future additions and maintenance clearer.
- If Baileys or WhatsApp ever localize or slightly change these stub messages, the current `includes`-based matching on fixed English strings may fail silently; it might be worth centralizing this logic with tests or adding a brief note about the dependency on these exact message texts.

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