Skip to content

fix(inbox): deduplica mensagens inbound por whatsapp_message_id - #58

Open
felipetruman wants to merge 1 commit into
thaleslaray:mainfrom
felipetruman:fix/webhook-inbound-dedup
Open

fix(inbox): deduplica mensagens inbound por whatsapp_message_id#58
felipetruman wants to merge 1 commit into
thaleslaray:mainfrom
felipetruman:fix/webhook-inbound-dedup

Conversation

@felipetruman

@felipetruman felipetruman commented Jun 16, 2026

Copy link
Copy Markdown

Problema

O Meta reenvia o webhook (retry) com o mesmo whatsapp_message_id. Hoje handleInboundMessage insere a mensagem direto (via RPC process_inbound_message ou fallback createMessage) sem checar duplicata — não há unique constraint em inbox_messages.whatsapp_message_id (índice existe mas é não-unique). Resultado: mensagem persistida 2x e IA disparada 2x, corrompendo contadores e o inbox silenciosamente.

Correção

Guard no topo de handleInboundMessage, antes do RPC e do fallback legacy (cobre ambos): usa findMessageByWhatsAppId (que já existia mas estava sem uso) e retorna cedo se a mensagem já existe.

  • Fail-open: se a checagem falhar, processa normalmente (melhor duplicar que perder mensagem).
  • App-level, sem migration — deployável de imediato.

Test plan

  • Reenviar o mesmo webhook inbound 2x → apenas 1 linha em inbox_messages, IA dispara 1x.
  • Mensagem nova → fluxo normal inalterado.

Summary by CodeRabbit

  • Bug Fixes
    • Improved message handling with early deduplication checks to prevent duplicate message processing.
    • Enhanced error resilience with improved fallback handling for message lookups.

O Meta reenvia o webhook (retry) com o mesmo whatsapp_message_id. Sem
guard, a mensagem era persistida 2x e a IA disparada 2x, corrompendo
contadores e o inbox silenciosamente.

Adiciona checagem via findMessageByWhatsAppId (que já existia mas não era
usada) no topo de handleInboundMessage, antes do RPC e do fallback legacy
— cobre ambos os caminhos. Fail-open: se a checagem falhar, processa
normalmente (melhor duplicar que perder mensagem).
@vercel

vercel Bot commented Jun 16, 2026

Copy link
Copy Markdown

@felipetruman is attempting to deploy a commit to the Thales Laray Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Jun 16, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

handleInboundMessage in lib/inbox/inbox-webhook.ts gains an early deduplication check. Before the existing RPC/fallback flow, it queries inboxDb.findMessageByWhatsAppId(payload.messageId) and, on a hit, returns the existing conversation and message identifiers with triggeredAI: false. Query errors are logged as warnings and processing continues normally (fail-open).

Changes

Inbound Message Deduplication

Layer / File(s) Summary
Early-return dedup guard
lib/inbox/inbox-webhook.ts
Inserts a pre-processing block that calls inboxDb.findMessageByWhatsAppId(payload.messageId); returns existing identifiers with triggeredAI: false on a duplicate hit, or logs a warning and falls through on error.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~5 minutes

Poem

🐇 A message arrives — but wait, I've seen this before!
My little paw checks the inbox door.
"Already here," I whisper with care,
triggeredAI: false floats gently in the air.
No double hops, no rabbit chase twice —
Deduplication is awfully nice! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is in Portuguese and directly addresses the main change: adding deduplication for inbound messages by whatsapp_message_id, which matches the PR's primary objective of preventing duplicate message processing.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
lib/inbox/inbox-webhook.ts (1)

112-112: 💤 Low value

Optional: Consider using English for consistency with other log messages.

The console log message uses Portuguese, while most other logs in this file use English (e.g., lines 145, 154, 162, 194). For developer-facing logs, consistency aids scanability.

♻️ Suggested change for consistency
-        console.log(`🔁 [INBOX] Mensagem duplicada ignorada (whatsapp_message_id=${payload.messageId})`)
+        console.log(`🔁 [INBOX] Duplicate message ignored (whatsapp_message_id=${payload.messageId})`)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/inbox/inbox-webhook.ts` at line 112, The console.log message in the
duplicate message check uses Portuguese text ("Mensagem duplicada ignorada")
while other log messages in the file use English for consistency. Replace the
Portuguese message with its English equivalent while preserving the emoji, tag,
and dynamic messageId parameter to maintain consistency with other logs in the
file like those found at lines 145, 154, 162, and 194.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@lib/inbox/inbox-webhook.ts`:
- Line 112: The console.log message in the duplicate message check uses
Portuguese text ("Mensagem duplicada ignorada") while other log messages in the
file use English for consistency. Replace the Portuguese message with its
English equivalent while preserving the emoji, tag, and dynamic messageId
parameter to maintain consistency with other logs in the file like those found
at lines 145, 154, 162, and 194.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3b29b53a-81f5-43fd-a3b6-6b6e60458bb4

📥 Commits

Reviewing files that changed from the base of the PR and between 17c69e2 and d9bc794.

📒 Files selected for processing (1)
  • lib/inbox/inbox-webhook.ts

felipetruman added a commit to felipetruman/smartzap that referenced this pull request Jun 16, 2026
Companion no nível do banco da guard app-level (thaleslaray#58). O índice do baseline
era não-unique (só performance), permitindo duplicatas em retries do Meta.
Troca por UNIQUE INDEX parcial (WHERE whatsapp_message_id IS NOT NULL),
garantindo dedup no DB mesmo se a guard app-level falhar.

Inclui nota de deduplicação prévia para bases já em uso (UNIQUE falha se
houver duplicatas existentes).
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