Skip to content

Conversation

@JefersonRamos
Copy link
Contributor

@JefersonRamos JefersonRamos commented Oct 27, 2025

📋 Description

Esse erro acontece porque o Node.js (a partir da versão 18) usa o Undici como implementação nativa de fetch(), e o Undici não aceita mais objetos agent tradicionais (como os criados por https-proxy-agent ou socks-proxy-agent).
Ele espera objetos compatíveis com a interface moderna Dispatcher, que possuem o método dispatch().

Ou seja, o Baileys estava recebendo um tipo de agente incompatível com o novo sistema de rede do Node.

Foi criada uma nova função makeProxyAgentUndici() para gerar agentes de proxy compatíveis com o Undici, mantendo a versão antiga (makeProxyAgent()) inalterada para compatibilidade com bibliotecas como Axios.

A nova função substitui os antigos HttpsProxyAgent e SocksProxyAgent por ProxyAgent da biblioteca undici, garantindo compatibilidade total com o Baileys e com qualquer uso de fetch() moderno.

🔗 Related Issue

Closes #2117

🧪 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

O protocolo socks é automaticamente normalizado para socks5, evitando erro de usuários que informem apenas "socks"

Summary by Sourcery

Introduce Undici-compatible proxy handling by adding makeProxyAgentUndici, updating BaileysStartupService to use it for fetchAgent, and adding undici to dependencies to ensure compatibility with Node.js 18+ native fetch

New Features:

  • Add makeProxyAgentUndici function to create Dispatcher-compatible proxy agents using undici

Bug Fixes:

  • Fix incompatible proxy agents in Baileys with Node.js 18+ native fetch

Enhancements:

  • Normalize 'socks' protocol to 'socks5' when constructing proxy URLs

Build:

  • Add undici dependency to enable ProxyAgent

…ici como implementação nativa de fetch(), e o Undici não aceita mais objetos agent tradicionais (como os criados por https-proxy-agent ou socks-proxy-agent).

Ele espera objetos compatíveis com a interface moderna Dispatcher, que possuem o método dispatch().

Ou seja, o Baileys estava recebendo um tipo de agente incompatível com o novo sistema de rede do Node.

Foi criada uma nova função makeProxyAgentUndici() para gerar agentes de proxy compatíveis com o Undici, mantendo a versão antiga (makeProxyAgent()) inalterada para compatibilidade com bibliotecas como Axios.

A nova função substitui os antigos HttpsProxyAgent e SocksProxyAgent por ProxyAgent da biblioteca undici, garantindo compatibilidade total com o Baileys e com qualquer uso de fetch() moderno.
@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Oct 27, 2025

Reviewer's Guide

This PR adds a new Undici-compatible proxy agent generator and updates the WhatsApp Baileys integration to use it for fetchAgent, ensuring compatibility with Node.js 18+ native fetch while preserving legacy proxy support and updating dependencies.

Sequence diagram for BaileysStartupService proxy agent selection (Node.js 18+ fetch compatibility)

sequenceDiagram
    participant BaileysStartupService
    participant ProxyConfig
    participant makeProxyAgent
    participant makeProxyAgentUndici
    participant ProxyAgent (undici)
    BaileysStartupService->>ProxyConfig: Get proxy configuration
    alt Using legacy agent
        BaileysStartupService->>makeProxyAgent: Create agent for Axios/legacy
        makeProxyAgent-->>BaileysStartupService: Return HttpsProxyAgent/SocksProxyAgent
    end
    alt Using fetchAgent (Node.js 18+)
        BaileysStartupService->>makeProxyAgentUndici: Create agent for fetch
        makeProxyAgentUndici->>ProxyAgent (undici): Instantiate ProxyAgent
        ProxyAgent (undici)-->>BaileysStartupService: Return ProxyAgent
    end
Loading

ER diagram for proxy configuration normalization

erDiagram
    PROXY {
        string host
        string protocol
        string username
        string password
        int port
    }
    PROXY ||--o{ PROXY_URL : normalizes
    PROXY_URL {
        string url
    }
Loading

Class diagram for updated proxy agent creation utilities

classDiagram
    class Proxy {
        host: string
        password?: string
        port?: number
        protocol: string
        username?: string
    }
    class HttpsProxyAgent
    class SocksProxyAgent
    class ProxyAgent
    class makeProxyAgent {
        +HttpsProxyAgent makeProxyAgent(proxy: Proxy | string)
    }
    class makeProxyAgentUndici {
        +ProxyAgent makeProxyAgentUndici(proxy: Proxy | string)
    }
    makeProxyAgent --|> HttpsProxyAgent
    makeProxyAgent --|> SocksProxyAgent
    makeProxyAgentUndici --|> ProxyAgent
    Proxy <.. makeProxyAgent
    Proxy <.. makeProxyAgentUndici
Loading

File-Level Changes

Change Details Files
Introduce makeProxyAgentUndici to generate modern Dispatcher-compatible proxy agents
  • import ProxyAgent from undici
  • parse proxy input (string or object) and normalize protocol (socks -> socks5)
  • build proxy URL with optional authentication
  • implement switch-case for supported protocols and throw on unsupported
src/utils/makeProxyAgent.ts
Replace fetchAgent usage in Baileys startup service with the new Undici agent
  • use makeProxyAgentUndici for fetchAgent in HTTP proxy setup
  • apply makeProxyAgentUndici in authenticated proxy section
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
Add undici as a new dependency for ProxyAgent support
  • add "undici": "^7.16.0" to package.json dependencies
package.json

Assessment against linked issues

Issue Objective Addressed Explanation
#2117 Fix the bug where audio messages sent from Chatwoot to Evolution API are not delivered to WhatsApp due to media upload errors (e.g., ENOENT, 'Media upload failed on all hosts').
#2117 Ensure compatibility with Node.js 18+ networking (Undici) for proxy agents used in Baileys and fetch(), so that media uploads (including audio) work correctly.

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 and they look great!

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

## Individual Comments

### Comment 1
<location> `src/utils/makeProxyAgent.ts:58` </location>
<code_context>
+    proxyUrl = proxy
+  } else {
+    const { host, password, port, protocol: proto, username } = proxy
+    protocol = proto.replace(':', '')
+
+    if (protocol === 'socks') {
</code_context>

<issue_to_address>
**issue:** Potential issue if 'proto' is undefined in Proxy object.

Add a check or default value for 'proto' to prevent errors when it is undefined.
</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 JefersonRamos changed the title Esse erro acontece porque o Node.js (a partir da versão 18) usa o Und… "Media upload failed on all hosts" utilizando proxy Oct 27, 2025
@JefersonRamos JefersonRamos changed the title "Media upload failed on all hosts" utilizando proxy fix: "Media upload failed on all hosts" utilizando proxy Oct 27, 2025
@renansko-vilela
Copy link

@suissa quando tempo até a verificação da PR?

@MattCarneiro
Copy link

MattCarneiro commented Oct 29, 2025

EDIT: aqui deu certo. mt obrigado

@DavidsonGomes DavidsonGomes merged commit df20c5f into EvolutionAPI:main Oct 29, 2025
1 check passed
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.

Chatwoot e Evolution 2.3.6 - Envio de áudio do Chatwoot para Evolution dá erro!

4 participants