fix: resolve @lid (LID) to phone number in messages handlers and fix …
…QR code loop
-
messages.upsert: mutate received.key.remoteJid to remoteJidAlt when @lid is detected, ensuring prepareMessage, chatbot emit, contact upsert and all downstream uses receive the correct @s.whatsapp.net JID instead of the LID identifier
-
messages.update: after finding the stored message by key.id, resolve @lid using remoteJidAlt (fork field) or findMessage.key.remoteJid as fallback; applies to DB status update, webhook to N8N, messageUpdate record and chat unread counter
-
connectionUpdate: guard against infinite QR code regeneration loop when connection closes before QR is scanned (no wuid, no statusCode)
-
Dockerfile: use tsup directly instead of npm run build to bypass pre-existing tsc type error on terminateCall; add openssl/libc6-compat to Alpine final stage for Prisma compatibility
-
docker-compose.yaml: switch from remote image to local build so fixes persist across container recreations
📋 Description
🔗 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
Handle WhatsApp @lid JIDs consistently in message handlers and prevent QR reconnect loops, while updating container build configuration for local builds and Prisma compatibility.
Bug Fixes:
- Normalize incoming and updated WhatsApp message JIDs by resolving @lid identifiers to the corresponding @s.whatsapp.net JIDs so downstream processing uses the correct phone-based identifier.
- Prevent infinite QR code regeneration loops by skipping automatic reconnect when the connection closes before a QR is scanned and no disconnect status code is available.
Build:
- Change the Docker build to run tsup directly and add required system libraries for Prisma compatibility in the Alpine final image.
Deployment:
- Switch docker-compose to build the API image locally instead of pulling a remote image and ensure core services are configured to restart automatically.
Chores:
- Adjust environment and timezone settings in container configuration to align with the updated deployment setup.
Reviewer's Guide
Updates WhatsApp Baileys service to normalize @lid JIDs to standard phone-number JIDs across message handlers, adds a connection guard to prevent infinite QR regeneration loops, and adjusts Docker/Docker Compose setup to build locally with tsup and additional Alpine dependencies for Prisma.
Sequence diagram for resolving @lid JID on messages.upsert
sequenceDiagram
actor WhatsAppServer
participant BaileysStartupService
participant MessagePreparer
participant Chatbot
participant ContactStore
WhatsAppServer->>BaileysStartupService: messages.upsert(received)
BaileysStartupService->>BaileysStartupService: normalize messageTimestamp
alt received.key.remoteJid contains @lid and received.key.remoteJidAlt exists
BaileysStartupService->>BaileysStartupService: set received.key.remoteJid = received.key.remoteJidAlt
end
BaileysStartupService->>BaileysStartupService: check settings.groupsIgnore and @g.us
alt not ignored
BaileysStartupService->>MessagePreparer: prepareMessage(received)
MessagePreparer-->>BaileysStartupService: preparedMessage
BaileysStartupService->>Chatbot: emit message event with normalized remoteJid
BaileysStartupService->>ContactStore: upsert contact with normalized remoteJid
end
Sequence diagram for resolving @lid JID on messages.update
sequenceDiagram
actor WhatsAppServer
participant BaileysStartupService
participant MessageStore
participant Webhook
participant ChatUnreadCounter
WhatsAppServer->>BaileysStartupService: messages.update([{ key, update }])
BaileysStartupService->>MessageStore: findMessageByKeyId(key.id)
MessageStore-->>BaileysStartupService: findMessage
alt key.remoteJid contains @lid
BaileysStartupService->>BaileysStartupService: resolvedRemoteJid = key.remoteJidAlt or findMessage.key.remoteJid or key.remoteJid
else
BaileysStartupService->>BaileysStartupService: resolvedRemoteJid = key.remoteJid
end
alt update.message is null and update.status is undefined
BaileysStartupService->>Webhook: sendDataWebhook(MESSAGES_DELETE, message with resolvedRemoteJid)
else update.status is defined and changed
alt not key.fromMe and resolvedRemoteJid exists
BaileysStartupService->>ChatUnreadCounter: mark chat read for resolvedRemoteJid
alt status is READ
BaileysStartupService->>BaileysStartupService: updateMessagesReadedByTimestamp(resolvedRemoteJid, findMessage.messageTimestamp)
end
end
BaileysStartupService->>Webhook: sendDataWebhook(MESSAGES_UPDATE, message with resolvedRemoteJid)
end
Updated class diagram for BaileysStartupService JID normalization and connection guard
classDiagram
class ChannelStartupService {
}
class BaileysStartupService {
- instance
- instanceId
- logger
+ connectionUpdate(connection, lastDisconnect)
+ onMessagesUpsert(received)
+ onMessagesUpdate(key, update)
+ sendDataWebhook(event, payload)
+ updateMessagesReadedByTimestamp(remoteJid, messageTimestamp)
}
ChannelStartupService <|-- BaileysStartupService
class ConnectionUpdateLogic {
+ shouldReconnect(instance, statusCode) bool
}
class JidNormalizer {
+ normalizeRemoteJidOnUpsert(received) string
+ resolveRemoteJidOnUpdate(key, findMessage) string
}
BaileysStartupService ..> ConnectionUpdateLogic : uses
BaileysStartupService ..> JidNormalizer : uses
Flow diagram for connectionUpdate QR loop guard
flowchart TD
A[connectionUpdate receives connection close] --> B[Read lastDisconnect error statusCode]
B --> C{instance.wuid exists?}
C -->|yes| D[Proceed to reconnect evaluation]
C -->|no| E{statusCode exists?}
E -->|no| F[Log and return without reconnect to prevent QR loop]
E -->|yes| D
D --> G[Check codesToNotReconnect]
G --> H{shouldReconnect?}
H -->|yes| I[Reconnect to WhatsApp]
H -->|no| J[Do not reconnect]
File-Level Changes
| Change | Details | Files |
|---|---|---|
| Normalize @lid JIDs to standard @s.whatsapp.net JIDs in message upsert and update flows so downstream logic sees consistent identifiers. |
|
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts |
| Prevent infinite QR code regeneration when the connection closes before QR is scanned. |
|
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts |
| Adjust Docker and Docker Compose to build the image locally with tsup and ensure runtime compatibility on Alpine. |
|
Dockerfiledocker-compose.yaml |
Possibly linked issues
- #[Bug] Typebot fails to send messages to users with LID - BadRequestException jidOptions.exists false: PR normalizes @lid to @s.whatsapp.net in handlers, fixing chatbot replies and JID issues described in the LID bug.
Tips and commands
Interacting with Sourcery
- Trigger a new review: Comment
@sourcery-ai reviewon 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 issueto create an issue from it. - Generate a pull request title: Write
@sourcery-aianywhere in the pull request title to generate a title at any time. You can also comment@sourcery-ai titleon the pull request to (re-)generate the title at any time. - Generate a pull request summary: Write
@sourcery-ai summaryanywhere in the pull request body to generate a PR summary at any time exactly where you want it. You can also comment@sourcery-ai summaryon the pull request to (re-)generate the summary at any time. - Generate reviewer's guide: Comment
@sourcery-ai guideon the pull request to (re-)generate the reviewer's guide at any time. - Resolve all Sourcery comments: Comment
@sourcery-ai resolveon 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 dismisson 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 reviewto 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
- Contact our support team for questions or feedback.
- Visit our documentation for detailed guides and information.
- Keep in touch with the Sourcery team by following us on X/Twitter, LinkedIn or GitHub.
why change the docker compose and docker file?
Hi! As part of our PR triage, we noticed the Check Code Quality workflow has not run on this PR (it requires maintainer approval for first-time external contributors, which we've now enabled).
To trigger CI:
- Push any commit to your branch (a rebase against
developis ideal — base was adjusted on our side frommaintodevelop) - Or close + reopen this PR
Once CI runs and is green I'll re-review for merge. Thanks!
Obrigado pelo trabalho de tipar o tratamento de @lid — direção correta, mas o PR no estado atual tem 3 problemas que precisam ser endereçados:
-
PR mistura 3 propósitos: (a) LID resolution + helpers tipados, (b) guard contra loop de QR no
connectionUpdate, (c) Dockerfile/docker-compose. Cada um deveria ser um PR separado — fica difícil revisar e mais arriscado mergear. -
Overlap direto com a base atual — o branch
developjá tem swap recíproco@lid → remoteJidAltinline nas linhas 1650-1657 dowhatsapp.baileys.service.ts, incluindo o set deaddressingMode = 'pn'. Este PR aplica a resolução mais cedo (antes do filtro de grupos) mas NÃO replica o swap recíproco nem oaddressingMode. Mergear como está pode regredir comportamento já presente ou criar duplicação. Precisa rebase + unificação com a lógica existente. -
Conflito com PR #2544 (
fix(whatsapp): allow @lid contacts to bypass onWhatsApp validation) — ambos tocam o mesmo bloco de validação. Sugiro aguardar o merge do #2544 primeiro e então reavaliar este.
Pontos adicionais:
- [ ] Reverter mudança de
TZ=America/Sao_Paulo→America/Fortalezano Dockerfile (não relacionado ao escopo) - [ ]
tsupdireto no Dockerfile bypassa o type-check do TS — workaround para erro emterminateCall— esconde problema. Resolver o erro de tipo ou ao menos documentar - [ ] Manter a substituição da senha hardcoded em compose (
POSTGRES_PASSWORD=${POSTGRES_PASSWORD}) — isso é positivo, vai em PR separado
Reabrir depois do rebase e da divisão em 3 PRs focados.
Olá @jeandgardany, obrigado pela contribuição. O fix de @lid em si é legítimo e endereça um problema real (rastreado em #1872). Porém não posso mergear essa PR como está porque ela vai muito além do que o título descreve.
Bloqueantes críticos
-
Breaking change não declarado: a PR remove
SEND_MESSAGE_UPDATE = 'send.message.update'do enumEventsemsrc/api/types/wa.types.ts:42. Isso quebra silenciosamente qualquer consumer downstream que referencia essa constante. Se há motivo para remover, precisa ir em PR separada com aviso. -
Dockerfile downgrade Node 24 → 20 + troca de
npm cipornpm install -f. O próprio commit body admite que isso é para mascarar um erro de tsc emterminateCallem vez de consertar. Isso é técnica-débito disfarçado. -
Segurança em
docker-compose.yaml: a PR expõe Postgres e Redis em5432:5432e6379:6379no host (0.0.0.0). Isso é uma regressão de segurança — usuários que rodarem esse compose em servidores expostos ficam vulneráveis. Também remove o serviçofrontend(evolution-manager) e os aliasesdokploy-network. -
CLAUDE.mdreescrito em português com referências a "DGGirl e-commerce", PM2ApiEvolution, fluxos Google Gemini, e troca do maintainer para[email protected]. Isso é configuração do seu fork pessoal e não pertence ao upstream. -
Churn massivo no
whatsapp.baileys.service.ts: +979/-1735 linhas para justificar ~50 linhas de fix de @lid. Praticamente impossível revisar com confiança o que foi alterado nessa janela. -
Sem testes, mesmo introduzindo helpers novos (
resolveLidJid,resolveLidContact).
Como prosseguir
Por favor abra uma nova PR focada contendo apenas:
✅ src/api/types/wa.types.ts — novos types LidMessageKey, LidContact, ExtendedIMessageKey + helpers resolveLidJid, resolveLidContact (essa parte é boa!)
✅ A normalização de @lid em messages.upsert/messages.update (a parte cirúrgica)
✅ A mudança em chatwoot.service.ts:632 (MessageBodyWithExtendedKey)
✅ O guard do QR-regeneration loop (se isolável)
❌ Sem Dockerfile, sem docker-compose, sem CLAUDE.md, sem package-lock.json regen
❌ Sem remoção de SEND_MESSAGE_UPDATE (separar em PR distinta com discussão)
Vou fechar esta PR quando você abrir a substituta focada. Obrigado pela contribuição — o trabalho de tipagem de LID é genuinamente útil.
🔴 👎
A parte de fundo (resolver @lid pra número + loop do qrcode) é útil, mas o PR está desatualizado (com conflitos) e mistura 15 commits de fork — deleta/altera workflows, Dockerfile, docker-compose, lockfile, CLAUDE.md, etc. Do jeito que está bagunçaria o repo. Rebaseia na develop e abre só a correção do LID/qrcode isolada.
@dpaes