feat: prevent deleted email conversations from syncing again (#14612)

# Pull Request Template

## Description

Prevent deleted email conversations from being synced into Chatwoot
again while they are still within the IMAP sync window.

When an admin explicitly deletes an email conversation, the incoming
email message IDs are stored temporarily in Redis. IMAP sync checks
these recently deleted message IDs in addition to existing message
records. Each Redis key expires automatically after two days.

This applies only to explicit conversation deletion. Individual message
deletion, inbox deletion, and account deletion keep their existing
behavior.

Fixes
[CW-7214](https://linear.app/chatwoot/issue/CW-7214/deleted-mails-in-gmail-inbox-gets-synced-again)
This commit is contained in:
Vishnu Narayanan
2026-06-15 17:06:40 +05:30
committed by GitHub
parent 35bef21f83
commit ee6382109a
7 changed files with 109 additions and 2 deletions
@@ -140,7 +140,7 @@ class Api::V1::Accounts::ConversationsController < Api::V1::Accounts::BaseContro
def destroy
authorize @conversation, :destroy?
::DeleteObjectJob.perform_later(@conversation, Current.user, request.ip)
::Conversations::DeleteService.new(conversation: @conversation, user: Current.user, ip: request.ip).perform
head :ok
end
@@ -0,0 +1,16 @@
class Conversations::DeleteService
pattr_initialize [:conversation!, :user, :ip]
def perform
track_deleted_email_messages
::DeleteObjectJob.perform_later(conversation, user, ip)
end
private
def track_deleted_email_messages
return unless conversation.inbox.email?
Imap::DeletedMessageTracker.new(inbox: conversation.inbox).record(conversation.messages.incoming.pluck(:source_id))
end
end
@@ -38,7 +38,11 @@ class Imap::BaseFetchEmailService
end
def email_already_present?(channel, message_id)
channel.inbox.messages.find_by(source_id: message_id).present?
channel.inbox.messages.find_by(source_id: message_id).present? || deleted_message_tracker.deleted?(message_id)
end
def deleted_message_tracker
@deleted_message_tracker ||= Imap::DeletedMessageTracker.new(inbox: channel.inbox)
end
def fetch_mail_for_channel
@@ -0,0 +1,28 @@
require 'digest'
class Imap::DeletedMessageTracker
TTL = 2.days.to_i
pattr_initialize [:inbox!]
def record(source_ids)
return unless inbox.email?
keys = source_ids.compact_blank.map { |source_id| redis_key(source_id) }
return if keys.blank?
Redis::Alfred.pipelined do |pipeline|
keys.each { |key| pipeline.set(key, true, ex: TTL) }
end
end
def deleted?(source_id)
Redis::Alfred.exists?(redis_key(source_id))
end
private
def redis_key(source_id)
format(Redis::RedisKeys::IMAP_DELETED_MESSAGE, inbox_id: inbox.id, message_id_digest: Digest::SHA256.hexdigest(source_id))
end
end