feat(label): add GET /label/syncLabels endpoint to force WhatsApp label re-sync
📋 Description
Add GET /label/syncLabels/:instanceName endpoint that forces WhatsApp to re-download labels via Baileys' resyncAppState(['regular'], true).
Problem
Currently, GET /label/findLabels/:instanceName only reads labels from the Prisma database. Labels created, renamed, or recolored on WhatsApp after the initial connection are never reflected in the API response. There is no way to force a re-sync of labels from WhatsApp.
Solution
New endpoint syncLabels that:
- Calls
this.client.resyncAppState(['regular'], true)to trigger an incremental re-download of WhatsApp's label app state - Waits 3 seconds for the existing
LABELS_EDITandLABELS_ASSOCIATIONevent handlers to process incoming data - Returns the updated labels from the database (same
LabelDto[]format asfindLabels)
Key Technical Details
resyncAppState(['regular'], true)— thetrueparameter means "incremental" (only fetch changes since last sync). This is safe and does NOT cause disconnects.resyncAppState(['regular'], false)— would download the FULL snapshot, which causes WhatsApp to disconnect the session. This was tested and confirmed in production. We intentionally usetrue.- 3-second delay allows Baileys' built-in event handlers (
labelHandle[Events.LABELS_EDIT]andlabelHandle[Events.LABELS_ASSOCIATION]) to process and persist the incoming label data before reading from DB. - No schema validation needed — like
findLabels, this is a simple GET with only theinstanceNameparameter.
Use Case
CRM integrations (Odoo, Chatwoot, etc.) that need to keep label data in sync with WhatsApp. The CRM calls syncLabels periodically to ensure it has the latest labels before mapping them to contacts/conversations.
Files Changed
| File | Change |
|---|---|
whatsapp.baileys.service.ts |
Added syncLabels() method using resyncAppState + fetchLabels() |
label.controller.ts |
Added syncLabels() delegation (same pattern as fetchLabels) |
label.router.ts |
Added GET /label/syncLabels/:instanceName route (same pattern as findLabels) |
evolution.channel.service.ts |
Added stub throwing BadRequestException |
whatsapp.business.service.ts |
Added stub throwing BadRequestException |
🔗 Related Issue
This addresses a gap in the label management API. Related to #1904 (labels.association handling).
🧪 Type of Change
- [ ] 🐛 Bug fix (non-breaking change which fixes an issue)
- [x] ✨ 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
- [x] Manual testing completed
- [x] Functionality verified in development environment
- [x] No breaking changes introduced
- [x] Tested with different connection types (if applicable)
Test results (production VPS, Evolution API v2.2.0):
- ✅
GET /label/syncLabels/testInstance→ HTTP 200, returns updatedLabelDto[] - ✅ No WhatsApp disconnection (incremental sync with
isLatest=true) - ✅ Labels created after initial connection are now returned after sync
- ✅ Existing
findLabelsandhandleLabelendpoints completely unaffected - ✅ Evolution Channel stub correctly returns 400 BadRequestException
- ✅ WhatsApp Business API stub correctly returns 400 BadRequestException
- ✅ Tested integration with Odoo CRM — labels synced successfully
✅ Checklist
- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [x] My changes generate no new warnings
- [x] I have manually tested my changes thoroughly
- [x] I have verified the changes work with different scenarios
- [x] Any dependent changes have been merged and published
📝 Additional Notes
- The
resyncAppStatefunction is provided by Baileys but was never used anywhere in the Evolution API codebase before this PR. - This feature is particularly valuable for multi-device setups where labels are managed from the phone but need to be reflected in the API.
- The 3-second delay is a pragmatic choice based on production testing. It could be made configurable in a future enhancement.
Summary by Sourcery
Add support for explicitly re-syncing WhatsApp labels and expose it via a new HTTP endpoint.
New Features:
- Introduce a Baileys service method to trigger an incremental WhatsApp label resync and return updated labels.
- Expose a new GET /label/syncLabels/:instanceName route and controller method to trigger label resync for a given instance.
Chores:
- Add stub syncLabels methods for Evolution and WhatsApp Business channels that return BadRequest exceptions.
Reviewer's Guide
Adds a new GET /label/syncLabels/:instanceName endpoint that triggers a Baileys incremental app state resync for labels, waits for label events to be processed, and then returns the refreshed labels from the database, while stubbing the same method as unsupported on non-Baileys channels.
Sequence diagram for GET /label/syncLabels endpoint flow
sequenceDiagram
actor CRM
participant ApiServer
participant LabelRouter
participant LabelController
participant WaMonitor
participant BaileysStartupService
participant BaileysClient
participant LabelEventHandlers
participant Database
CRM->>ApiServer: HTTP GET /label/syncLabels/:instanceName
ApiServer->>LabelRouter: route syncLabels
LabelRouter->>LabelRouter: dataValidate request to LabelDto
LabelRouter->>LabelController: syncLabels(InstanceDto)
LabelController->>WaMonitor: waInstances[instanceName]
WaMonitor->>BaileysStartupService: syncLabels()
BaileysStartupService->>BaileysClient: resyncAppState([regular], true)
BaileysClient-->>BaileysStartupService: resync initiated
BaileysClient->>LabelEventHandlers: emit LABELS_EDIT events
BaileysClient->>LabelEventHandlers: emit LABELS_ASSOCIATION events
LabelEventHandlers->>Database: upsert label records
BaileysStartupService->>BaileysStartupService: wait 3000 ms
BaileysStartupService->>Database: fetchLabels()
Database-->>BaileysStartupService: LabelDto[]
BaileysStartupService-->>WaMonitor: LabelDto[]
WaMonitor-->>LabelController: LabelDto[]
LabelController-->>LabelRouter: LabelDto[]
LabelRouter-->>ApiServer: HTTP 200 LabelDto[]
ApiServer-->>CRM: HTTP 200 LabelDto[]
Updated class diagram for label sync across channel services
classDiagram
class ChannelStartupService {
}
class BaileysStartupService {
+fetchLabels() Promise~LabelDto[]~
+syncLabels() Promise~LabelDto[]~
+handleLabel(data HandleLabelDto) Promise~any~
}
class EvolutionStartupService {
+fetchLabels() Promise~void~
+syncLabels() Promise~void~
+handleLabel() Promise~void~
}
class BusinessStartupService {
+fetchLabels() Promise~void~
+syncLabels() Promise~void~
+handleLabel() Promise~void~
}
class LabelController {
+fetchLabels(instance InstanceDto) Promise~LabelDto[]~
+handleLabel(instance InstanceDto, data HandleLabelDto) Promise~any~
+syncLabels(instance InstanceDto) Promise~LabelDto[]~
}
class LabelRouter {
+router Router
+registerRoutes() void
}
class WaMonitor {
+waInstances map~string, ChannelStartupService~
}
ChannelStartupService <|-- BaileysStartupService
ChannelStartupService <|-- EvolutionStartupService
ChannelStartupService <|-- BusinessStartupService
WaMonitor "1" --> "*" ChannelStartupService : waInstances
LabelController --> WaMonitor : uses
LabelRouter --> LabelController : uses
File-Level Changes
| Change | Details | Files |
|---|---|---|
| Implement Baileys-based label resync flow and expose it via controller and router as GET /label/syncLabels/:instanceName. |
|
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.tssrc/api/controllers/label.controller.tssrc/api/routes/label.router.ts |
| Add syncLabels stubs for non-Baileys WhatsApp channels to keep the ChannelStartupService interface consistent while explicitly marking the operation as unsupported. |
|
src/api/integrations/channel/evolution/evolution.channel.service.tssrc/api/integrations/channel/meta/whatsapp.business.service.ts |
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.
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!
O que falta pra juntar isso ai minha gente?
Endpoint bem estruturado, segue o padrão de findLabels/handleLabel, comentários explicando o porquê das escolhas. Quase pronto.
Bloqueador:
- [ ] BOM (U+FEFF) introduzido no início de
whatsapp.baileys.service.ts— o diff mostra um zero-width no-break space precedendo a linha+import { getCollectionsDto } from '@api/dto/business.dto';. Provavelmente seu editor salvou o arquivo com encoding UTF-8-BOM. Removendo com:
sed -i '1s/^\xEF\xBB\xBF//' src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
Nits (não-bloqueantes, considerar follow-up):
- [ ]
setTimeout(3000)fixo segura um worker HTTP — em uso esporádico OK, mas se o caso de uso for periódico (sync agendado), considere polling de estado ou variável de sinalização nos handlers deLABELS_EDIT/LABELS_ASSOCIATION - [ ] Sem throttle entre chamadas concorrentes — duas chamadas paralelas iniciam dois resync. Cache key
syncLabels_lock_${instanceId}com TTL 30s resolveria (retornar 429 ou os labels atuais sem novo resync) - [ ] Guard
if (typeof this.client.resyncAppState !== 'function')no caso de versão futura do Baileys mudar a API interna
Após remover o BOM, aprovo.
Olá @josuecocoman, obrigado pela feature. O endpoint é útil e a implementação está quase pronta. Mudanças necessárias:
Bloqueante
- BOM injetado em
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:1. O diff mostra:
Esse caractere invisível antes de+import { getCollectionsDto } from ...importé um Byte Order Mark (U+FEFF). Quebra alguns parsers e linters silenciosamente. Por favor remova — salve o arquivo como UTF-8 sem BOM e force-push.
Sugestões (não-bloqueantes)
-
3 segundos fixos de
setTimeoutantes dofetchLabels()é frágil. Se a conta tem muitas labels ou link está lento, retorna stale. Considere:- Tornar configurável via env (
LABEL_SYNC_DELAY_MS, default 3000) - Ou fazer polling até o evento
LABELS_ASSOCIATIONchegar (com timeout máximo)
- Tornar configurável via env (
-
Sem rate-limit. Callers podem hammer
resyncAppStatechamando o endpoint em loop. Baileys pode throttle ou disconnectar. Considere um debounce/lock por instância. -
schema: nullno router — não tem DTO validation. Está OK pois só passa:instanceName, mas é inconsistente com o resto do router.
Após remover o BOM, mergeio (mesmo que os pontos 2-4 fiquem para follow-up). Obrigado!
🟢 👍
Mira a develop e implementa direitinho: novo GET /label/syncLabels com controller + router + os 3 channel services, usando resyncAppState(['regular'], true) no Baileys (sync incremental, sem desconectar) e stubs apropriados no Meta/Evolution. Faz o que promete. Só dois detalhes de higiene pra limpar antes: o diff introduziu um BOM (caractere invisível) no início do whatsapp.baileys.service.ts e tirou a newline final de label.controller.ts/label.router.ts — remove esses ruídos que aí fica impecável.
@dpaes