Skip to content

Conversation

@JefersonRamos
Copy link
Contributor

@JefersonRamos JefersonRamos commented Jan 14, 2026

…essage DTO

📋 Description

Em cenários de alto volume de envio de mensagens via Evolution API, chamadas HTTP síncronas podem sofrer timeout, fazendo com que o backend do integrador perca a referência do msg.key.id, apesar da mensagem já ter sido gerada/enviada pelo Baileys.

Como o messageId é gerado localmente pelo Baileys antes do envio, adotei uma abordagem que permite pré-gerar esse identificador no mesmo contexto da sessão, eliminando a dependência da resposta HTTP para rastreamento.

Criada uma nova API interna:

POST /baileys/generateMessageID/{instance}

  • Essa API:

    • Executa dentro do processo do Baileys
    • Gera o messageId usando generateMessageIDV2(sock.user?.id)
    • Retorna um messageId válido, único e compatível com o protocolo WhatsApp
  • Ajustado o fluxo de envio para:

    • Aceitar messageId opcional via options
    • Utilizar o messageId fornecido quando presente
    • Manter o comportamento padrão do Baileys (geração automática) quando não informado

Benefícios:

  • Elimina perda de referência em caso de timeout HTTP
  • Permite persistir o messageId antes do envio
  • Mantém ACK / READ / DELIVERY totalmente compatíveis
  • Não altera o comportamento padrão quando o override não é usado
  • Não impacta a fila de jobs nem a integridade da sessão

Observações importantes:

  • Cada messageId deve ser usado uma única vez
  • O ID deve ser gerado e utilizado imediatamente, na mesma sessão ativa
  • IDs não utilizados ou gerados antes de reconnect devem ser descartados
  • O uso concorrente deve respeitar a serialização por instância

🔗 Related Issue

Closes #(issue_number)

🧪 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 (if applicable)

📸 Screenshots (if applicable)

✅ 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

Summary by Sourcery

Add support for externally supplied WhatsApp message IDs and expose an internal API to pre-generate protocol-compatible message IDs per instance.

New Features:

  • Expose a generateMessageID endpoint on the Baileys router/controller to return a Baileys-generated WhatsApp message ID for a given instance.
  • Allow send message flows in Baileys and Evolution services to accept an optional messageId from options/DTO metadata and use it when present instead of always generating a new ID.

Enhancements:

  • Propagate messageId through sendMessage DTO options and metadata to keep message tracking consistent across different WhatsApp integration paths.

@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Jan 14, 2026

Reviewer's Guide

Adds support for externally generated WhatsApp/Baileys message IDs, including a new internal API endpoint to pre-generate Baileys-compatible message IDs and wiring the optional messageId through DTOs, controllers, services, and the send pipeline so it overrides default ID generation when provided.

Sequence diagram for the new generateMessageID API flow

sequenceDiagram
  actor Integrator
  participant HTTP_API as HTTP_API
  participant BaileysRouter as BaileysRouter
  participant BaileysController as BaileysController
  participant BaileysStartupService as BaileysStartupService
  participant BaileysSock as BaileysSock

  Integrator->>HTTP_API: GET /baileys/generateMessageID/{instance}
  HTTP_API->>BaileysRouter: routeRequest
  BaileysRouter->>BaileysController: generateMessageID(instanceDto)
  BaileysController->>BaileysStartupService: generateMessageID()
  BaileysStartupService->>BaileysSock: generateMessageIDV2(userId)
  BaileysSock-->>BaileysStartupService: messageId
  BaileysStartupService-->>BaileysController: { id: messageId }
  BaileysController-->>BaileysRouter: { id: messageId }
  BaileysRouter-->>HTTP_API: HTTP 200 { id: messageId }
  HTTP_API-->>Integrator: returns preGenerated messageId
Loading

Sequence diagram for sending messages with optional external messageId

sequenceDiagram
  actor Integrator
  participant EvolutionAPI as EvolutionAPI
  participant EvolutionStartupService as EvolutionStartupService
  participant BaileysStartupService as BaileysStartupService
  participant BaileysSock as BaileysSock
  participant WhatsAppServer as WhatsAppServer

  Integrator->>EvolutionAPI: POST /sendMessage with options.messageId?
  EvolutionAPI->>EvolutionStartupService: sendMessage(sender, message, options)
  EvolutionStartupService->>EvolutionStartupService: messageId = options.messageId || v4()
  EvolutionStartupService->>BaileysStartupService: sendMessage(sender, message, optionsWithMessageId)
  BaileysStartupService->>BaileysStartupService: use options.messageId when calling sock.sendMessage
  BaileysStartupService->>BaileysSock: sendMessage(jid, content, options.messageId)
  BaileysSock->>WhatsAppServer: sendMessage with provided messageId
  WhatsAppServer-->>BaileysSock: ack using same messageId
  BaileysSock-->>BaileysStartupService: send result
  BaileysStartupService-->>EvolutionStartupService: send result
  EvolutionStartupService-->>Integrator: HTTP 200 with tracking using messageId
Loading

Updated class diagram for Baileys and Evolution messaging structures

