Skip to content

: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.

fix(conversations): stop duplicate support replies (#78936)

Alex V74cc76155035
diff --git a/posthog/api/comments.py b/posthog/api/comments.py
index ac9d65db2641..6e03116181d4 100644
--- a/posthog/api/comments.py
+++ b/posthog/api/comments.py
@@ -9,8 +9,8 @@ from django.utils import timezone
import structlog
import posthoganalytics
-from drf_spectacular.utils import extend_schema, extend_schema_field
-from rest_framework import exceptions, pagination, serializers, viewsets
+from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field
+from rest_framework import exceptions, pagination, serializers, status, viewsets
from rest_framework.exceptions import ErrorDetail
from rest_framework.generics import get_object_or_404
from rest_framework.request import Request
@@ -39,6 +39,8 @@ from posthog.models.integration import Integration, SlackIntegration
from posthog.tasks.comment_slack_sync import backfill_comment_slack_thread
from posthog.tasks.email import send_discussions_mentioned
+from products.conversations.backend import reply_dedupe
+
if TYPE_CHECKING:
from posthog.rbac.user_access_control import UserAccessControl
@@ -515,6 +517,11 @@ class CommentSerializer(serializers.ModelSerializer):
return updated_instance
+class CommentErrorSerializer(serializers.Serializer):
+ detail = serializers.CharField(help_text="Human-readable explanation of what went wrong.")
+ error_type = serializers.CharField(required=False, help_text="Stable machine-readable identifier for the failure.")
+
+
class CommentPagination(pagination.CursorPagination):
ordering = "-created_at"
page_size = 100
@@ -656,6 +663,79 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelV
def list(self, request, *args, **kwargs):
return super().list(request, *args, **kwargs)
+ def _build_reply_fingerprint(self, validated_data: dict[str, Any]) -> "reply_dedupe.ReplyFingerprint | None":
+ created_by = validated_data.get("created_by")
+ source_comment = validated_data.get("source_comment")
+ return reply_dedupe.ReplyFingerprint.build(
+ team_id=self.team_id,
+ created_by_id=getattr(created_by, "id", None),
+ scope=validated_data.get("scope"),
+ item_id=validated_data.get("item_id"),
+ content=validated_data.get("content"),
+ rich_content=validated_data.get("rich_content"),
+ item_context=validated_data.get("item_context"),
+ source_comment_id=getattr(source_comment, "id", None),
+ is_task=validated_data.get("is_task"),
+ has_unverifiable_metadata=bool(validated_data.get("mentions") or validated_data.get("slug")),
+ )
+
+ def _created_response(self, serializer: serializers.BaseSerializer[Any]) -> Response:
+ data = serializer.data
+ return Response(data, status=status.HTTP_201_CREATED, headers=self.get_success_headers(data))
+
+ @extend_schema(
+ responses={
+ 200: OpenApiResponse(
+ response=CommentSerializer,
+ description=(
+ "An identical support message was already created by a recent request. "
+ "The original comment is returned and nothing new is written."
+ ),
+ ),
+ 201: OpenApiResponse(response=CommentSerializer),
+ 409: OpenApiResponse(
+ response=CommentErrorSerializer,
+ description="An identical support message is still being created by another request.",
+ ),
+ },
+ )
+ def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ """Create a comment.
+
+ Support messages are deduplicated: an identical message from the same author on the same
+ ticket within a short window returns the original comment with a 200 instead of creating a
+ second one, and a 409 while a concurrent request is still creating it.
+ """
+ serializer = self.get_serializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+
+ # Validate first, so the guard runs behind the ticket-editor check in the serializer rather
+ # than reserving a key for a request that was never allowed to write.
+ fingerprint = self._build_reply_fingerprint(serializer.validated_data)
+ if fingerprint is None:
+ self.perform_create(serializer)
+ return self._created_response(serializer)
+
+ def save_comment() -> Comment:
+ self.perform_create(serializer)
+ return cast(Comment, serializer.instance)
+
+ guarded = reply_dedupe.create_deduplicated(fingerprint, save_comment)
+ if guarded.outcome is reply_dedupe.CreateOutcome.CONFLICT:
+ return Response(
+ {
+ "detail": reply_dedupe.REPLY_IN_PROGRESS_DETAIL,
+ "error_type": reply_dedupe.REPLY_IN_PROGRESS_ERROR_TYPE,
+ },
+ status=status.HTTP_409_CONFLICT,
+ )
+ if guarded.outcome is reply_dedupe.CreateOutcome.REPLAYED:
+ # Serialize the stored row directly. Going back through save() would re-fire the
+ # mention notifications the original request already sent.
+ return Response(self.get_serializer(guarded.comment).data)
+
+ return self._created_response(serializer)
+
def _slack_mirror_flag_enabled(self) -> bool:
"""Whether discussions↔Slack sync is on for this user/team.
diff --git a/posthog/api/test/test_comments.py b/posthog/api/test/test_comments.py
index c4523adb8082..b54d3cb16997 100644
--- a/posthog/api/test/test_comments.py
+++ b/posthog/api/test/test_comments.py
@@ -16,10 +16,12 @@ from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.comment import Comment
from posthog.models.comment.utils import build_comment_item_url, extract_plain_text_from_rich_content
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
+from posthog.redis import get_client
from posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV, POSTHOG_AI_APP_CLIENT_ID_DEV
from products.conversations.backend.models import Ticket
from products.conversations.backend.models.constants import Channel, Status
+from products.conversations.backend.reply_dedupe import REPLY_IN_PROGRESS_ERROR_TYPE, ReplyFingerprint, reserve
from ee.models.rbac.access_control import AccessControl
@@ -1458,6 +1460,88 @@ class TestComments(APIBaseTest, QueryMatchingTest):
assert entry.detail["changes"][0]["after"] == "plain note"
+# The Support composer posts its replies through this endpoint, and both gateways and operators
+# retry those requests. The guard's own behavior is covered in
+# products/conversations/backend/tests/test_reply_dedupe.py; these are the wiring cases.
+class TestCommentsSupportReplyDedupe(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ get_client().flushall()
+ self.ticket = Ticket.objects.create_with_number(
+ team=self.team,
+ channel_source=Channel.WIDGET,
+ widget_session_id="dedupe-session",
+ distinct_id="dedupe-user",
+ status=Status.OPEN,
+ )
+
+ def _post(self, **overrides: Any) -> Any:
+ payload: dict[str, Any] = {
+ "content": "Have you tried clearing the cache?",
+ "scope": "conversations_ticket",
+ "item_id": str(self.ticket.id),
+ "item_context": {"author_type": "support", "is_private": False},
+ }
+ payload.update(overrides)
+ return self.client.post(f"/api/projects/{self.team.id}/comments", payload, format="json")
+
+ @mock.patch("posthog.api.comments.produce_discussion_mention_events")
+ @mock.patch("posthog.tasks.email.send_discussions_mentioned.delay")
+ def test_retried_support_reply_returns_the_original_without_notifying_twice(
+ self, mock_send_email: mock.MagicMock, mock_produce_events: mock.MagicMock
+ ) -> None:
+ mentioned = User.objects.create_and_join(self.organization, "[email protected]", None)
+ rich_content = {
+ "type": "doc",
+ "content": [{"type": "paragraph", "content": [{"type": "ph-mention", "attrs": {"id": mentioned.id}}]}],
+ }
+
+ first = self._post(rich_content=rich_content)
+ second = self._post(rich_content=rich_content)
+
+ assert first.status_code == status.HTTP_201_CREATED
+ assert second.status_code == status.HTTP_200_OK
+ assert second.json()["id"] == first.json()["id"]
+ assert Comment.objects.filter(scope="conversations_ticket", item_id=str(self.ticket.id)).count() == 1
+ assert mock_send_email.call_count == 1
+ assert mock_produce_events.call_count == 1
+
+ def test_reply_still_being_created_returns_a_conflict(self) -> None:
+ fingerprint = ReplyFingerprint.build(
+ team_id=self.team.id,
+ created_by_id=self.user.id,
+ scope="conversations_ticket",
+ item_id=str(self.ticket.id),
+ content="Have you tried clearing the cache?",
+ rich_content=None,
+ item_context={"author_type": "support", "is_private": False},
+ )
+ assert fingerprint is not None
+ reserve(fingerprint)
+
+ response = self._post()
+
+ assert response.status_code == status.HTTP_409_CONFLICT
+ assert response.json()["error_type"] == REPLY_IN_PROGRESS_ERROR_TYPE
+ assert not Comment.objects.filter(scope="conversations_ticket").exists()
+
+ @parameterized.expand(
+ [
+ ("internal_ticket_discussion", {"scope": "Ticket"}),
+ ("customer_message", {"item_context": {"author_type": "customer", "is_private": False}}),
+ ("task", {"is_task": True}),
+ ("notebook_comment", {"scope": "Notebook", "item_context": None}),
+ ]
+ )
+ def test_non_support_messages_are_still_created_twice(self, _name: str, overrides: dict[str, Any]) -> None:
+ first = self._post(**overrides)
+ second = self._post(**overrides)
+
+ assert first.status_code == status.HTTP_201_CREATED
+ assert second.status_code == status.HTTP_201_CREATED
+ assert second.json()["id"] != first.json()["id"]
+
+
TICKET_SCOPE_CASES = [("conversations_ticket",), ("Ticket",)]
diff --git a/products/conversations/backend/api/tests/test_tickets.py b/products/conversations/backend/api/tests/test_tickets.py
index 6bbe32b8bee9..c8d9aa264ba9 100644
--- a/products/conversations/backend/api/tests/test_tickets.py
+++ b/products/conversations/backend/api/tests/test_tickets.py
@@ -28,6 +28,7 @@ from posthog.hogql.query import execute_hogql_query
from posthog.models import ActivityLog, Comment, Organization, Tag, Team, User
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.utils import generate_random_token_personal, hash_key_value
+from posthog.redis import get_client
from posthog.test.persons import create_person
from products.conversations.backend.api.ticket_filters import query_params_to_view_filters
@@ -35,6 +36,7 @@ from products.conversations.backend.api.tickets import TicketReplyRequestSeriali
from products.conversations.backend.models import Ticket, TicketAssignment, TicketView
from products.conversations.backend.models.constants import Channel, ChannelDetail, Priority, Status
from products.conversations.backend.person_lookup import PERSON_EMAIL_LOOKUP_QUERY, _get_persons_by_email
+from products.conversations.backend.reply_dedupe import REPLY_IN_PROGRESS_ERROR_TYPE, ReplyFingerprint, reserve
from ee.clickhouse.materialized_columns.columns import get_bloom_filter_lower_index_name
from ee.models.rbac.access_control import AccessControl
@@ -2325,6 +2327,8 @@ class TestTicketReplyAPI(APIBaseTest):
status=Status.OPEN,
)
self.url = f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/reply/"
+ # Reply dedupe reservations live in fakeredis, which is a single process-wide store.
+ get_client().flushall()
@parameterized.expand(
[
@@ -2435,6 +2439,79 @@ class TestTicketReplyAPI(APIBaseTest):
assert not serializer.is_valid()
assert "rich_content" in serializer.errors
+ @patch("products.conversations.backend.signals.send_email_reply")
+ def test_retried_reply_returns_the_original_and_delivers_once(self, mock_send_email_reply, mock_on_commit):
+ # API clients and gateways replay this POST within a second or two, and each delivery that
+ # gets through is a message the customer actually receives twice.
+ self.ticket.email_from = "[email protected]"
+ self.ticket.save(update_fields=["email_from"])
+ self.team.conversations_settings = {"email_enabled": True}
+ self.team.save(update_fields=["conversations_settings"])
+
+ first = self.client.post(self.url, {"message": "On it now"}, format="json")
+ second = self.client.post(self.url, {"message": "On it now"}, format="json")
+
+ assert first.status_code == status.HTTP_201_CREATED
+ assert second.status_code == status.HTTP_200_OK
+ assert second.json() == first.json()
+ assert Comment.objects.filter(scope="conversations_ticket", item_id=str(self.ticket.id)).count() == 1
+ mock_send_email_reply.delay.assert_called_once()
+
+ def test_reply_still_being_created_returns_a_conflict(self, mock_on_commit):
+ fingerprint = ReplyFingerprint.build(
+ team_id=self.team.id,
+ created_by_id=self.user.id,
+ scope="conversations_ticket",
+ item_id=str(self.ticket.id),
+ content="On it now",
+ rich_content=None,
+ item_context={"author_type": "support", "is_private": False},
+ )
+ assert fingerprint is not None
+ reserve(fingerprint)
+
+ response = self.client.post(self.url, {"message": "On it now"}, format="json")
+
+ assert response.status_code == status.HTTP_409_CONFLICT
+ assert response.json()["error_type"] == REPLY_IN_PROGRESS_ERROR_TYPE
+ assert not Comment.objects.filter(scope="conversations_ticket", item_id=str(self.ticket.id)).exists()
+
+ @parameterized.expand(
+ [
+ ("different_privacy", {"is_private": True}),
+ ("different_body", {"message": "Something else"}),
+ ]
+ )
+ def test_a_genuinely_different_reply_is_still_posted(self, mock_on_commit, _name, overrides):
+ self.client.post(self.url, {"message": "On it now"}, format="json")
+
+ response = self.client.post(self.url, {"message": "On it now", **overrides}, format="json")
+
+ assert response.status_code == status.HTTP_201_CREATED
+ assert Comment.objects.filter(scope="conversations_ticket", item_id=str(self.ticket.id)).count() == 2
+
+ def test_reply_replays_a_message_first_sent_through_the_comments_endpoint(self, mock_on_commit):
+ # The composer writes through /comments/ while API clients use /reply/. Both hash into one
+ # keyspace, so a retry that arrives on the other path must not post a second message.
+ created = self.client.post(
+ f"/api/projects/{self.team.id}/comments",
+ {
+ "content": "On it now",
+ "scope": "conversations_ticket",
+ "item_id": str(self.ticket.id),
+ "item_context": {"author_type": "support", "is_private": False},
+ },
+ format="json",
+ )
+ assert created.status_code == status.HTTP_201_CREATED
+
+ replayed = self.client.post(self.url, {"message": "On it now"}, format="json")
+
+ assert replayed.status_code == status.HTTP_200_OK
+ assert replayed.json()["id"] == created.json()["id"]
+ assert replayed.json()["author_type"] == "support"
+ assert Comment.objects.filter(scope="conversations_ticket", item_id=str(self.ticket.id)).count() == 1
+
@patch.object(transaction, "on_commit", side_effect=immediate_on_commit)
class TestAiFeedbackAPI(APIBaseTest):
diff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.py
index 00823c8828e7..adc659059a15 100644
--- a/products/conversations/backend/api/tickets.py
+++ b/products/conversations/backend/api/tickets.py
@@ -67,6 +67,8 @@ from products.conversations.backend.person_lookup import _get_persons_by_email
from ee.models.rbac.role import Role
+from .. import reply_dedupe
+
if TYPE_CHECKING:
from posthog.models import User
@@ -1202,7 +1204,19 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessContro
parameters=[TICKET_ID_PARAM],
request=TicketReplyRequestSerializer,
responses={
+ 200: OpenApiResponse(
+ response=TicketMessageSerializer,
+ description=(
+ "An identical message was already posted by a recent request. The original "
+ "message is returned and nothing new is written."
+ ),
+ ),
201: OpenApiResponse(response=TicketMessageSerializer),
+ 400: OpenApiResponse(response=TicketErrorSerializer),
+ 409: OpenApiResponse(
+ response=TicketErrorSerializer,
+ description="An identical message is still being created by another request.",
+ ),
},
)
@action(
@@ -1217,6 +1231,10 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessContro
With is_private=false, the reply is delivered to the customer via the
ticket's channel (email, Slack, Teams, GitHub). With is_private=true,
the message is stored as an internal note only visible to team members.
+
+ Retrying an identical message from the same author within a short window returns the
+ original message with a 200 rather than posting it twice, and a 409 while a concurrent
+ request is still creating it.
"""
ticket = self.get_object()
@@ -1230,21 +1248,48 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessContro
serializer.is_valid(raise_exception=True)
data = serializer.validated_data
- is_private = data["is_private"]
+ item_context = {"author_type": "support", "is_private": data["is_private"]}
+
+ def create_comment() -> Comment:
+ return Comment.objects.create(
+ team=self.team,
+ created_by=request.user,
+ scope="conversations_ticket",
+ item_id=str(ticket.id),
+ content=data["message"],
+ rich_content=data.get("rich_content"),
+ item_context=item_context,
+ )
- comment = Comment.objects.create(
- team=self.team,
- created_by=request.user,
+ fingerprint = reply_dedupe.ReplyFingerprint.build(
+ team_id=self.team_id,
+ created_by_id=request.user.id,
scope="conversations_ticket",
item_id=str(ticket.id),
content=data["message"],
rich_content=data.get("rich_content"),
- item_context={"author_type": "support", "is_private": is_private},
+ item_context=item_context,
)
+ if fingerprint is None:
+ return self._reply_response(create_comment(), ticket, created=True)
+ guarded = reply_dedupe.create_deduplicated(fingerprint, create_comment)
+ if guarded.outcome is reply_dedupe.CreateOutcome.CONFLICT:
+ return Response(
+ {
+ "detail": reply_dedupe.REPLY_IN_PROGRESS_DETAIL,
+ "error_type": reply_dedupe.REPLY_IN_PROGRESS_ERROR_TYPE,
+ },
+ status=drf_status.HTTP_409_CONFLICT,
+ )
+ return self._reply_response(
+ cast(Comment, guarded.comment), ticket, created=guarded.outcome is reply_dedupe.CreateOutcome.CREATED
+ )
+
+ def _reply_response(self, comment: Comment, ticket: Ticket, *, created: bool) -> Response:
return Response(
TicketMessageSerializer(self._serialize_message(comment, ticket)).data,
- status=drf_status.HTTP_201_CREATED,
+ status=drf_status.HTTP_201_CREATED if created else drf_status.HTTP_200_OK,
)
@extend_schema(
diff --git a/products/conversations/backend/reply_dedupe.py b/products/conversations/backend/reply_dedupe.py
new file mode 100644
index 000000000000..6fd8a9ea6d84
--- /dev/null
+++ b/products/conversations/backend/reply_dedupe.py
@@ -0,0 +1,345 @@
+"""Idempotency guard for team-authored support messages.
+
+Two POST paths create them, and both get retried in the wild: gateways and API clients replay
+the request within a second, and an operator whose send looks like it failed sends the same text
+again. Dedupe on the validated request the server already has, so neither caller needs to supply
+an idempotency key.
+
+Redis access goes through ``posthog.redis.get_client()`` rather than the Django cache. The default
+cache alias is replica-aware, so the ``GET`` that follows a lost ``SET NX`` could read a lagging
+replica and report a conflict for a reservation that already resolved. This client is bound to
+``REDIS_URL`` alone, and it exposes the Lua needed for the owner-token compares below, which
+``cache.add``/``get``/``set`` cannot do atomically.
+"""
+
+import json
+import uuid
+import hashlib
+from collections.abc import Callable
+from dataclasses import dataclass
+from datetime import datetime, timedelta
+from enum import Enum
+from typing import Any
+
+from django.utils import timezone
+
+import structlog
+
+from posthog.models.comment import Comment
+from posthog.redis import get_client
+
+logger = structlog.get_logger(__name__)
+
+# A reservation only has to outlive one request, and a worker killed mid-create self-heals this
+# many seconds later instead of blocking that exact message for the full replay window.
+IN_FLIGHT_TTL_SECONDS = 30
+# How long a created message stays replayable. Covers the automated retries (0-1s apart) and the
+# operator who resends after an unconfirmed send (tens of seconds).
+REPLAY_WINDOW_SECONDS = 120
+
+SUPPORT_TICKET_SCOPE = "conversations_ticket"
+SUPPORT_AUTHOR_TYPE = "support"
+
+REPLY_IN_PROGRESS_ERROR_TYPE = "reply_in_progress"
+REPLY_IN_PROGRESS_DETAIL = "This message is already being sent. Check the thread before sending it again."
+
+# Both endpoints hash into one keyspace, so a retry that switches paths still replays. Bump the
+# version when the fingerprint's contents change, so old entries can't be read under new rules.
+_KEY_PREFIX = "conversations:reply_dedupe:v1:"
+_IN_FLIGHT_VALUE_PREFIX = "inflight:"
+_COMMENT_VALUE_PREFIX = "comment:"
+
+# Compare the owner token before writing, so a creator that stalled past its own TTL cannot
+# overwrite or delete the reservation a later attempt has since taken.
+_PUBLISH_SCRIPT = """
+if redis.call('GET', KEYS[1]) ~= ARGV[1] then
+ return 0
+end
+redis.call('SET', KEYS[1], ARGV[2], 'EX', ARGV[3])
+return 1
+"""
+
+_RELEASE_SCRIPT = """
+if redis.call('GET', KEYS[1]) ~= ARGV[1] then
+ return 0
+end
+return redis.call('DEL', KEYS[1])
+"""
+
+
+class ReservationState(Enum):
+ # Free to create, either because we took the reservation or because Redis couldn't answer.
+ ACQUIRED = "acquired"
+ # Another attempt holds the reservation and hasn't finished creating yet.
+ IN_FLIGHT = "in_flight"
+ # An earlier attempt already created this message.
+ REPLAY = "replay"
+
+
+@dataclass(frozen=True, kw_only=True)
+class Reservation:
+ state: ReservationState
+ key: str
+ # Absent when we failed open, which makes publish and release no-ops.
+ owner_token: str | None = None
+ comment_id: str | None = None
+
+
+@dataclass(frozen=True, kw_only=True)
+class ReplyFingerprint:
+ """The immutable identity of a support-message create request.
+
+ Two requests with the same fingerprint are the same message: same team, ticket, author,
+ thread position, body, and privacy. ``build`` returns None for anything this guard must not
+ collapse.
+ """
+
+ team_id: int
+ scope: str
+ item_id: str
+ created_by_id: int
+ source_comment_id: str | None
+ content: str
+ rich_content: Any
+ item_context: dict[str, Any]
+
+ @classmethod
+ def build(
+ cls,
+ *,
+ team_id: int,
+ created_by_id: int | None,
+ scope: Any,
+ item_id: Any,
+ content: Any,
+ rich_content: Any,
+ item_context: Any,
+ source_comment_id: Any = None,
+ is_task: Any = False,
+ has_unverifiable_metadata: bool = False,
+ ) -> "ReplyFingerprint | None":
+ if scope != SUPPORT_TICKET_SCOPE or not item_id or created_by_id is None:
+ return None
+ if not isinstance(item_context, dict) or item_context.get("author_type") != SUPPORT_AUTHOR_TYPE:
+ return None
+ # A task carries state (completion) that a replayed response would misreport, and an emoji
+ # reaction is a toggle rather than a message.
+ if is_task or item_context.get("is_emoji"):
+ return None
+ # Explicit mentions and the notification slug are consumed by the serializer and never
+ # persisted, so a replay can't confirm the stored row came from the same request.
+ if has_unverifiable_metadata:
+ return None
+ if not isinstance(content, str):
+ return None
+
+ return cls(
+ team_id=team_id,
+ scope=scope,
+ item_id=str(item_id),
+ created_by_id=created_by_id,
+ source_comment_id=str(source_comment_id) if source_comment_id else None,
+ content=content,
+ rich_content=rich_content,
+ item_context=item_context,
+ )
+
+ @property
+ def key(self) -> str:
+ canonical = json.dumps(
+ {
+ "team_id": self.team_id,
+ "scope": self.scope,
+ "item_id": self.item_id,
+ "created_by_id": self.created_by_id,
+ "source_comment_id": self.source_comment_id,
+ "content": self.content,
+ "rich_content": self.rich_content,
+ "item_context": self.item_context,
+ },
+ sort_keys=True,
+ separators=(",", ":"),
+ default=str,
+ )
+ # Only the digest reaches Redis, so no message content lands in a key.
+ return f"{_KEY_PREFIX}{hashlib.sha256(canonical.encode()).hexdigest()}"
+
+ def matches(self, comment: Comment) -> bool:
+ """Whether this persisted comment is the message this request asked for."""
+ if comment.deleted or comment.version != 0:
+ return False
+ if (
+ comment.team_id != self.team_id
+ or comment.scope != self.scope
+ or comment.item_id != self.item_id
+ or comment.created_by_id != self.created_by_id
+ or comment.content != self.content
+ or comment.rich_content != self.rich_content
+ ):
+ return False
+ if str(comment.source_comment_id or "") != (self.source_comment_id or ""):
+ return False
+ # Delivery bookkeeping is merged into item_context after creation, so require the
+ # request's own fields rather than equality.
+ persisted_context = comment.item_context or {}
+ return all(persisted_context.get(field) == value for field, value in self.item_context.items())
+
+ def find_persisted_match(self, *, created_after: datetime) -> Comment | None:
+ """The most recent row this request would have created, if some earlier attempt already did.
+
+ This is what closes the window where a create commits but its publication never lands: the
+ reservation is gone, so only the database can tell the retry that its message exists.
+ """
+ candidates = Comment.objects.filter(
+ team_id=self.team_id,
+ scope=self.scope,
+ item_id=self.item_id,
+ created_by_id=self.created_by_id,
+ content=self.content,
+ deleted=False,
+ version=0,
+ created_at__gte=created_after,
+ ).order_by("-created_at")[:20]
+ return next((comment for comment in candidates if self.matches(comment)), None)
+
+ def load_replay_target(self, comment_id: str | None) -> Comment | None:
+ """Re-verify a published mapping before serving it as a replay."""
+ if not comment_id:
+ return None
+ comment = Comment.objects.filter(team_id=self.team_id, pk=comment_id).first()
+ if comment is None or not self.matches(comment):
+ logger.warning("conversations_reply_dedupe_stale_mapping", comment_id=comment_id)
+ return None
+ return comment
+
+
+class CreateOutcome(Enum):
+ CREATED = "created"
+ # An identical message already exists; return it without writing anything.
+ REPLAYED = "replayed"
+ # A concurrent request is still creating this message, and we can't yet say which row it is.
+ CONFLICT = "conflict"
+
+
+@dataclass(frozen=True, kw_only=True)
+class GuardedCreate:
+ outcome: CreateOutcome
+ comment: Comment | None = None
+
+
+def create_deduplicated(fingerprint: ReplyFingerprint, create: Callable[[], Comment]) -> GuardedCreate:
+ """Run ``create`` at most once per fingerprint, and report what happened.
+
+ Both support-message endpoints go through here so the protocol can't drift between them. The
+ caller owns the response shape: a REPLAYED outcome is theirs to render as a 200 and a CONFLICT
+ as a 409. Exceptions from ``create`` propagate unchanged after the reservation is settled.
+ """
+ reservation = reserve(fingerprint)
+ if reservation.state is ReservationState.REPLAY:
+ replayed = fingerprint.load_replay_target(reservation.comment_id)
+ if replayed is not None:
+ return GuardedCreate(outcome=CreateOutcome.REPLAYED, comment=replayed)
+ # A mapping we can't verify is treated as no mapping, rather than serving an unrelated row.
+ elif reservation.state is ReservationState.IN_FLIGHT:
+ return GuardedCreate(outcome=CreateOutcome.CONFLICT)
+
+ attempted_at = timezone.now()
+ already_created = fingerprint.find_persisted_match(created_after=_replay_window_start(attempted_at))
+ if already_created is not None:
+ publish(reservation, already_created.id)
+ return GuardedCreate(outcome=CreateOutcome.REPLAYED, comment=already_created)
+
+ try:
+ comment = create()
+ except Exception:
+ # Mention fan-out and post_save receivers run after the INSERT, so an exception does not
+ # mean the row is absent. Releasing blindly would make an already-delivered message
+ # immediately repeatable.
+ recovered = fingerprint.find_persisted_match(created_after=attempted_at)
+ if recovered is not None:
+ publish(reservation, recovered.id)
+ else:
+ release(reservation)
+ raise
+
+ publish(reservation, comment.id)
+ return GuardedCreate(outcome=CreateOutcome.CREATED, comment=comment)
+
+
+def _replay_window_start(attempted_at: datetime) -> datetime:
+ return attempted_at - timedelta(seconds=REPLAY_WINDOW_SECONDS)
+
+
+def reserve(fingerprint: ReplyFingerprint) -> Reservation:
+ """Claim the right to create this message, or report who got there first.
+
+ Fails open (ACQUIRED without a token) once Redis has failed twice. That degrades to the caller's
+ recent-row lookup, which catches a retry of a message that already committed. It does not
+ serialize two concurrent first attempts: while Redis is unreachable, both can pass that lookup
+ before either inserts, and the customer receives the message twice. Closing that last race needs
+ a durable idempotency key or a uniqueness constraint, which this design deliberately avoids, so
+ the retry here is what keeps a single dropped connection from widening the window.
+ """
+ key = fingerprint.key
+ token = f"{_IN_FLIGHT_VALUE_PREFIX}{uuid.uuid4()}"
+ for attempt in range(2):
+ try:
+ client = get_client()
+ if client.set(key, token, nx=True, ex=IN_FLIGHT_TTL_SECONDS):
+ return Reservation(state=ReservationState.ACQUIRED, key=key, owner_token=token)
+ held = client.get(key)
+ if held is not None:
+ return _classify_held_value(key, held, token)
+ # The holder's entry expired or was evicted between the SET and the GET, so try again
+ # instead of reporting a conflict that no longer exists.
+ except Exception:
+ if attempt == 0:
+ continue
+ logger.warning("conversations_reply_dedupe_reserve_error", key=key, exc_info=True)
+ return Reservation(state=ReservationState.ACQUIRED, key=key)
+
+
+def publish(reservation: Reservation, comment_id: Any) -> None:
+ """Point the reservation at the created message so later retries replay it."""
+ if reservation.owner_token is None:
+ return
+ value = f"{_COMMENT_VALUE_PREFIX}{comment_id}"
+ for attempt in range(2):
+ try:
+ get_client().eval(
+ _PUBLISH_SCRIPT, 1, reservation.key, reservation.owner_token, value, REPLAY_WINDOW_SECONDS
+ )
+ return
+ except Exception:
+ if attempt == 0:
+ continue
+ # The message is already committed. Raising here would turn a confirmed send into an
+ # error the client is likely to retry, and the recent-row lookup covers that retry.
+ logger.exception("conversations_reply_dedupe_publish_failed", key=reservation.key)
+
+
+def release(reservation: Reservation) -> None:
+ """Give up the reservation so an immediate retry isn't blocked for the full in-flight TTL."""
+ if reservation.owner_token is None:
+ return
+ try:
+ get_client().eval(_RELEASE_SCRIPT, 1, reservation.key, reservation.owner_token)
+ except Exception:
+ logger.warning("conversations_reply_dedupe_release_error", key=reservation.key, exc_info=True)
+
+
+def _classify_held_value(key: str, held: Any, token: str) -> Reservation:
+ value = held.decode() if isinstance(held, bytes) else str(held)
+ if value == token:
+ # Our own SET landed even though its reply never reached us, so we still own the reservation.
+ return Reservation(state=ReservationState.ACQUIRED, key=key, owner_token=token)
+ if value.startswith(_COMMENT_VALUE_PREFIX):
+ return Reservation(
+ state=ReservationState.REPLAY,
+ key=key,
+ comment_id=value.removeprefix(_COMMENT_VALUE_PREFIX),
+ )
+ if value.startswith(_IN_FLIGHT_VALUE_PREFIX):
+ return Reservation(state=ReservationState.IN_FLIGHT, key=key)
+ logger.warning("conversations_reply_dedupe_malformed_value", key=key)
+ return Reservation(state=ReservationState.ACQUIRED, key=key)
diff --git a/products/conversations/backend/tests/test_reply_dedupe.py b/products/conversations/backend/tests/test_reply_dedupe.py
new file mode 100644
index 000000000000..f12d7db504ff
--- /dev/null
+++ b/products/conversations/backend/tests/test_reply_dedupe.py
@@ -0,0 +1,245 @@
+from datetime import timedelta
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.models.comment import Comment
+from posthog.redis import get_client
+
+from products.conversations.backend import reply_dedupe
+from products.conversations.backend.reply_dedupe import (
+ CreateOutcome,
+ ReplyFingerprint,
+ ReservationState,
+ create_deduplicated,
+ reserve,
+)
+
+
+class _DroppedBeforeTheWrite:
+ def set(self, *args, **kwargs):
+ raise ConnectionError("connection reset before the write")
+
+
+class _DroppedAfterTheWrite:
+ # The reservation lands and its reply is lost, so a retry finds its own token in the key.
+ def __init__(self, client):
+ self._client = client
+
+ def set(self, *args, **kwargs):
+ self._client.set(*args, **kwargs)
+ raise TimeoutError("the reply never arrived")
+
+
+class TestReplyDedupe(BaseTest):
+ def setUp(self):
+ super().setUp()
+ # fakeredis keeps one FakeServer per process, and TEST_clear_clients() drops the client
+ # without dropping its data, so reservations would otherwise leak between tests.
+ get_client().flushall()
+ self.item_id = "11111111-1111-4111-8111-111111111111"
+
+ def _fingerprint(self, **overrides) -> ReplyFingerprint:
+ fields: dict = {
+ "team_id": self.team.id,
+ "created_by_id": self.user.id,
+ "scope": "conversations_ticket",
+ "item_id": self.item_id,
+ "content": "Have you tried clearing the cache?",
+ "rich_content": None,
+ "item_context": {"author_type": "support", "is_private": False},
+ }
+ fields.update(overrides)
+ fingerprint = ReplyFingerprint.build(**fields)
+ assert fingerprint is not None
+ return fingerprint
+
+ def _create_comment(self, **overrides) -> Comment:
+ fields: dict = {
+ "team": self.team,
+ "created_by": self.user,
+ "scope": "conversations_ticket",
+ "item_id": self.item_id,
+ "content": "Have you tried clearing the cache?",
+ "item_context": {"author_type": "support", "is_private": False},
+ }
+ fields.update(overrides)
+ return Comment.objects.create(**fields)
+
+ def test_identical_requests_produce_one_key(self):
+ assert self._fingerprint().key == self._fingerprint().key
+
+ @parameterized.expand(
+ [
+ ("privacy", {"item_context": {"author_type": "support", "is_private": True}}),
+ ("content", {"content": "Different body"}),
+ ("ticket", {"item_id": "22222222-2222-4222-8222-222222222222"}),
+ ("thread_parent", {"source_comment_id": "33333333-3333-4333-8333-333333333333"}),
+ ("author", {"created_by_id": 987654}),
+ ("rich_content", {"rich_content": {"type": "doc", "content": []}}),
+ ]
+ )
+ def test_distinguishing_fields_change_the_key(self, _name: str, overrides: dict):
+ assert self._fingerprint(**overrides).key != self._fingerprint().key
+
+ def test_key_carries_no_message_content(self):
+ secret = "customer account number 4242"
+ assert secret not in self._fingerprint(content=secret).key
+
+ @parameterized.expand(
+ [
+ ("dashboard_comment", {"scope": "Dashboard"}),
+ ("internal_ticket_discussion", {"scope": "Ticket"}),
+ ("customer_message", {"item_context": {"author_type": "customer", "is_private": False}}),
+ ("task", {"is_task": True}),
+ ("emoji_reaction", {"item_context": {"author_type": "support", "is_emoji": True}}),
+ ("explicit_mentions_or_slug", {"has_unverifiable_metadata": True}),
+ ("no_ticket", {"item_id": None}),
+ ("no_author", {"created_by_id": None}),
+ ]
+ )
+ def test_ineligible_requests_are_not_deduplicated(self, _name: str, overrides: dict):
+ fields: dict = {
+ "team_id": self.team.id,
+ "created_by_id": self.user.id,
+ "scope": "conversations_ticket",
+ "item_id": self.item_id,
+ "content": "Have you tried clearing the cache?",
+ "rich_content": None,
+ "item_context": {"author_type": "support", "is_private": False},
+ }
+ fields.update(overrides)
+ assert ReplyFingerprint.build(**fields) is None
+
+ def test_retry_replays_the_first_message_without_creating_a_second(self):
+ first = create_deduplicated(self._fingerprint(), self._create_comment)
+ second = create_deduplicated(self._fingerprint(), self._fail_if_called)
+
+ assert first.outcome is CreateOutcome.CREATED
+ assert second.outcome is CreateOutcome.REPLAYED
+ assert second.comment is not None and second.comment.id == first.comment.id # type: ignore[union-attr]
+ assert Comment.objects.count() == 1
+
+ def test_concurrent_attempt_conflicts_instead_of_creating(self):
+ reserve(self._fingerprint())
+
+ guarded = create_deduplicated(self._fingerprint(), self._fail_if_called)
+
+ assert guarded.outcome is CreateOutcome.CONFLICT
+ assert guarded.comment is None
+
+ def test_released_reservation_lets_an_immediate_retry_through(self):
+ fingerprint = self._fingerprint()
+ with self.assertRaises(RuntimeError):
+ create_deduplicated(fingerprint, self._raise_before_persisting)
+
+ guarded = create_deduplicated(fingerprint, self._create_comment)
+
+ assert guarded.outcome is CreateOutcome.CREATED
+
+ def test_failure_after_the_row_persists_still_blocks_a_duplicate(self):
+ fingerprint = self._fingerprint()
+ with self.assertRaises(RuntimeError):
+ create_deduplicated(fingerprint, self._persist_then_raise)
+
+ guarded = create_deduplicated(fingerprint, self._fail_if_called)
+
+ assert guarded.outcome is CreateOutcome.REPLAYED
+ assert Comment.objects.count() == 1
+
+ def test_committed_row_is_replayed_when_publication_never_landed(self):
+ # The create/publish crash window: the row exists but Redis has no mapping for it, so only
+ # the recent-row lookup can stop the retry from posting the message twice.
+ existing = self._create_comment()
+
+ guarded = create_deduplicated(self._fingerprint(), self._fail_if_called)
+
+ assert guarded.outcome is CreateOutcome.REPLAYED
+ assert guarded.comment is not None and guarded.comment.id == existing.id
+
+ @parameterized.expand(
+ [
+ ("deleted", {"deleted": True}),
+ ("edited", {"version": 3}),
+ ("different_privacy", {"item_context": {"author_type": "support", "is_private": True}}),
+ ]
+ )
+ def test_a_row_that_no_longer_matches_is_not_replayed(self, _name: str, overrides: dict):
+ self._create_comment(**overrides)
+
+ guarded = create_deduplicated(self._fingerprint(), self._create_comment)
+
+ assert guarded.outcome is CreateOutcome.CREATED
+
+ def test_stale_mapping_does_not_serve_an_unrelated_row(self):
+ fingerprint = self._fingerprint()
+ create_deduplicated(fingerprint, self._create_comment)
+ Comment.objects.update(content="edited by someone else", version=1)
+
+ guarded = create_deduplicated(fingerprint, self._create_comment)
+
+ assert guarded.outcome is CreateOutcome.CREATED
+
+ def test_a_message_older_than_the_replay_window_is_not_replayed(self):
+ old = self._create_comment()
+ Comment.objects.filter(pk=old.pk).update(
+ created_at=timezone.now() - timedelta(seconds=reply_dedupe.REPLAY_WINDOW_SECONDS + 60)
+ )
+
+ guarded = create_deduplicated(self._fingerprint(), self._create_comment)
+
+ assert guarded.outcome is CreateOutcome.CREATED
+
+ @parameterized.expand(
+ [
+ ("another_attempt_holds_it", "inflight:abc", ReservationState.IN_FLIGHT),
+ # A value we can't parse must not block the message; the recent-row lookup guards the create.
+ ("unparseable", "garbage", ReservationState.ACQUIRED),
+ ]
+ )
+ def test_an_existing_reservation_value_decides_the_state(self, _name: str, stored: str, expected: ReservationState):
+ fingerprint = self._fingerprint()
+ get_client().set(fingerprint.key, stored)
+
+ assert reserve(fingerprint).state is expected
+
+ @parameterized.expand(
+ [
+ ("the_write_never_ran", lambda client: _DroppedBeforeTheWrite()),
+ ("the_write_landed_and_its_reply_was_lost", lambda client: _DroppedAfterTheWrite(client)),
+ ]
+ )
+ def test_one_dropped_connection_does_not_give_up_the_reservation(self, _name: str, flaky_client):
+ # Failing open on the first error hands back an ownerless reservation, and two concurrent
+ # attempts then both create the message. A single reset connection must not cost that.
+ client = get_client()
+
+ with patch.object(reply_dedupe, "get_client", side_effect=[flaky_client(client), client]):
+ reservation = reserve(self._fingerprint())
+
+ assert reservation.state is ReservationState.ACQUIRED
+ assert reservation.owner_token is not None
+
+ def test_redis_failure_falls_back_to_the_database(self):
+ # Losing Redis must degrade to database-backed replay detection, not to duplicate messages.
+ existing = self._create_comment()
+
+ with patch.object(reply_dedupe, "get_client", side_effect=ConnectionError("redis down")):
+ guarded = create_deduplicated(self._fingerprint(), self._fail_if_called)
+
+ assert guarded.outcome is CreateOutcome.REPLAYED
+ assert guarded.comment is not None and guarded.comment.id == existing.id
+
+ def _fail_if_called(self) -> Comment:
+ raise AssertionError("the guard should not have created a second message")
+
+ def _raise_before_persisting(self) -> Comment:
+ raise RuntimeError("validation blew up before the insert")
+
+ def _persist_then_raise(self) -> Comment:
+ self._create_comment()
+ raise RuntimeError("mention fan-out failed after the insert")
diff --git a/products/conversations/frontend/generated/api.ts b/products/conversations/frontend/generated/api.ts
index d2841783b0b9..36d5e27fccd6 100644
--- a/products/conversations/frontend/generated/api.ts
+++ b/products/conversations/frontend/generated/api.ts
@@ -507,6 +507,10 @@ export const getConversationsTicketsReplyCreateUrl = (projectId: string, id: str
* With is_private=false, the reply is delivered to the customer via the
* ticket's channel (email, Slack, Teams, GitHub). With is_private=true,
* the message is stored as an internal note only visible to team members.
+ *
+ * Retrying an identical message from the same author within a short window returns the
+ * original message with a 200 rather than posting it twice, and a 409 while a concurrent
+ * request is still creating it.
*/
export const conversationsTicketsReplyCreate = async (
projectId: string,
diff --git a/products/conversations/frontend/generated/api.zod.ts b/products/conversations/frontend/generated/api.zod.ts
index 441f43a590df..0d5c3175becf 100644
--- a/products/conversations/frontend/generated/api.zod.ts
+++ b/products/conversations/frontend/generated/api.zod.ts
@@ -282,6 +282,10 @@ export const ConversationsTicketsNotesPartialUpdateBody = /* @__PURE__ */ zod
* With is_private=false, the reply is delivered to the customer via the
* ticket's channel (email, Slack, Teams, GitHub). With is_private=true,
* the message is stored as an internal note only visible to team members.
+ *
+ * Retrying an identical message from the same author within a short window returns the
+ * original message with a 200 rather than posting it twice, and a 409 while a concurrent
+ * request is still creating it.
*/
export const conversationsTicketsReplyCreateBodyMessageMax = 5000
diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts
index f2f93eace54e..fc8a2d5acd52 100644
--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts
+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts
@@ -1,7 +1,11 @@
+import { MOCK_DEFAULT_USER } from '~/lib/api.mock'
+
import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { userLogic } from 'scenes/userLogic'
import { tagsModel } from '~/models/tagsModel'
import { initKeaTests } from '~/test/init'
@@ -14,6 +18,13 @@ import { EmailReplyBlockedReason, getEmailReplyBlockedReason, supportTicketScene
const FEEDBACK_STORAGE_KEY = 'conversations_ai_reply_feedback'
+/** A logic left mounted keeps polling for messages, into whichever suite builds the same key next. */
+function stopPolling(logic: ReturnType<typeof supportTicketSceneLogic.build> | undefined): void {
+ if (logic?.isMounted()) {
+ logic.unmount()
+ }
+}
+
jest.mock('~/lib/api', () => {
const actual = jest.requireActual('~/lib/api')
return {
@@ -72,6 +83,21 @@ function makeAiComment(id: string, isPrivate: boolean = true): CommentType {
} as unknown as CommentType
}
+function makeSupportComment(overrides: Partial<CommentType> = {}): CommentType {
+ return {
+ id: 'msg-sent-1',
+ content: 'hello',
+ rich_content: null,
+ version: 0,
+ scope: 'conversations_ticket',
+ item_id: 'ticket-1',
+ item_context: { author_type: 'support', is_private: false },
+ created_at: '2026-01-01T00:00:10Z',
+ created_by: MOCK_DEFAULT_USER,
+ ...overrides,
+ } as unknown as CommentType
+}
+
function makeTicket(): Ticket {
return {
id: 'ticket-1',
@@ -320,7 +346,7 @@ describe('supportTicketSceneLogic sendMessage with statusAfterSend', () => {
beforeEach(async () => {
initKeaTests()
- commentsCreateMock.mockReset().mockResolvedValue(undefined)
+ commentsCreateMock.mockReset().mockResolvedValue(makeSupportComment())
ticketGetMock.mockReset().mockResolvedValue(loadedTicket())
ticketUpdateMock.mockReset()
// A non-'new', dash-free id: sendMessage early-returns on 'new' and loadTicket
@@ -330,6 +356,10 @@ describe('supportTicketSceneLogic sendMessage with statusAfterSend', () => {
await expectLogic(logic).toDispatchActions(['setTicket'])
})
+ afterEach(() => {
+ stopPolling(logic)
+ })
+
// "Send and set status" must persist through the same PATCH as the "Save changes" button,
// and must never change who the ticket is assigned to.
test.each<[string, TicketAssignee, TicketStatus]>([
@@ -408,6 +438,161 @@ describe('supportTicketSceneLogic sendMessage with statusAfterSend', () => {
})
})
+describe('supportTicketSceneLogic send outcome handling', () => {
+ let logic: ReturnType<typeof supportTicketSceneLogic.build>
+
+ const commentsCreateMock = api.comments.create as jest.Mock
+ const commentsListMock = api.comments.list as jest.Mock
+ const ticketGetMock = api.conversationsTickets.get as jest.Mock
+ const captureMock = posthog.capture as jest.Mock
+
+ const loadedTicket = (): Ticket => ({ ...makeTicket(), priority: 'medium', assignee: null }) as Ticket
+
+ const rejectWith = (status?: number): void => {
+ commentsCreateMock.mockRejectedValue(Object.assign(new Error('send failed'), { status }))
+ }
+
+ beforeEach(async () => {
+ initKeaTests()
+ commentsCreateMock.mockReset().mockResolvedValue(makeSupportComment())
+ commentsListMock.mockReset().mockResolvedValue({ results: [] })
+ ticketGetMock.mockReset().mockResolvedValue(loadedTicket())
+ captureMock.mockClear()
+ userLogic.actions.loadUserSuccess(MOCK_DEFAULT_USER)
+ logic = supportTicketSceneLogic({ id: 42 })
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['setTicket', 'setMessages'])
+ })
+
+ afterEach(() => {
+ stopPolling(logic)
+ // These cases point the shared mock at failures and pending promises, which would break
+ // every later suite's initial message load.
+ commentsListMock.mockReset().mockResolvedValue({ results: [] })
+ commentsCreateMock.mockReset().mockResolvedValue(makeSupportComment())
+ })
+
+ it('shows the sent message without waiting for the next poll', async () => {
+ const onSuccess = jest.fn()
+
+ await expectLogic(logic, () => {
+ logic.actions.sendMessage('hello', null, false, onSuccess)
+ }).toDispatchActions(['appendMessage'])
+
+ expect(logic.values.messages.map((message) => message.id)).toEqual(['msg-sent-1'])
+ expect(onSuccess).toHaveBeenCalledTimes(1)
+ expect(logic.values.messageSending).toBe(false)
+ })
+
+ // A poll that started before the send must not replace the list with its older snapshot.
+ it('keeps the sent message when an in-flight poll resolves afterwards', async () => {
+ let resolveStalePoll: ((value: { results: CommentType[] }) => void) | undefined
+ commentsListMock.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveStalePoll = resolve
+ })
+ )
+
+ logic.actions.loadMessages()
+ await expectLogic(logic, () => {
+ logic.actions.sendMessage('hello', null, false)
+ }).toDispatchActions(['appendMessage'])
+
+ resolveStalePoll?.({ results: [] })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.messages.map((message) => message.id)).toEqual(['msg-sent-1'])
+ })
+
+ // 429 and 4xx rejections happen before anything is written, so the operator can just resend.
+ // Sending them down the recovery path would tell them to go check a thread that never changed.
+ it.each<[string, number]>([
+ ['throttled', 429],
+ ['rejected', 400],
+ ])('reports a %s send as a plain failure without looking at the thread', async (_name, status) => {
+ rejectWith(status)
+ commentsListMock.mockClear()
+ const onSuccess = jest.fn()
+
+ await expectLogic(logic, () => {
+ logic.actions.sendMessage('hello', null, false, onSuccess)
+ }).toFinishAllListeners()
+
+ expect(commentsListMock).not.toHaveBeenCalled()
+ expect(onSuccess).not.toHaveBeenCalled()
+ expect(captureMock).not.toHaveBeenCalledWith('support reply send unconfirmed', expect.anything())
+ expect(logic.values.messageSending).toBe(false)
+ })
+
+ // A response we never saw, a timeout, a 409 from the server's own dedupe guard, and a 5xx all
+ // leave the same question open: did the message land? If it did, adopt it instead of telling the
+ // operator to resend something the customer already received.
+ it.each<[string, number | undefined]>([
+ ['no response', undefined],
+ ['a timeout', 408],
+ ['a concurrent duplicate', 409],
+ ['a server error', 503],
+ ])('adopts the message that landed despite %s', async (_name, status) => {
+ rejectWith(status)
+ const landed = makeSupportComment({ id: 'msg-landed-1', created_at: new Date().toISOString() })
+ commentsListMock.mockResolvedValue({ results: [landed] })
+ const onSuccess = jest.fn()
+
+ await expectLogic(logic, () => {
+ logic.actions.sendMessage('hello', null, false, onSuccess)
+ }).toDispatchActions(['appendMessage'])
+
+ expect(logic.values.messages.map((message) => message.id)).toEqual(['msg-landed-1'])
+ expect(onSuccess).toHaveBeenCalledTimes(1)
+ expect(commentsCreateMock).toHaveBeenCalledTimes(1)
+ expect(captureMock).not.toHaveBeenCalledWith('support reply send unconfirmed', expect.anything())
+ })
+
+ // Adopting a near-miss would show the operator the wrong message as theirs, so each of these
+ // has to keep the outcome unresolved.
+ it.each<[string, Partial<CommentType>]>([
+ ['a different body', { content: 'something else' }],
+ ['a private note rather than a reply', { item_context: { author_type: 'support', is_private: true } }],
+ ['a colleague as the author', { created_by: { ...MOCK_DEFAULT_USER, id: 9999 } as any }],
+ ['a timestamp outside the replay window', { created_at: '2026-01-01T00:00:10Z' }],
+ ])('does not adopt a message with %s', async (_name, overrides) => {
+ rejectWith(503)
+ commentsListMock.mockResolvedValue({
+ results: [makeSupportComment({ id: 'msg-other-1', created_at: new Date().toISOString(), ...overrides })],
+ })
+ const onSuccess = jest.fn()
+
+ await expectLogic(logic, () => {
+ logic.actions.sendMessage('hello', null, false, onSuccess)
+ }).toFinishAllListeners()
+
+ expect(logic.values.messages).toEqual([])
+ expect(onSuccess).not.toHaveBeenCalled()
+ expect(captureMock).toHaveBeenCalledWith('support reply send unconfirmed', {
+ reason: 'server_error',
+ is_private: false,
+ })
+ })
+
+ it('leaves the outcome unresolved when the recovery lookup also fails', async () => {
+ rejectWith(undefined)
+ commentsListMock.mockRejectedValue(new Error('offline'))
+ const onSuccess = jest.fn()
+
+ await expectLogic(logic, () => {
+ logic.actions.sendMessage('hello', null, false, onSuccess)
+ }).toFinishAllListeners()
+
+ expect(onSuccess).not.toHaveBeenCalled()
+ expect(captureMock).toHaveBeenCalledWith('support reply send unconfirmed', {
+ reason: 'network',
+ is_private: false,
+ })
+ expect(logic.values.messageSending).toBe(false)
+ })
+})
+
describe('supportTicketSceneLogic tag pool refresh', () => {
let logic: ReturnType<typeof supportTicketSceneLogic.build>
@@ -435,6 +620,10 @@ describe('supportTicketSceneLogic tag pool refresh', () => {
tagsListMock.mockClear()
})
+ afterEach(() => {
+ stopPolling(logic)
+ })
+
// A newly typed tag is created globally on save, so the shared pool must reload to surface it
// on other tickets; an already-known tag needs no reload.
it('reloads the shared tag pool when a new tag was saved', async () => {
@@ -482,6 +671,10 @@ describe('supportTicketSceneLogic loadPreviousTickets email gating', () => {
ticketGetMock.mockReset()
})
+ afterEach(() => {
+ stopPolling(logic)
+ })
+
// email_from is attacker-spoofable unless the ticket's identity is positively attested, and
// person.properties.email is customer-controlled analytics with no trusted mapping. Only a
// verified ticket may widen the match by email — otherwise a spoofed sender pulls another
@@ -526,7 +719,7 @@ describe('supportTicketSceneLogic private note editing', () => {
localStorage.clear()
initKeaTests()
noteUpdateMock.mockReset().mockResolvedValue(undefined)
- commentsCreateMock.mockReset().mockResolvedValue(undefined)
+ commentsCreateMock.mockReset().mockResolvedValue(makeSupportComment())
ticketGetMock.mockReset().mockResolvedValue(loadedTicket())
logic = supportTicketSceneLogic({ id: 42 })
logic.mount()
@@ -534,6 +727,10 @@ describe('supportTicketSceneLogic private note editing', () => {
await expectLogic(logic).toDispatchActions(['setTicket', 'setMessages'])
})
+ afterEach(() => {
+ stopPolling(logic)
+ })
+
test('startEditingMessage stashes the in-progress draft and loads the note', async () => {
const draft = { type: 'doc', content: [{ type: 'paragraph', content: [{ type: 'text', text: 'wip' }] }] }
logic.actions.setDraftContent(draft)
diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts
index 4e9a44b1a3ab..de06ab87f938 100644
--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts
+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts
@@ -15,6 +15,7 @@ import {
} from 'kea'
import { loaders } from 'kea-loaders'
import { beforeUnload, router } from 'kea-router'
+import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
@@ -25,9 +26,11 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { getCurrentTeamId } from 'lib/utils/getAppContext'
import { isUUIDLike } from 'lib/utils/guards'
import { markdownToHtml } from 'lib/utils/markdown'
+import { objectsEqual } from 'lib/utils/objects'
import { fullName } from 'lib/utils/strings'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
+import { userLogic } from 'scenes/userLogic'
import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'
import { impersonationNoticeLogic } from '~/layout/navigation/ImpersonationNotice/impersonationNoticeLogic'
@@ -37,7 +40,7 @@ import { CLOUD_HOSTNAMES } from '~/lib/constants'
import { tagsModel } from '~/models/tagsModel'
import { defaultDataTableColumns } from '~/queries/nodes/DataTable/utils'
import { DataTableNode, NodeKind } from '~/queries/schema/schema-general'
-import type { Breadcrumb, CommentType, PersonType } from '~/types'
+import type { Breadcrumb, CommentType, PersonType, UserType } from '~/types'
import { ActivityScope, PropertyFilterType, PropertyOperator, Region } from '~/types'
import {
@@ -69,6 +72,35 @@ import { conversationsDraftModeLogic } from '../settings/conversationsDraftModeL
import { supportTicketsSceneLogic } from '../tickets/supportTicketsSceneLogic'
const MESSAGE_POLL_INTERVAL = 5000 // 5 seconds
+/** Must not exceed the server's replay window, or recovery could adopt a message from an older send. */
+const SEND_RECOVERY_WINDOW_SECONDS = 120
+
+/**
+ * How a failed send request should be treated. `null` means the send definitely did not happen:
+ * the server rejected the request before writing anything, so the draft is safe to keep and resend.
+ * Every other value means we don't know, and have to look at the thread before telling the operator.
+ */
+type UnconfirmedSendReason = 'network' | 'timeout' | 'in_progress' | 'server_error' | null
+
+function classifySendFailure(error: any): UnconfirmedSendReason {
+ const status = error?.status
+ if (typeof status !== 'number') {
+ // No response reached us, so the request may still have been processed.
+ return 'network'
+ }
+ if (status === 408) {
+ return 'timeout'
+ }
+ if (status === 409) {
+ // The dedupe guard is still creating an identical message from an earlier attempt.
+ return 'in_progress'
+ }
+ if (status >= 500) {
+ return 'server_error'
+ }
+ // Includes 429: throttling rejects before the request body is handled, so nothing was written.
+ return null
+}
function regionFromUrl(url?: string): Region | undefined {
if (url) {
@@ -195,6 +227,7 @@ export interface supportTicketSceneLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
availableTags: string[] // tagsModel
currentTeam: TeamPublicType | TeamType | null // teamLogic
+ user: UserType | null // userLogic
assignee: TicketAssignee
breadcrumbs: Breadcrumb[]
chatMessages: ChatMessage[]
@@ -243,6 +276,9 @@ export interface supportTicketSceneLogicActions {
value: true
} // supportTicketsSceneLogic
loadTags: () => any // tagsModel
+ appendMessage: (message: CommentType) => {
+ message: CommentType
+ }
cancelEditingMessage: () => {
value: true
}
@@ -511,6 +547,8 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([
['resolveAssignee'],
tagsModel,
['tags as availableTags'],
+ userLogic,
+ ['user'],
],
})),
actions({
@@ -524,6 +562,7 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([
loadMessages: true,
setMessages: (messages: CommentType[]) => ({ messages }),
setMessagesLoading: (loading: boolean) => ({ loading }),
+ appendMessage: (message: CommentType) => ({ message }),
loadOlderMessages: true,
setOlderMessages: (olderMessages: CommentType[]) => ({ olderMessages }),
@@ -761,6 +800,12 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([
{
setMessages: (_, { messages }) => messages,
setOlderMessages: (state, { olderMessages }) => [...olderMessages, ...state],
+ appendMessage: (state, { message }) => {
+ if (state.some((existing) => existing.id === message.id)) {
+ return state
+ }
+ return [...state, message].sort((a, b) => a.created_at.localeCompare(b.created_at))
+ },
},
],
messagesLoading: [
@@ -1185,11 +1230,19 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([
actions.setMessages([])
return
}
+ const revision = ++cache.messageRevision
+ const ticketId = values.ticket.id
try {
const response = await api.comments.list({
scope: 'conversations_ticket',
- item_id: values.ticket.id,
+ item_id: ticketId,
})
+ if (cache.messageRevision !== revision || values.ticket?.id !== ticketId) {
+ // setMessages replaces the list wholesale, so a poll that started before a
+ // newer load or a local write must not apply its older snapshot.
+ actions.setMessagesLoading(false)
+ return
+ }
// Reverse to show oldest first (bottom = newest)
actions.setMessages((response.results || []).reverse())
} catch {
@@ -1217,6 +1270,9 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([
.filter((msg) => new Date(msg.created_at) < new Date(oldestMessage.created_at))
.reverse()
+ // Prepending is a local write too: a poll that started earlier would replace the
+ // list with just the newest page and drop what we just loaded.
+ cache.messageRevision += 1
actions.setOlderMessages(olderMessages)
actions.setHasMoreMessages(olderMessages.length > 0)
} catch {
@@ -1229,45 +1285,55 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([
actions.setMessageSending(false)
return
}
- try {
- if (values.editingMessageId) {
- const editingId = values.editingMessageId
- await conversationsTicketsNotesPartialUpdate(
- String(getCurrentTeamId()),
- values.ticket.id,
- editingId,
- {
- message: content,
- rich_content: richContent,
- }
- )
- // Optimistic local update so the thread reflects the edit before comments.list returns.
- actions.setMessages(
- values.messages.map((message) =>
- message.id === editingId
- ? {
- ...message,
- content,
- rich_content: richContent,
- version: (message.version ?? 0) + 1,
- }
- : message
- )
- )
- lemonToast.success('Private note updated')
+ const ticketId = values.ticket.id
+
+ if (values.editingMessageId) {
+ const editingId = values.editingMessageId
+ try {
+ await conversationsTicketsNotesPartialUpdate(String(getCurrentTeamId()), ticketId, editingId, {
+ message: content,
+ rich_content: richContent,
+ })
+ } catch {
+ // A failed PATCH leaves the note as it was, so this is always a definite failure
+ // and never goes through the create-recovery path below.
+ lemonToast.error('Failed to update note')
actions.setMessageSending(false)
- // Restore the stashed composer draft; skip onSuccess (it clears the editor).
- actions.cancelEditingMessage()
- actions.loadMessages()
return
}
+ // Optimistic local update so the thread reflects the edit before comments.list returns.
+ cache.messageRevision += 1
+ actions.setMessages(
+ values.messages.map((message) =>
+ message.id === editingId
+ ? {
+ ...message,
+ content,
+ rich_content: richContent,
+ version: (message.version ?? 0) + 1,
+ }
+ : message
+ )
+ )
+ lemonToast.success('Private note updated')
+ actions.setMessageSending(false)
+ // Restore the stashed composer draft; skip onSuccess (it clears the editor).
+ actions.cancelEditingMessage()
+ actions.loadMessages()
+ return
+ }
+
+ const attemptStartedAt = dayjs()
+ let sent: CommentType | null = null
+ let unconfirmedReason: UnconfirmedSendReason = null
- await api.comments.create(
+ try {
+ sent = await api.comments.create(
{
content,
rich_content: richContent,
scope: 'conversations_ticket',
- item_id: values.ticket.id,
+ item_id: ticketId,
item_context: {
author_type: 'support',
is_private: isPrivate,
@@ -1275,26 +1341,65 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([
},
{}
)
- // "Added", not "sent": email delivery is async (outbox + Celery) and can still fail
- // after this API call succeeds; the per-message delivery status is the send signal.
- lemonToast.success(isPrivate ? 'Private note added' : 'Reply added')
- actions.setMessageSending(false)
- onSuccess?.()
- if (!isPrivate) {
- actions.incrementUnreadCustomerCount()
+ } catch (error: any) {
+ unconfirmedReason = classifySendFailure(error)
+ if (unconfirmedReason === null) {
+ lemonToast.error('Failed to send message')
+ actions.setMessageSending(false)
+ return
}
- if (statusAfterSend) {
- actions.setStatus(statusAfterSend)
- actions.updateTicket()
+ // The message may already be in the thread, so look before telling the operator
+ // anything. A silent fetch keeps this off the normal loading and error paths.
+ const authorId = values.user?.id
+ try {
+ const response = await api.comments.list({ scope: 'conversations_ticket', item_id: ticketId })
+ const earliestAcceptable = attemptStartedAt.subtract(SEND_RECOVERY_WINDOW_SECONDS, 'second')
+ sent =
+ (response.results || []).find(
+ (message) =>
+ message.content === content &&
+ objectsEqual(message.rich_content ?? null, richContent ?? null) &&
+ message.item_context?.is_private === isPrivate &&
+ message.item_context?.author_type === 'support' &&
+ // Without a known author we can't tell our own send from a
+ // colleague's identical one, so treat the outcome as unresolved.
+ authorId !== undefined &&
+ message.created_by?.id === authorId &&
+ !dayjs(message.created_at).isBefore(earliestAcceptable)
+ ) ?? null
+ } catch {
+ // Leave `sent` null: an unresolved outcome is the safe answer, and the operator
+ // does not need a second toast about a fetch they never asked for.
}
- setTimeout(() => {
- actions.loadMessages()
- }, 300)
- actions.loadTickets()
- } catch {
- lemonToast.error(values.editingMessageId ? 'Failed to update note' : 'Failed to send message')
+ }
+
+ if (!sent) {
+ posthog.capture('support reply send unconfirmed', {
+ reason: unconfirmedReason,
+ is_private: isPrivate,
+ })
+ lemonToast.error(
+ "We couldn't confirm that your message was added. Check the thread before sending it again."
+ )
actions.setMessageSending(false)
+ return
+ }
+
+ // "Added", not "sent": email delivery is async (outbox + Celery) and can still fail
+ // after this API call succeeds; the per-message delivery status is the send signal.
+ cache.messageRevision += 1
+ actions.appendMessage(sent)
+ lemonToast.success(isPrivate ? 'Private note added' : 'Reply added')
+ actions.setMessageSending(false)
+ onSuccess?.()
+ if (!isPrivate) {
+ actions.incrementUnreadCustomerCount()
+ }
+ if (statusAfterSend) {
+ actions.setStatus(statusAfterSend)
+ actions.updateTicket()
}
+ actions.loadTickets()
},
startEditingMessage: ({ message }) => {
// Only stash the composer draft on first enter; switching notes keeps the original stash.
@@ -1389,14 +1494,16 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([
}
},
})),
- afterMount(({ actions, props, values }) => {
+ afterMount(({ actions, props, values, cache }) => {
+ // Guards against a slow poll landing after a newer load or a local message write.
+ cache.messageRevision = 0
actions.setDraftModeEnabled(values.draftModeDefault)
if (props.id !== 'new') {
actions.loadTicket()
}
}),
- beforeUnmount(({ cache }) => {
- cache.disposables.disposeAll()
+ beforeUnmount(() => {
+ // The message poller is registered through cache.disposables, which the plugin tears down.
impersonationNoticeLogic.findMounted()?.actions.setTicketContext(null)
}),
beforeUnload(({ values, actions }) => ({
diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.ts
index 59ca66db7084..6de570194bb9 100644
--- a/products/platform_features/frontend/generated/api.schemas.ts
+++ b/products/platform_features/frontend/generated/api.schemas.ts
@@ -860,6 +860,13 @@ export interface PaginatedCommentListApi {
results: CommentApi[]
}
+export interface CommentErrorApi {
+ /** Human-readable explanation of what went wrong. */
+ detail: string
+ /** Stable machine-readable identifier for the failure. */
+ error_type?: string
+}
+
export interface PatchedCommentApi {
readonly id?: string
readonly created_by?: UserBasicApi | null
diff --git a/products/platform_features/frontend/generated/api.ts b/products/platform_features/frontend/generated/api.ts
index 5fff14b6fab9..722129dda740 100644
--- a/products/platform_features/frontend/generated/api.ts
+++ b/products/platform_features/frontend/generated/api.ts
@@ -904,6 +904,13 @@ export const getCommentsCreateUrl = (projectId: string) => {
return `/api/projects/${projectId}/comments/`
}
+/**
+ * Create a comment.
+ *
+ * Support messages are deduplicated: an identical message from the same author on the same
+ * ticket within a short window returns the original comment with a 200 instead of creating a
+ * second one, and a 409 while a concurrent request is still creating it.
+ */
export const commentsCreate = async (
projectId: string,
commentApi?: NonReadonly<CommentApi>,
diff --git a/products/platform_features/frontend/generated/api.zod.ts b/products/platform_features/frontend/generated/api.zod.ts
index 9b8ab0b6198d..2056b0997596 100644
--- a/products/platform_features/frontend/generated/api.zod.ts
+++ b/products/platform_features/frontend/generated/api.zod.ts
@@ -349,6 +349,13 @@ export const ChangeRequestsRejectCreateBody = /* @__PURE__ */ zod.object({
),
})
+/**
+ * Create a comment.
+ *
+ * Support messages are deduplicated: an identical message from the same author on the same
+ * ticket within a short window returns the original comment with a 200 instead of creating a
+ * second one, and a 409 while a concurrent request is still creating it.
+ */
export const commentsCreateBodyScopeMax = 79
export const commentsCreateBodyIsTaskDefault = false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 97a09316f400..24ce68900799 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -15592,6 +15592,13 @@ export namespace Schemas {
source_comment?: string | null;
}
+ export interface CommentError {
+ /** Human-readable explanation of what went wrong. */
+ detail: string;
+ /** Stable machine-readable identifier for the failure. */
+ error_type?: string;
+ }
+
export interface CommentSlackThread {
readonly id: string;
/** Resource type of the mirrored discussion (e.g. Insight). */
diff --git a/services/mcp/src/generated/conversations/api.ts b/services/mcp/src/generated/conversations/api.ts
index dd74e5764e79..2fe63471d04c 100644
--- a/services/mcp/src/generated/conversations/api.ts
+++ b/services/mcp/src/generated/conversations/api.ts
@@ -255,6 +255,10 @@ export const ConversationsTicketsNotesDestroyParams = /* @__PURE__ */ zod.object
* With is_private=false, the reply is delivered to the customer via the
* ticket's channel (email, Slack, Teams, GitHub). With is_private=true,
* the message is stored as an internal note only visible to team members.
+ *
+ * Retrying an identical message from the same author within a short window returns the
+ * original message with a 200 rather than posting it twice, and a 409 while a concurrent
+ * request is still creating it.
*/
export const ConversationsTicketsReplyCreateParams = /* @__PURE__ */ zod.object({
id: zod.string().describe("The ticket's UUID or its numeric ticket number."),