:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(conversations): add email thread persistence (#80736)
Arthur Moreira de Deus542755946842
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex c16ba7026ecd..f5a6fd8937f2 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -137,6 +137,9 @@ rules:|DeploymentProject|EarlyAccessFeature|EmailMessageMapping+ |EmailThread+ |EmailThreadMessage+ |EmailThreadParticipant|EmailReputationSnapshot|EvaluationContext|Edge@@ -495,6 +498,9 @@ rules:|DeploymentProject|EarlyAccessFeature|EmailMessageMapping+ |EmailThread+ |EmailThreadMessage+ |EmailThreadParticipant|EmailReputationSnapshot|EvaluationContext|Edgediff --git a/posthog/api/comments.py b/posthog/api/comments.pyindex 5729a23e0468..62f41636ae7c 100644--- a/posthog/api/comments.py+++ b/posthog/api/comments.py@@ -28,7 +28,11 @@ from posthog.models import Team, Userfrom posthog.models.activity_logging.activity_log import Change, Detail, log_activityfrom posthog.models.activity_logging.model_activity import get_was_impersonatedfrom posthog.models.comment import Comment, CommentSlackThread-from posthog.models.comment.comment import TICKET_COMMENT_SCOPES, activity_log_scope_for+from posthog.models.comment.comment import (+ COMMENT_SCOPES_BLOCKED_FROM_GENERIC_API,+ TICKET_COMMENT_SCOPES,+ activity_log_scope_for,+)from posthog.models.comment.slack_thread import DISCUSSIONS_SLACK_SYNC_FLAGfrom posthog.models.comment.utils import (DESKTOP_COMMENT_SCOPES,@@ -354,6 +358,9 @@ class CommentSerializer(serializers.ModelSerializer):raise exceptions.ValidationError({"scope": ErrorDetail("This field is required.", code="required")})scope = data["scope"] if "scope" in data else getattr(instance, "scope", None)item_id = data["item_id"] if "item_id" in data else getattr(instance, "item_id", None)+ candidate_scopes = {scope, getattr(instance, "scope", None), getattr(source_comment, "scope", None)}+ if candidate_scopes & COMMENT_SCOPES_BLOCKED_FROM_GENERIC_API:+ raise exceptions.PermissionDenied("Email thread messages cannot be managed through the comments API")if source_comment is not None:if source_comment.team_id != self.context["team_id"]:raise exceptions.ValidationError({"source_comment": "Comment not found."})@@ -898,6 +905,7 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVdef safely_get_queryset(self, queryset: QuerySet) -> QuerySet:params = self.request.GET.dict()+ queryset = queryset.exclude(scope__in=COMMENT_SCOPES_BLOCKED_FROM_GENERIC_API)if params.get("user"):queryset = queryset.filter(user=params.get("user"))diff --git a/posthog/api/test/test_comment_slack_sync.py b/posthog/api/test/test_comment_slack_sync.pyindex 2e8ea18a9112..f1b3828684ac 100644--- a/posthog/api/test/test_comment_slack_sync.py+++ b/posthog/api/test/test_comment_slack_sync.py@@ -317,6 +317,7 @@ class TestCommentReplySlackSignal(APIBaseTest):("from_slack_reply_not_echoed", "parent", "Insight", {"from_slack": True}, False),("emoji_reaction_not_mirrored", "parent", "Insight", {"is_emoji": True}, False),("conversations_ticket_excluded", "parent", "conversations_ticket", None, False),+ ("email_thread_excluded", "parent", "EmailThread", None, False),("top_level_comment", None, "Insight", None, False),])@@ -384,6 +385,30 @@ class TestReplyMirror(APIBaseTest):mock_slack.assert_not_called()+ @patch("posthog.tasks.comment_slack_sync.SlackIntegration")+ def test_email_thread_reply_is_not_mirrored(self, mock_slack):+ parent = Comment.objects.create(team=self.team, scope="EmailThread", item_id="thread-42", content="root")+ CommentSlackThread.objects.for_team(self.team.id).create(+ team=self.team,+ scope="EmailThread",+ item_id="thread-42",+ source_comment=parent,+ integration=self.integration,+ slack_channel_id="C1",+ slack_thread_ts="100.1",+ )+ reply = Comment.objects.create(+ team=self.team,+ scope="EmailThread",+ item_id="thread-42",+ content="reply",+ source_comment=parent,+ )++ mirror_comment_reply_to_slack.apply(kwargs={"comment_id": str(reply.id)})++ mock_slack.assert_not_called()+@patch("posthog.tasks.comment_slack_sync.SlackIntegration")def test_reply_posts_once_across_task_reruns(self, mock_slack):mock_slack.return_value.client.chat_postMessage.return_value = {"ts": "100.2"}diff --git a/posthog/api/test/test_comments.py b/posthog/api/test/test_comments.pyindex 4234e32e751f..7fbe88b66d0b 100644--- a/posthog/api/test/test_comments.py+++ b/posthog/api/test/test_comments.py@@ -1405,6 +1405,48 @@ class TestComments(APIBaseTest, QueryMatchingTest):assert response.status_code == status.HTTP_200_OKassert [c["scope"] for c in response.json()["results"]] == ["Notebook"]+ @mock.patch("posthog.api.comments.CommentViewSet._slack_mirror_flag_enabled", return_value=True)+ def test_email_thread_comments_are_blocked_from_generic_comment_surfaces(self, _flag: mock.Mock) -> None:+ comment = Comment.objects.create(+ team=self.team,+ scope="EmailThread",+ item_id="019fed13-8204-76cd-8c0c-5d02cf10fc02",+ content="Private email body",+ created_by=self.user,+ )++ unscoped = self.client.get(f"/api/projects/{self.team.id}/comments")+ scoped = self.client.get(f"/api/projects/{self.team.id}/comments?scope=EmailThread")+ detail = self.client.get(f"/api/projects/{self.team.id}/comments/{comment.id}")+ update = self.client.patch(+ f"/api/projects/{self.team.id}/comments/{comment.id}",+ {"content": "Rewritten email body"},+ )+ create = self.client.post(+ f"/api/projects/{self.team.id}/comments",+ {+ "scope": "EmailThread",+ "item_id": "019fed13-8204-76cd-8c0c-5d02cf10fc02",+ "content": "New email body",+ },+ )+ slack = self.client.post(+ f"/api/projects/{self.team.id}/comments/{comment.id}/send_to_slack/",+ {"integration_id": 1, "channel_id": "C1"},+ )++ assert comment.id not in {row["id"] for row in unscoped.json()["results"]}+ assert scoped.json()["results"] == []+ assert detail.status_code == status.HTTP_404_NOT_FOUND+ assert update.status_code == status.HTTP_404_NOT_FOUND+ assert create.status_code == status.HTTP_403_FORBIDDEN+ assert slack.status_code == status.HTTP_404_NOT_FOUND+ assert not ActivityLog.objects.filter(+ team_id=self.team.id,+ scope="EmailThread",+ item_id=comment.item_id,+ ).exists()+def test_ticket_scoped_comment_detail_actions_work_for_session_users(self) -> None:# Detail actions carry no scope param; the default-list exclusion must not 404 them.comment = Comment.objects.create(diff --git a/posthog/models/comment/comment.py b/posthog/models/comment/comment.pyindex 50b95f4c056f..0412768c11dd 100644--- a/posthog/models/comment/comment.py+++ b/posthog/models/comment/comment.py@@ -73,6 +73,9 @@ class Comment(UUIDTModel, RootTeamMixin):# surfaces gated on weaker scopes (e.g. activity logs).TICKET_COMMENT_SCOPES = frozenset({"Ticket", "conversations_ticket"})+# Product-owned content in these scopes is available only through the owning product's API.+COMMENT_SCOPES_BLOCKED_FROM_GENERIC_API = frozenset({"EmailThread"})+def activity_log_scope_for(comment: Comment) -> str:# Map legacy "recording" → "Replay"; replies are logged under the parent thread.@@ -82,7 +85,7 @@ def activity_log_scope_for(comment: Comment) -> str:@mutable_receiver(models.signals.post_save, sender=Comment)def log_comment_activity(sender, instance: Comment, created: bool, **kwargs):- if created:+ if created and instance.scope not in COMMENT_SCOPES_BLOCKED_FROM_GENERIC_API:# TRICKY: - Comments relate to a "thing" like a flag or insight. When we log the activity we need to know what the "thing" is# Rendering in the frontend we needdiff --git a/posthog/models/comment/slack_thread.py b/posthog/models/comment/slack_thread.pyindex 9a11d6e74095..b1d8cd33161d 100644--- a/posthog/models/comment/slack_thread.py+++ b/posthog/models/comment/slack_thread.py@@ -1,6 +1,6 @@from django.db import models, transaction-from posthog.models.comment.comment import Comment+from posthog.models.comment.comment import COMMENT_SCOPES_BLOCKED_FROM_GENERIC_API, Commentfrom posthog.models.scoping.root_mixin import TeamScopedRootMixinfrom posthog.models.signals import mutable_receiverfrom posthog.models.utils import UUIDModel@@ -68,13 +68,13 @@ def mirror_comment_reply_to_slack_on_create(sender, instance: Comment, created:"""Sync a newly-created discussion reply out to any mirrored Slack threads.Only replies (``source_comment`` set) sync — the thread root is posted by the send_to_slack- action. Conversations tickets are excluded (that product has its own Slack sync),- Slack-originated replies (``item_context.from_slack``) are skipped to avoid echo loops, and+ action. Conversations tickets and protected scopes are excluded because their owning products+ control integrations. Slack-originated replies (``item_context.from_slack``) are skipped to avoid echo loops, andemoji reactions (``item_context.is_emoji`` — stored as reply comments) don't post as messages."""if not created or not instance.source_comment_id:return- if instance.scope == "conversations_ticket":+ if instance.scope == "conversations_ticket" or instance.scope in COMMENT_SCOPES_BLOCKED_FROM_GENERIC_API:returnitem_context = instance.item_contextif isinstance(item_context, dict) and (item_context.get("from_slack") or item_context.get("is_emoji")):diff --git a/posthog/tasks/comment_slack_sync.py b/posthog/tasks/comment_slack_sync.pyindex 66210d75dd7b..e69c8c57b8f5 100644--- a/posthog/tasks/comment_slack_sync.py+++ b/posthog/tasks/comment_slack_sync.py@@ -11,6 +11,7 @@ from posthog.comment.formatting import slack_files_to_placeholder_lines, slack_tfrom posthog.helpers.slack_identity import resolve_posthog_user_for_slack, resolve_slack_userfrom posthog.helpers.slack_thread_mirror import post_comment_to_slack_thread, slack_author_from_userfrom posthog.models.comment import Comment, CommentSlackThread+from posthog.models.comment.comment import COMMENT_SCOPES_BLOCKED_FROM_GENERIC_APIfrom posthog.models.comment.slack_thread import DISCUSSIONS_SLACK_SYNC_FLAGfrom posthog.models.integration import SlackIntegrationfrom posthog.models.team import Team@@ -120,6 +121,8 @@ def _mark_reply_synced(reply: Comment, ts: object) -> None:def _reply_skip_reason(reply: Comment) -> str | None:+ if reply.scope in COMMENT_SCOPES_BLOCKED_FROM_GENERIC_API:+ return "protected_scope"item_context = reply.item_context if isinstance(reply.item_context, dict) else {}if item_context.get("from_slack"):return "from_slack" # came in from Slack — echoing it back would loopdiff --git a/products/conversations/backend/migrations/0060_emailthread_emailthreadmessage_and_more.py b/products/conversations/backend/migrations/0060_emailthread_emailthreadmessage_and_more.pynew file mode 100644index 000000000000..681e092bfbec--- /dev/null+++ b/products/conversations/backend/migrations/0060_emailthread_emailthreadmessage_and_more.py@@ -0,0 +1,159 @@+# Generated by Django 5.2.17 on 2026-08-10 16:13++import django.db.models.deletion+from django.db import migrations, models++import posthog.uuidt+++class Migration(migrations.Migration):+ dependencies = [+ ("conversations", "0059_validate_email_channel_kind_constraint"),+ ("posthog", "1296_backfill_cimd_verification_token_url"),+ ]++ operations = [+ migrations.CreateModel(+ name="EmailThread",+ fields=[+ (+ "id",+ models.UUIDField(default=posthog.uuidt.uuid7, editable=False, primary_key=True, serialize=False),+ ),+ ("canonical_thread_key", models.CharField(max_length=998)),+ ("subject", models.TextField(blank=True, default="")),+ ("first_message_at", models.DateTimeField(blank=True, null=True)),+ ("last_message_at", models.DateTimeField(blank=True, null=True)),+ ("message_count", models.PositiveIntegerField(default=0)),+ ("preview", models.CharField(blank=True, default="", max_length=500)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "team",+ models.ForeignKey(+ db_constraint=False, on_delete=django.db.models.deletion.CASCADE, to="posthog.team"+ ),+ ),+ ],+ options={+ "db_table": "posthog_conversations_email_thread",+ },+ ),+ migrations.CreateModel(+ name="EmailThreadMessage",+ fields=[+ (+ "id",+ models.UUIDField(default=posthog.uuidt.uuid7, editable=False, primary_key=True, serialize=False),+ ),+ ("message_id", models.CharField(blank=True, max_length=998, null=True)),+ ("in_reply_to", models.CharField(blank=True, max_length=998, null=True)),+ ("references", models.JSONField(blank=True, default=list)),+ ("sent_at", models.DateTimeField()),+ ("sender_email", models.CharField(max_length=400)),+ ("sender_name", models.CharField(blank=True, default="", max_length=400)),+ ("to_recipients", models.JSONField(blank=True, default=list)),+ ("cc_recipients", models.JSONField(blank=True, default=list)),+ (+ "direction",+ models.CharField(choices=[("inbound", "Inbound"), ("outbound", "Outbound")], max_length=16),+ ),+ ("source_type", models.CharField(max_length=64)),+ ("source_id", models.CharField(max_length=512)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ (+ "comment",+ models.OneToOneField(+ db_constraint=False,+ on_delete=django.db.models.deletion.RESTRICT,+ related_name="email_thread_message",+ to="posthog.comment",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False, on_delete=django.db.models.deletion.CASCADE, to="posthog.team"+ ),+ ),+ (+ "thread",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="messages",+ to="conversations.emailthread",+ ),+ ),+ ],+ options={+ "db_table": "posthog_conversations_email_thread_message",+ "ordering": ["sent_at", "id"],+ },+ ),+ migrations.CreateModel(+ name="EmailThreadParticipant",+ fields=[+ (+ "id",+ models.UUIDField(default=posthog.uuidt.uuid7, editable=False, primary_key=True, serialize=False),+ ),+ ("email", models.CharField(max_length=400)),+ ("display_name", models.CharField(blank=True, default="", max_length=400)),+ ("kind", models.CharField(choices=[("internal", "Internal"), ("customer", "Customer")], max_length=16)),+ ("person_id", models.UUIDField(blank=True, null=True)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "team",+ models.ForeignKey(+ db_constraint=False, on_delete=django.db.models.deletion.CASCADE, to="posthog.team"+ ),+ ),+ (+ "thread",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="participants",+ to="conversations.emailthread",+ ),+ ),+ ],+ options={+ "db_table": "posthog_conversations_email_thread_participant",+ },+ ),+ migrations.AddIndex(+ model_name="emailthread",+ index=models.Index(fields=["team", "-last_message_at"], name="email_thread_team_last_idx"),+ ),+ migrations.AddConstraint(+ model_name="emailthread",+ constraint=models.UniqueConstraint(+ fields=("team", "canonical_thread_key"), name="unique_email_thread_key_per_team"+ ),+ ),+ migrations.AddIndex(+ model_name="emailthreadmessage",+ index=models.Index(fields=["team", "thread", "sent_at", "id"], name="email_message_thread_time_idx"),+ ),+ migrations.AddConstraint(+ model_name="emailthreadmessage",+ constraint=models.UniqueConstraint(+ fields=("team", "source_type", "source_id"), name="unique_email_message_source_per_team"+ ),+ ),+ migrations.AddConstraint(+ model_name="emailthreadmessage",+ constraint=models.UniqueConstraint(+ condition=models.Q(("message_id__isnull", False), models.Q(("message_id", ""), _negated=True)),+ fields=("team", "message_id"),+ name="unique_email_message_id_per_team",+ ),+ ),+ migrations.AddConstraint(+ model_name="emailthreadparticipant",+ constraint=models.UniqueConstraint(+ fields=("team", "thread", "email"), name="unique_email_thread_participant"+ ),+ ),+ ]diff --git a/products/conversations/backend/migrations/max_migration.txt b/products/conversations/backend/migrations/max_migration.txtindex 2260130ccb67..743fd9571bf1 100644--- a/products/conversations/backend/migrations/max_migration.txt+++ b/products/conversations/backend/migrations/max_migration.txt@@ -1 +1 @@-0059_validate_email_channel_kind_constraint+0060_emailthread_emailthreadmessage_and_morediff --git a/products/conversations/backend/models/__init__.py b/products/conversations/backend/models/__init__.pyindex 449c8d7323c8..8bbb53c2d243 100644--- a/products/conversations/backend/models/__init__.py+++ b/products/conversations/backend/models/__init__.py@@ -2,6 +2,14 @@ from .assignment import TicketAssignmentfrom .constants import Channel, ChannelDetail, Priority, RuleType, Statusfrom .email_message_mapping import EmailMessageMappingfrom .email_outbox_message import EmailOutboxMessage+from .email_thread import (+ EMAIL_THREAD_COMMENT_SCOPE,+ EmailThread,+ EmailThreadMessage,+ EmailThreadMessageDirection,+ EmailThreadParticipant,+ EmailThreadParticipantKind,+)from .github_comment_mapping import GithubCommentMappingfrom .restore_token import ConversationRestoreTokenfrom .signing_secret import SigningSecret@@ -22,6 +30,12 @@ __all__ = ["EmailChannelKind","EmailMessageMapping","EmailOutboxMessage",+ "EMAIL_THREAD_COMMENT_SCOPE",+ "EmailThread",+ "EmailThreadMessage",+ "EmailThreadMessageDirection",+ "EmailThreadParticipant",+ "EmailThreadParticipantKind","GithubCommentMapping","Priority","RuleType",diff --git a/products/conversations/backend/models/email_thread.py b/products/conversations/backend/models/email_thread.pynew file mode 100644index 000000000000..fc7e387258fd--- /dev/null+++ b/products/conversations/backend/models/email_thread.py@@ -0,0 +1,101 @@+from django.db import models++from posthog.models.scoping.root_mixin import TeamScopedRootMixin+from posthog.models.utils import UUIDModel++EMAIL_THREAD_COMMENT_SCOPE = "EmailThread"+++class EmailThreadMessageDirection(models.TextChoices):+ INBOUND = "inbound", "Inbound"+ OUTBOUND = "outbound", "Outbound"+++class EmailThreadParticipantKind(models.TextChoices):+ INTERNAL = "internal", "Internal"+ CUSTOMER = "customer", "Customer"+++class EmailThread(TeamScopedRootMixin, UUIDModel):+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)+ canonical_thread_key = models.CharField(max_length=998)+ subject = models.TextField(default="", blank=True)+ first_message_at = models.DateTimeField(null=True, blank=True)+ last_message_at = models.DateTimeField(null=True, blank=True)+ message_count = models.PositiveIntegerField(default=0)+ preview = models.CharField(max_length=500, default="", blank=True)+ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)++ class Meta:+ db_table = "posthog_conversations_email_thread"+ constraints = [+ models.UniqueConstraint(+ fields=["team", "canonical_thread_key"],+ name="unique_email_thread_key_per_team",+ ),+ ]+ indexes = [+ models.Index(fields=["team", "-last_message_at"], name="email_thread_team_last_idx"),+ ]+++class EmailThreadMessage(TeamScopedRootMixin, UUIDModel):+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)+ thread = models.ForeignKey("conversations.EmailThread", on_delete=models.CASCADE, related_name="messages")+ comment = models.OneToOneField(+ "posthog.Comment",+ on_delete=models.RESTRICT,+ db_constraint=False,+ related_name="email_thread_message",+ )+ message_id = models.CharField(max_length=998, null=True, blank=True)+ in_reply_to = models.CharField(max_length=998, null=True, blank=True)+ references = models.JSONField(default=list, blank=True)+ sent_at = models.DateTimeField()+ sender_email = models.CharField(max_length=400)+ sender_name = models.CharField(max_length=400, default="", blank=True)+ to_recipients = models.JSONField(default=list, blank=True)+ cc_recipients = models.JSONField(default=list, blank=True)+ direction = models.CharField(max_length=16, choices=EmailThreadMessageDirection.choices)+ source_type = models.CharField(max_length=64)+ source_id = models.CharField(max_length=512)+ created_at = models.DateTimeField(auto_now_add=True)++ class Meta:+ db_table = "posthog_conversations_email_thread_message"+ ordering = ["sent_at", "id"]+ constraints = [+ models.UniqueConstraint(+ fields=["team", "source_type", "source_id"],+ name="unique_email_message_source_per_team",+ ),+ models.UniqueConstraint(+ fields=["team", "message_id"],+ condition=models.Q(message_id__isnull=False) & ~models.Q(message_id=""),+ name="unique_email_message_id_per_team",+ ),+ ]+ indexes = [+ models.Index(fields=["team", "thread", "sent_at", "id"], name="email_message_thread_time_idx"),+ ]+++class EmailThreadParticipant(TeamScopedRootMixin, UUIDModel):+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)+ thread = models.ForeignKey("conversations.EmailThread", on_delete=models.CASCADE, related_name="participants")+ email = models.CharField(max_length=400)+ display_name = models.CharField(max_length=400, default="", blank=True)+ kind = models.CharField(max_length=16, choices=EmailThreadParticipantKind.choices)+ person_id = models.UUIDField(null=True, blank=True)+ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)++ class Meta:+ db_table = "posthog_conversations_email_thread_participant"+ constraints = [+ models.UniqueConstraint(+ fields=["team", "thread", "email"],+ name="unique_email_thread_participant",+ ),+ ]diff --git a/products/conversations/backend/services/email_threads.py b/products/conversations/backend/services/email_threads.pynew file mode 100644index 000000000000..0573af472dc3--- /dev/null+++ b/products/conversations/backend/services/email_threads.py@@ -0,0 +1,24 @@+from uuid import UUID++from django.db import transaction++from posthog.models.comment import Comment++from products.conversations.backend.models.email_thread import (+ EMAIL_THREAD_COMMENT_SCOPE,+ EmailThread,+ EmailThreadMessage,+)+++def delete_email_thread(*, team_id: int, thread_id: UUID | str) -> None:+ thread = EmailThread.objects.for_team(team_id).select_for_update().get(id=thread_id)++ EmailThreadMessage.objects.for_team(team_id).filter(thread=thread).delete()+ Comment.objects.filter(+ team_id=team_id,+ scope=EMAIL_THREAD_COMMENT_SCOPE,+ item_id=str(thread.id),+ ).delete()+ thread.delete()diff --git a/products/conversations/backend/tests/test_email_threads.py b/products/conversations/backend/tests/test_email_threads.pynew file mode 100644index 000000000000..467f7d207435--- /dev/null+++ b/products/conversations/backend/tests/test_email_threads.py@@ -0,0 +1,224 @@+from datetime import datetime, timedelta++from posthog.test.base import BaseTest++from django.db import IntegrityError, transaction+from django.utils import timezone++from parameterized import parameterized++from posthog.models.comment import Comment++from products.conversations.backend.models import (+ EMAIL_THREAD_COMMENT_SCOPE,+ EmailThread,+ EmailThreadMessage,+ EmailThreadMessageDirection,+ EmailThreadParticipant,+ EmailThreadParticipantKind,+ Ticket,+)+from products.conversations.backend.services.email_threads import delete_email_thread+++class TestEmailThreadPersistence(BaseTest):+ def _create_thread(self, *, canonical_thread_key: str = "<[email protected]>") -> EmailThread:+ return EmailThread.objects.for_team(self.team.id).create(+ team=self.team,+ canonical_thread_key=canonical_thread_key,+ subject="Quarterly planning",+ )++ def _create_message(+ self,+ thread: EmailThread,+ *,+ source_id: str,+ message_id: str,+ sent_at: datetime,+ direction: str = EmailThreadMessageDirection.INBOUND,+ ) -> EmailThreadMessage:+ comment = Comment.objects.create(+ team=self.team,+ scope=EMAIL_THREAD_COMMENT_SCOPE,+ item_id=str(thread.id),+ content=f"Body for {source_id}",+ )+ return EmailThreadMessage.objects.for_team(self.team.id).create(+ team=self.team,+ thread=thread,+ comment=comment,+ message_id=message_id,+ in_reply_to="<[email protected]>" if direction == EmailThreadMessageDirection.OUTBOUND else None,+ references=["<[email protected]>"],+ sent_at=sent_at,+ sender_email="[email protected]",+ sender_name="Example sender",+ to_recipients=[{"email": "[email protected]", "name": "Owner"}],+ cc_recipients=[{"email": "[email protected]", "name": "Observer"}],+ direction=direction,+ source_type="mailgun",+ source_id=source_id,+ )++ def test_messages_use_source_timestamp_order_and_preserve_email_metadata(self) -> None:+ thread = self._create_thread()+ later = timezone.now()+ outbound = self._create_message(+ thread,+ source_id="provider-2",+ message_id="<[email protected]>",+ sent_at=later,+ direction=EmailThreadMessageDirection.OUTBOUND,+ )+ inbound = self._create_message(+ thread,+ source_id="provider-1",+ message_id="<[email protected]>",+ sent_at=later - timedelta(hours=1),+ )++ messages = list(EmailThreadMessage.objects.for_team(self.team.id).filter(thread=thread))++ assert [message.id for message in messages] == [inbound.id, outbound.id]+ assert outbound.comment.scope == EMAIL_THREAD_COMMENT_SCOPE+ assert outbound.comment.item_id == str(thread.id)+ assert outbound.comment.source_comment_id is None+ assert outbound.in_reply_to == "<[email protected]>"+ assert outbound.references == ["<[email protected]>"]+ assert outbound.to_recipients == [{"email": "[email protected]", "name": "Owner"}]+ assert outbound.cc_recipients == [{"email": "[email protected]", "name": "Observer"}]+ assert outbound.direction == EmailThreadMessageDirection.OUTBOUND+ assert outbound.source_type == "mailgun"+ assert outbound.source_id == "provider-2"++ def test_email_thread_comments_do_not_update_matching_ticket_stats(self) -> None:+ thread = self._create_thread()+ ticket = Ticket.objects.create(+ id=thread.id,+ team=self.team,+ ticket_number=1,+ widget_session_id="email-thread-scope-test",+ distinct_id="example-customer",+ )++ with self.captureOnCommitCallbacks(execute=True):+ self._create_message(+ thread,+ source_id="provider-1",+ message_id="<[email protected]>",+ sent_at=timezone.now(),+ )++ ticket.refresh_from_db()+ assert ticket.message_count == 0+ assert ticket.unread_customer_count == 0+ assert ticket.unread_team_count == 0+ assert ticket.last_message_at is None+ assert ticket.last_message_text is None++ @parameterized.expand(+ [+ ("provider_identity", "provider-1", "<[email protected]>"),+ ("rfc_message_id", "provider-2", "<[email protected]>"),+ ]+ )+ def test_duplicate_canonical_messages_are_rejected(+ self, _name: str, duplicate_source_id: str, duplicate_message_id: str+ ) -> None:+ thread = self._create_thread()+ sent_at = timezone.now()+ self._create_message(+ thread,+ source_id="provider-1",+ message_id="<[email protected]>",+ sent_at=sent_at,+ )++ with self.assertRaises(IntegrityError), transaction.atomic():+ self._create_message(+ thread,+ source_id=duplicate_source_id,+ message_id=duplicate_message_id,+ sent_at=sent_at,+ )++ def test_messages_without_rfc_ids_do_not_collide(self) -> None:+ thread = self._create_thread()+ sent_at = timezone.now()++ first = self._create_message(+ thread,+ source_id="provider-1",+ message_id="",+ sent_at=sent_at,+ )+ second = self._create_message(+ thread,+ source_id="provider-2",+ message_id="",+ sent_at=sent_at,+ )++ assert first.id != second.id++ def test_canonical_thread_key_is_unique_per_team(self) -> None:+ self._create_thread()++ with self.assertRaises(IntegrityError), transaction.atomic():+ self._create_thread()++ def test_team_deletion_removes_messages_and_their_comment_bodies(self) -> None:+ team_id = self.team.id+ thread = self._create_thread()+ message = self._create_message(+ thread,+ source_id="provider-1",+ message_id="<[email protected]>",+ sent_at=timezone.now(),+ )+ comment_id = message.comment_id++ # The message's comment FK must not block the team cascade: both rows are collected by+ # the same delete, so RESTRICT clears rather than raising ProtectedError.+ self.team.delete()++ # The team row is gone, so scope by the captured id without re-resolving it.+ assert not EmailThreadMessage.objects.for_team(team_id, canonical=True).filter(id=message.id).exists()+ assert not Comment.objects.filter(id=comment_id).exists()++ def test_delete_service_removes_envelopes_participants_and_all_thread_comments(self) -> None:+ thread = self._create_thread()+ message = self._create_message(+ thread,+ source_id="provider-1",+ message_id="<[email protected]>",+ sent_at=timezone.now(),+ )+ EmailThreadParticipant.objects.for_team(self.team.id).create(+ team=self.team,+ thread=thread,+ email="[email protected]",+ display_name="Example customer",+ kind=EmailThreadParticipantKind.CUSTOMER,+ )+ orphaned_content = Comment.objects.create(+ team=self.team,+ scope=EMAIL_THREAD_COMMENT_SCOPE,+ item_id=str(thread.id),+ content="Captured before its envelope was written",+ )+ unrelated = Comment.objects.create(+ team=self.team,+ scope=EMAIL_THREAD_COMMENT_SCOPE,+ item_id="different-thread",+ content="Keep this content",+ )++ delete_email_thread(team_id=self.team.id, thread_id=thread.id)++ assert not EmailThread.objects.for_team(self.team.id).filter(id=thread.id).exists()+ assert not EmailThreadMessage.objects.for_team(self.team.id).filter(id=message.id).exists()+ assert not EmailThreadParticipant.objects.for_team(self.team.id).filter(thread_id=thread.id).exists()+ assert not Comment.objects.filter(id__in=[message.comment_id, orphaned_content.id]).exists()+ assert Comment.objects.filter(id=unrelated.id).exists()