Skip to content

fix(chat): normalize @lid JIDs to @s.whatsapp.net and include Contact table entries in fetchChats - #2703

Open
xstudioproductions wants to merge 1 commit into
evolution-foundation:mainfrom
xstudioproductions:fix/lid-jid-fetchchats-normalization
Open

fix(chat): normalize @lid JIDs to @s.whatsapp.net and include Contact table entries in fetchChats#2703
xstudioproductions wants to merge 1 commit into
evolution-foundation:mainfrom
xstudioproductions:fix/lid-jid-fetchchats-normalization

Conversation

@xstudioproductions

@xstudioproductions xstudioproductions commented Aug 23, 2026

Copy link
Copy Markdown

Description

This PR resolves an issue where personal 1-on-1 chats and contacts fail to render in the Evolution Manager UI due to WhatsApp Multi-Device @lid (Linked Identity) JIDs and unlinked "Contact" table records.

🐛 Problem

  1. @lid JID Filtering in Frontend: WhatsApp Multi-Device assigns @lid domain JIDs (e.g., 173452640125135@lid) to incoming messages and chats. However, the Evolution Manager UI filters personal contacts strictly checking if remoteJid ends with @s.whatsapp.net. As a result, all @lid personal chats are hidden from the Contatos tab in the UI.
  2. Missing Contact Records: fetchChats previously queried solely from the "Message" table. Contacts saved in the "Contact" table without message history were excluded from the chat sidebar.
  3. PostgreSQL Type Mismatch: Combining raw SQL subqueries required explicit PostgreSQL type casting for JSONB and Enum types.

🛠️ Solution

  1. JID Normalization: Added JID normalization in src/api/services/channel.service.ts (fetchChats) to format @lid suffixes to @s.whatsapp.net in the API output payload, ensuring full compatibility with Evolution Manager UI.
  2. CTE UNION Query: Refactored fetchChats SQL query into Common Table Expressions (msg_chats & contact_chats) joined by UNION ALL to include both active message threads and saved address book contacts.
  3. Explicit Type Casting: Applied explicit PostgreSQL type casting (NULL::jsonb, NULL::text, NULL::integer) to ensure schema compatibility across PostgreSQL database instances.

🧪 How Has This Been Tested?

  • Verified POST /chat/findChats/:instanceName returns all 1-on-1 personal contacts with @s.whatsapp.net JIDs.
  • Tested on Evolution Manager UI (v2.3.7): all personal contacts, group chats (@g.us), push names, profile pictures, and last message previews are displayed and selectable.
  • Confirmed backward compatibility with sending text messages and webhook triggers.

Summary by Sourcery

Ensure personal chats and saved contacts are consistently returned and displayed by normalizing JIDs and expanding chat retrieval beyond message history.

Bug Fixes:

  • Normalize WhatsApp @lid personal chat identifiers to standard @s.whatsapp.net JIDs so contacts render correctly in the manager UI.
  • Include saved contacts without message history in fetched chats, while preserving message-backed conversations and defaulting missing metadata appropriately.

Enhancements:

  • Refactor chat retrieval to combine message conversations and address-book contacts with duplicate chat consolidation and PostgreSQL-compatible type handling.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Sorry @xstudioproductions, you have reached your weekly rate limit of 500000 diff characters.

Please try again later or upgrade to continue using Sourcery

@sourcery-ai

sourcery-ai Bot commented Aug 23, 2026

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Refactors fetchChats to union message- and contact-based chats, normalizes @lid JIDs to @s.whatsapp.net in the API response, and adds PostgreSQL-safe type casting and defaults to ensure consistent chat rendering in the Evolution Manager UI.

Flow diagram for unified chat fetching and JID normalization

flowchart TD
    A[fetchChats] --> B[msg_chats CTE]
    A --> C[contact_chats CTE]
    B --> D[combined_chats UNION ALL]
    C --> D
    D --> E[Deduplicate by remoteJid]
    E --> F[Normalize @lid to @s.whatsapp.net]
    F --> G[Return chats to Evolution Manager]
Loading

File-Level Changes

Change Details Files
Refactor fetchChats SQL into CTEs that combine message-derived chats with contact-only chats, with explicit type casting and stable ordering.
  • Rename rankedMessages CTE to msg_chats and adjust selected columns (chatName, lastMessageSource casting).
  • Add contact_chats CTE that selects contacts (including those without messages), left-joining chats and providing NULL::jsonb/text/integer placeholders for missing last-message fields.
  • Create combined_chats CTE that UNION ALLs msg_chats and contact_chats, then select DISTINCT ON remoteJid with ordering by updatedAt for deterministic latest entry.
  • Apply COALESCE for unreadMessages and windowActive logic based on chat window timing.
src/api/services/channel.service.ts
Normalize @lid JIDs and improve response shaping in the fetchChats mapping logic.
  • Introduce finalRemoteJid variable and convert remoteJid values ending with @lid to @s.whatsapp.net before returning them in the API payload.
  • Update pushName fallback to use the normalized JID local part or a default 'Contato' when pushName is absent.
  • Ensure unreadCount defaults to 0 when unreadMessages is null or undefined.
  • Preserve lastMessage mapping while using cleanMessageData helper as before.
src/api/services/channel.service.ts

Possibly linked issues

  • #unknown: The PR normalizes @lid JIDs in fetchChats, directly addressing hidden incoming chats in the Manager UI.
  • #META: PR directly fixes one tracked @lid symptom by normalizing fetchChats JIDs and restoring affected contact visibility.

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

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