classDiagram
  class BaileysStartupService {
    - client
    + sendMessage(sender, message, options, isIntegration)
    - generateMessageID() Promise
  }

  class EvolutionStartupService {
    + sendMessage(sender, message, options, file, isIntegration)
    - createAudioMessage(sender, options)
  }

  class BaileysController {
    - waMonitor
    + baileysOnWhatsapp(jid)
    + generateMessageID(instanceDto)
    + profilePictureUrl(instanceDto, body)
  }

  class Options {
    + delay: number
    + presence: string
    + linkPreview: boolean
    + mentionsEveryOne: boolean
    + mentioned: string[]
    + webhookUrl: string
    + messageId: string
  }

  class Metadata {
    + delay: number
    + presence: string
    + linkPreview: boolean
    + mentionsEveryOne: boolean
    + mentioned: string[]
    + encoding: boolean
    + notConvertSticker: boolean
    + messageId: string
  }

  class SendTextDto {
  }

  class InstanceDto {
    + instanceName: string
  }

  class WaMonitor {
    + waInstances: Map
  }

  class BaileysSock {
    + user: any
    + generateMessageIDV2(userId)
    + sendMessage(jid, content, messageId)
  }

  Metadata <|-- SendTextDto
  Options o-- EvolutionStartupService
  Options o-- BaileysStartupService
  BaileysController o-- WaMonitor
  WaMonitor o-- BaileysStartupService
  BaileysStartupService o-- BaileysSock
  BaileysController ..> InstanceDto
  EvolutionStartupService ..> Options
  BaileysStartupService ..> Options
  Metadata ..> Options
Loading

File-Level Changes

Change Details Files
Introduce internal API and service method to generate Baileys-compatible message IDs per instance.
  • Add private generateMessageID method on BaileysStartupService that uses generateMessageIDV2 with the current client user id and returns an object containing the id
  • Expose generateMessageID via BaileysController, resolving the correct instance from waMonitor and delegating to the service method
  • Register a new GET /baileys/generateMessageID/{instance} route in BaileysRouter that validates the instance and calls the controller, returning the generated id
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
src/api/integrations/channel/whatsapp/baileys.controller.ts
src/api/integrations/channel/whatsapp/baileys.router.ts
Allow callers to provide an optional messageId that is used for message sending instead of auto-generated IDs.
  • Extend Options and Metadata DTOs to include an optional messageId field so clients can pass a custom identifier
  • Thread messageId from incoming data into the options/metadata objects used by Baileys and Evolution send flows
  • Update Baileys sendMessage calls to pass options.messageId instead of null where the message key id is expected
  • Update EvolutionStartupService to honor options.messageId when choosing the messageId, falling back to a UUID v4 when not provided
src/api/dto/sendMessage.dto.ts
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
src/api/integrations/channel/evolution/evolution.channel.service.ts

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 - I've found 3 issues, and left some high level feedback:

  • In sendMessage, the change from null to options.messageId assumes options is always defined; consider using options?.messageId (or a default) to avoid runtime errors when options is undefined.
  • The new generateMessageID method is declared private in BaileysStartupService but is invoked from BaileysController via instance.generateMessageID(); either make it public or expose it via a dedicated public wrapper to avoid TypeScript access violations and clarify its intended usage.
  • In generateMessageID, you’re calling generateMessageIDV2(this.client.user?.id) without checking that this.client.user?.id exists; adding a guard or clear error when the instance is not connected would make the behavior more predictable.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `sendMessage`, the change from `null` to `options.messageId` assumes `options` is always defined; consider using `options?.messageId` (or a default) to avoid runtime errors when `options` is undefined.
- The new `generateMessageID` method is declared `private` in `BaileysStartupService` but is invoked from `BaileysController` via `instance.generateMessageID()`; either make it public or expose it via a dedicated public wrapper to avoid TypeScript access violations and clarify its intended usage.
- In `generateMessageID`, you’re calling `generateMessageIDV2(this.client.user?.id)` without checking that `this.client.user?.id` exists; adding a guard or clear error when the instance is not connected would make the behavior more predictable.

## Individual Comments

### Comment 1
<location> `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:1983-1988` </location>
<code_context>
     }
   }

+  private async generateMessageID() {
+
+    return {
+      id: generateMessageIDV2(this.client.user?.id)
+    };
+  }
</code_context>

<issue_to_address>
**suggestion:** Consider making `generateMessageID` synchronous and/or public if it's part of the controller surface.

This method doesn’t `await` anything, so it can be made synchronous to avoid unnecessary promise wrapping. Since it’s called externally via `instance.generateMessageID(...)`, treating it as `public` would also better reflect its actual usage and improve typings and maintainability.

```suggestion
  public generateMessageID() {
    return {
      id: generateMessageIDV2(this.client.user?.id)
    };
  }
```
</issue_to_address>

### Comment 2
<location> `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:2253` </location>
<code_context>
           linkPreview,
           quoted,
-          null,
+          options.messageId,
           group?.ephemeralDuration,
           // group?.participants,
</code_context>

<issue_to_address>
**issue (bug_risk):** Passing `undefined` instead of `null` for `messageId` may subtly change behavior; consider preserving the old null semantics.

To keep the old behavior while allowing explicit IDs, you can pass `options?.messageId ?? null` here (and in the other similar call).
</issue_to_address>

### Comment 3
<location> `src/api/integrations/channel/evolution/evolution.channel.service.ts:321` </location>
<code_context>
       let audioFile;

-      const messageId = v4();
+      const messageId = options?.messageId || v4();

       let messageRaw: any;
</code_context>

<issue_to_address>
**suggestion:** Prefer nullish coalescing over `||` when choosing between provided and generated message IDs.

`options?.messageId || v4()` will replace any falsy `messageId` (like an empty string) with a new ID. If the intent is to only fall back when `messageId` is `null` or `undefined`, use `const messageId = options?.messageId ?? v4();` to preserve valid-but-falsy IDs.

```suggestion
      const messageId = options?.messageId ?? v4();
```
</issue_to_address>

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.

JefersonRamos and others added 5 commits January 14, 2026 11:35
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
…ce.ts

Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
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