: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
fix(signals): link pull requests from support tickets (#123232)
Paul D'Ambra61ba67bd075b
diff --git a/docs/internal/conversations-reliability.md b/docs/internal/conversations-reliability.mdindex 8bb2da092d6d..9f6e92260441 100644--- a/docs/internal/conversations-reliability.md+++ b/docs/internal/conversations-reliability.md@@ -115,6 +115,7 @@ That is provider acceptance, not customer delivery.Timeouts after a possible accept retry with the same `client_msg_id`.Honor `Retry-After` on 429s, cap at one hour, and treat 5xx plus Slack timeout codes as transient.Permanent Slack application errors (revoked token, missing channel, invalid blocks) fail the part.+Automated PR replies check the approved channel list and current channel type before posting. A failed channel lookup retries; a known external channel fails the part.Keep `post_reply_to_slack` registered for in-flight Celery messages.New work uses `process_slack_delivery_part`.diff --git a/posthog/api/team/conversations_settings.py b/posthog/api/team/conversations_settings.pyindex 7be00087f255..ff0cf6019f8b 100644--- a/posthog/api/team/conversations_settings.py+++ b/posthog/api/team/conversations_settings.py@@ -13,12 +13,23 @@ from posthog.api.utils import validate_authorized_url_wildcardsfrom posthog.event_usage import report_user_actionfrom posthog.models import Team, User+from products.conversations.backend.models.constants import AUTOMATED_UPDATE_SLACK_CHANNEL_IDS+@extend_schema_field(OpenApiTypes.OBJECT)class ConversationsSettingsField(serializers.JSONField):pass+def validate_automated_update_slack_channel_ids(channel_ids: Any) -> list[str]:+ field = serializers.ListField(child=serializers.RegexField(regex=r"\A[CG][A-Z0-9]{6,}\Z"))+ validated = field.run_validation([] if channel_ids is None else channel_ids)+ unique_channel_ids = list(dict.fromkeys(validated))+ if len(unique_channel_ids) > 20:+ raise serializers.ValidationError("Use 20 channels or fewer.")+ return unique_channel_ids++MANAGED_CONVERSATIONS_SETTINGS = (# Strip widget_public_token from user input - it's auto-generated only"widget_public_token",@@ -216,6 +227,13 @@ def validate_conversations_settings(# null so a clearing PATCH still overwrites the stored list (see# merge_conversations_settings, which only replaces keys present here).value.pop("slack_channel_ids", None)+ if AUTOMATED_UPDATE_SLACK_CHANNEL_IDS in value:+ try:+ value[AUTOMATED_UPDATE_SLACK_CHANNEL_IDS] = validate_automated_update_slack_channel_ids(+ value[AUTOMATED_UPDATE_SLACK_CHANNEL_IDS]+ )+ except serializers.ValidationError as error:+ raise serializers.ValidationError({AUTOMATED_UPDATE_SLACK_CHANNEL_IDS: error.detail}) from erroricon_url = value.get("slack_bot_icon_url")if icon_url is not None:if not isinstance(icon_url, str):diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.pyindex 92e9808a6e1c..ac7f301ac20b 100644--- a/posthog/api/test/test_team.py+++ b/posthog/api/test/test_team.py@@ -2343,6 +2343,31 @@ def team_api_test_factory():assert settings["widget_greeting_text"] == "Hello!"assert settings["widget_color"] == "#ff0000"+ @parameterized.expand(+ [+ ("deduplicates_ids", ["C0123ABCD", "C0123ABCD"], status.HTTP_200_OK, ["C0123ABCD"]),+ ("clears_with_null", None, status.HTTP_200_OK, []),+ ("rejects_names", ["#support"], status.HTTP_400_BAD_REQUEST, None),+ ("rejects_direct_messages", ["D0123ABCD"], status.HTTP_400_BAD_REQUEST, None),+ ("rejects_non_list", "C0123ABCD", status.HTTP_400_BAD_REQUEST, None),+ ("rejects_non_string", [123], status.HTTP_400_BAD_REQUEST, None),+ ("caps_channels", [f"C{i:08d}" for i in range(21)], status.HTTP_400_BAD_REQUEST, None),+ ]+ )+ def test_automated_update_channel_allowlist_validation(+ self, _name, channel_ids, expected_status, expected_channels+ ):+ response = self.client.patch(+ "/api/environments/@current/",+ {"conversations_settings": {"automated_update_slack_channel_ids": channel_ids}},+ )++ assert response.status_code == expected_status+ if expected_channels is not None:+ assert (+ response.json()["conversations_settings"]["automated_update_slack_channel_ids"] == expected_channels+ )+@parameterized.expand([(["legacy", "list"],), ("legacy string",), (1,)])def test_conversations_settings_merges_with_legacy_non_object_existing(self, legacy_value):# Rows written before validation required an object/null can hold a straydiff --git a/products/conversations/backend/ai/human_outcome.py b/products/conversations/backend/ai/human_outcome.pyindex 062b5b36b529..7591801f8ac9 100644--- a/products/conversations/backend/ai/human_outcome.py+++ b/products/conversations/backend/ai/human_outcome.py@@ -72,6 +72,7 @@ def record_human_outcome(*, team_id: int, ticket_id: str, draft_message_id: str,latest_ai_draft_id = (_ticket_comments(team_id=team_id, ticket_id=ticket_id).filter(item_context__author_type="AI", item_context__is_private=True, deleted=False)+ .filter(item_context__automated_update_key__isnull=True).order_by("-created_at", "-id").values_list("id", flat=True).first()@@ -114,6 +115,7 @@ def maybe_record_human_outcome(*, team_id: int, ticket_id: str, comment_id: str,# to the customer, so a later human reply is a follow-up, not adoption of a draft.ai_note = (comments.filter(item_context__author_type="AI", item_context__is_private=True, deleted=False)+ .filter(item_context__automated_update_key__isnull=True).filter(before_this).order_by("-created_at", "-id").first()diff --git a/products/conversations/backend/api/tests/test_ai_triage_api.py b/products/conversations/backend/api/tests/test_ai_triage_api.pyindex edf529138bed..4f8d9bd9c2d8 100644--- a/products/conversations/backend/api/tests/test_ai_triage_api.py+++ b/products/conversations/backend/api/tests/test_ai_triage_api.py@@ -89,6 +89,21 @@ class TestAiHumanOutcomeAPI(APIBaseTest):self.ticket.refresh_from_db()assert "human_outcome" not in self.ticket.ai_triage+ def test_automated_update_does_not_replace_the_latest_ai_draft(self) -> None:+ Comment.objects.create(+ team=self.team,+ scope="conversations_ticket",+ item_id=str(self.ticket.id),+ content="Pull request update",+ item_context={"author_type": "AI", "is_private": True, "automated_update_key": "pr-123"},+ )++ response = self.client.post(self.url, self._payload("used"), format="json")++ assert response.status_code == status.HTTP_202_ACCEPTED+ self.ticket.refresh_from_db()+ assert self.ticket.ai_triage["human_outcome"] == "used"+class TestAiTriageSourcesAPI(APIBaseTest):def setUp(self) -> None:diff --git a/products/conversations/backend/api/tests/test_signals.py b/products/conversations/backend/api/tests/test_signals.pyindex 7a00638d6ad1..a36a1f9c4833 100644--- a/products/conversations/backend/api/tests/test_signals.py+++ b/products/conversations/backend/api/tests/test_signals.py@@ -150,6 +150,15 @@ class TestTicketMessageSignals(BaseTest):self.ticket.refresh_from_db()assert self.ticket.ai_triage["human_outcome"] == "used"+ def test_automated_update_does_not_replace_draft_for_human_outcome(self, mock_on_commit):+ draft = "Add the snippet to the head of every page."+ self._create_ai_message(draft)+ self._create_ai_message("Pull request update", item_context={"automated_update_key": "pr-123"})+ self._create_team_message(draft)++ self.ticket.refresh_from_db()+ assert self.ticket.ai_triage["human_outcome"] == "used"+def test_used_draft_then_edited_send_upgrades_human_outcome(self, mock_on_commit):draft = "Add the snippet to the head of every page, then reload to send a pageview."ai_draft = self._create_ai_message(draft)diff --git a/products/conversations/backend/api/tests/test_tickets.py b/products/conversations/backend/api/tests/test_tickets.pyindex 11d1188ae08a..e1ec39b8c269 100644--- a/products/conversations/backend/api/tests/test_tickets.py+++ b/products/conversations/backend/api/tests/test_tickets.py@@ -3480,6 +3480,25 @@ class TestAiFeedbackAPI(APIBaseTest):)assert response.status_code == status.HTTP_400_BAD_REQUEST+ @patch("products.conversations.backend.api.tickets.posthoganalytics.capture")+ def test_ai_feedback_rejects_automated_update(self, mock_capture, mock_on_commit):+ update = Comment.objects.create(+ team=self.team,+ scope="conversations_ticket",+ item_id=str(self.ticket.id),+ content="Pull request update",+ item_context={"author_type": "AI", "is_private": True, "automated_update_key": "pr-123"},+ )++ response = self.client.post(+ self.url,+ {"message_id": str(update.id), "rating": "good"},+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ mock_capture.assert_not_called()+class TestTicketAccessControl(APIBaseTest):"""Resource- and object-level access control for support tickets (the `ticket` RBAC resource)."""diff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.pyindex 6cfd36907aa4..84b7b9316da5 100644--- a/products/conversations/backend/api/tickets.py+++ b/products/conversations/backend/api/tickets.py@@ -1933,6 +1933,22 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessControserializer.is_valid(raise_exception=True)data = serializer.validated_data+ try:+ message_id = uuid.UUID(data["message_id"])+ except ValueError:+ message_id = None+ if (+ message_id+ and Comment.objects.filter(+ id=message_id,+ team_id=self.team_id,+ scope="conversations_ticket",+ item_id=str(ticket.id),+ item_context__automated_update_key__isnull=False,+ ).exists()+ ):+ raise ValidationError({"message_id": "Automated updates cannot receive AI feedback."})+ai_triage = ticket.ai_triage or {}trace_id = ai_triage.get("ai_trace_id")distinct_id = f"reviewer:{request.user.distinct_id}"diff --git a/products/conversations/backend/facade/api.py b/products/conversations/backend/facade/api.pyindex ed31ad9a2920..b63e1b47e2e3 100644--- a/products/conversations/backend/facade/api.py+++ b/products/conversations/backend/facade/api.py@@ -59,10 +59,11 @@ from products.conversations.backend.models import (Status,Ticket,)-from products.conversations.backend.models.constants import WORKFLOW_AUTHOR_TYPE+from products.conversations.backend.models.constants import WORKFLOW_AUTHOR_TYPE, Channelfrom products.conversations.backend.services.messages import public_human_ticket_replies-from products.conversations.backend.slack import get_slack_client+from products.conversations.backend.slack import _is_internal_channel, get_slack_clientfrom products.conversations.backend.support_slack import (+ automated_update_channel_allowed,get_support_slack_bot_token,supporthog_lacks_custom_identity_scope,)@@ -441,6 +442,59 @@ def post_ticket_internal_note(team_id: int, ticket_id: str, content: str, *, dedreturn str(comment.id)+def post_ticket_automated_update(+ team_id: int, ticket_id: str, *, public_content: str, private_content: str, dedupe_key: str+) -> str | None:+ source_ticket = Ticket.objects.filter(team_id=team_id, id=ticket_id).select_related("team").first()+ if source_ticket is None:+ return None+ checked_channel = source_ticket.slack_channel_id+ send_to_slack = False+ if (+ source_ticket.channel_source == Channel.SLACK+ and checked_channel+ and source_ticket.slack_thread_ts+ and automated_update_channel_allowed(source_ticket.team, checked_channel)+ ):+ try:+ send_to_slack = _is_internal_channel(get_slack_client(source_ticket.team), checked_channel)+ except Exception:+ logger.exception("Failed to check support Slack channel before automated update", ticket_id=ticket_id)++ with transaction.atomic():+ ticket = Ticket.objects.select_for_update().filter(team_id=team_id, id=ticket_id).first()+ if ticket is None:+ return None+ if Comment.objects.filter(+ team_id=team_id,+ scope="conversations_ticket",+ item_id=ticket_id,+ item_context__automated_update_key=dedupe_key,+ deleted=False,+ ).exists():+ return None+ send_to_slack = bool(+ send_to_slack+ and ticket.channel_source == Channel.SLACK+ and ticket.slack_channel_id == checked_channel+ and ticket.slack_thread_ts == source_ticket.slack_thread_ts+ )+ comment = Comment.objects.create(+ team_id=team_id,+ scope="conversations_ticket",+ item_id=ticket_id,+ content=public_content if send_to_slack else private_content,+ item_context={+ "author_type": "AI",+ "is_private": not send_to_slack,+ "automated_update_key": dedupe_key,+ "internal_channel_only": send_to_slack,+ **({"internal_note_key": dedupe_key} if not send_to_slack else {}),+ },+ )+ return str(comment.id)++def trigger_immediate_channel_summary(*,team_id: int,diff --git a/products/conversations/backend/models/constants.py b/products/conversations/backend/models/constants.pyindex 63fb9e56876c..76ce60614837 100644--- a/products/conversations/backend/models/constants.py+++ b/products/conversations/backend/models/constants.py@@ -1,5 +1,7 @@from django.db import models+AUTOMATED_UPDATE_SLACK_CHANNEL_IDS = "automated_update_slack_channel_ids"+class Channel(models.TextChoices):WIDGET = "widget", "Widget"diff --git a/products/conversations/backend/services/delivery.py b/products/conversations/backend/services/delivery.pyindex dd23a3f7d908..e9af5a3e795d 100644--- a/products/conversations/backend/services/delivery.py+++ b/products/conversations/backend/services/delivery.py@@ -220,7 +220,7 @@ def _body_snapshot(include_images=False,organization_id=team.organization_id,)- return {+ snapshot = {"text": slack_text,"blocks": slack_blocks,"author_name": author.name,@@ -228,6 +228,9 @@ def _body_snapshot("media_team_id": media_team_id,"images": _image_refs(comment.rich_content if isinstance(comment.rich_content, dict) else None),}+ if isinstance(comment.item_context, dict) and comment.item_context.get("internal_channel_only") is True:+ snapshot["internal_channel_only"] = True+ return snapshotdef _enqueue_failed_slack_body(diff --git a/products/conversations/backend/signals.py b/products/conversations/backend/signals.pyindex fb1519ae0201..1da8304dcf17 100644--- a/products/conversations/backend/signals.py+++ b/products/conversations/backend/signals.py@@ -143,6 +143,14 @@ def update_ticket_on_message(sender, instance: Comment, created: bool, **kwargs)if not created:return+ if (+ instance.created_by_id is None+ and isinstance(instance.item_context, dict)+ and instance.item_context.get("author_type") == "AI"+ and instance.item_context.get("automated_update_key")+ ):+ return+# Capture values for closure (avoid referencing instance in deferred callback)team_id = instance.team_iditem_id = instance.item_iddiff --git a/products/conversations/backend/slack.py b/products/conversations/backend/slack.pyindex 02e233beaccd..69636db650ff 100644--- a/products/conversations/backend/slack.py+++ b/products/conversations/backend/slack.py@@ -1665,7 +1665,7 @@ def ticket_unfurl(ticket: "Ticket", team: Team) -> dict:}-def _is_internal_channel(client: WebClient, channel: str) -> bool:+def _is_internal_channel(client: WebClient, channel: str, *, raise_on_error: bool = False) -> bool:"""Whether `channel` is an ordinary channel of this workspace alone.Fails closed, twice over: a channel we cannot read is one we cannot prove is internal, and@@ -1684,6 +1684,8 @@ def _is_internal_channel(client: WebClient, channel: str) -> bool:response = client.conversations_info(channel=channel)except Exception:logger.warning("slack_support_unfurl_channel_lookup_failed", slack_channel_id=channel)+ if raise_on_error:+ raisereturn Falseinfo = response.get("channel") or {}if any(info.get(flag) for flag in _NON_INTERNAL_CHANNEL_FLAGS):diff --git a/products/conversations/backend/support_slack.py b/products/conversations/backend/support_slack.pyindex f3ede863a48e..19fd8ba4d568 100644--- a/products/conversations/backend/support_slack.py+++ b/products/conversations/backend/support_slack.py@@ -11,6 +11,7 @@ from posthog.models.team.extensions import get_or_create_team_extensionfrom posthog.models.utils import mask_key_valuefrom products.conversations.backend.models import TeamConversationsSlackConfig+from products.conversations.backend.models.constants import AUTOMATED_UPDATE_SLACK_CHANNEL_IDSif TYPE_CHECKING:from posthog.models.team.team import Team@@ -28,6 +29,13 @@ SUPPORT_SLACK_FILE_SCOPES = frozenset({SUPPORT_SLACK_FILE_READ_SCOPE, SUPPORT_SLSUPPORT_SLACK_CUSTOM_IDENTITY_SCOPE = "chat:write.customize"+def automated_update_channel_allowed(team: "Team", channel_id: str) -> bool:+ project_team = team.parent_team or team+ settings = project_team.conversations_settings+ channel_ids = settings.get(AUTOMATED_UPDATE_SLACK_CHANNEL_IDS) if isinstance(settings, dict) else None+ return isinstance(channel_ids, list) and channel_id in channel_ids++# Every SupportHog delivery is verified with the signing secret, so the read is cached and not made# once per request. A rotation reaches each process within five minutes.@cache_for(timedelta(minutes=5))diff --git a/products/conversations/backend/tasks/slack.py b/products/conversations/backend/tasks/slack.pyindex 84ffe3590cfe..f47f0f9ffa01 100644--- a/products/conversations/backend/tasks/slack.py+++ b/products/conversations/backend/tasks/slack.py@@ -83,6 +83,7 @@ from products.conversations.backend.slack import (NudgeClassifierVerdict,NudgeFunnelVerdict,SlackConfirmationNeedsRetry,+ _is_internal_channel,capture_nudge_event,capture_support_event,create_ticket_from_confirmation,@@ -102,7 +103,11 @@ from products.conversations.backend.slack import (ticket_deep_link,)-from ..support_slack import SUPPORT_SLACK_ALLOWED_HOST_SUFFIXES, supporthog_missing_file_scopes+from ..support_slack import (+ SUPPORT_SLACK_ALLOWED_HOST_SUFFIXES,+ automated_update_channel_allowed,+ supporthog_missing_file_scopes,+)logger = structlog.get_logger(__name__)SUPPORTHOG_EVENT_IDEMPOTENCY_TTL_SECONDS = 6 * 60@@ -846,6 +851,9 @@ def _post_slack_body("text": slack_text,"username": sender.username,}+ if payload.get("internal_channel_only") is True:+ message_kwargs["unfurl_links"] = False+ message_kwargs["unfurl_media"] = Falseif client_msg_id:message_kwargs["client_msg_id"] = client_msg_idif sender.icon_url:@@ -928,6 +936,34 @@ def _load_slack_delivery_runtime(claim: DeliveryClaim) -> SlackDeliveryRuntime |def _deliver_slack_body(claim: DeliveryClaim, runtime: SlackDeliveryRuntime) -> None:+ channel = str(runtime.route.get("channel") or "")+ if runtime.payload.get("internal_channel_only") is True and not automated_update_channel_allowed(+ runtime.team, channel+ ):+ _fail_claimed_delivery_part(+ claim,+ error_code="channel_not_allowlisted",+ error="The Slack channel is not approved for automated updates",+ )+ return+ if runtime.payload.get("internal_channel_only") is True:+ try:+ is_internal = _is_internal_channel(runtime.client, channel, raise_on_error=True)+ except Exception as exc:+ _retry_delivery_claim(+ claim,+ error_code="channel_lookup_failed",+ error="Could not check whether the Slack channel is internal",+ retry_after_seconds=_retry_after_seconds(exc),+ )+ return+ if not is_internal:+ _fail_claimed_delivery_part(+ claim,+ error_code="channel_not_internal",+ error="The Slack channel is not confirmed as internal",+ )+ returnts = _post_slack_body(client=runtime.client,team=runtime.team,diff --git a/products/conversations/backend/temporal/coordinator.py b/products/conversations/backend/temporal/coordinator.pyindex 7e2cf93d2f9a..bbb8442b3285 100644--- a/products/conversations/backend/temporal/coordinator.py+++ b/products/conversations/backend/temporal/coordinator.py@@ -208,6 +208,7 @@ def _collect_eligible(lookback_minutes: int = TICKET_LOOKBACK_MINUTES) -> list[Eteam_id=team_id,scope="conversations_ticket",item_id__in=ticket_ids,+ item_context__automated_update_key__isnull=True,).values_list("item_id", "item_context__author_type", "created_at"):if author_type == "customer":prev = latest_customer_msg.get(item_id)diff --git a/products/conversations/backend/temporal/tests/test_coordinator.py b/products/conversations/backend/temporal/tests/test_coordinator.pyindex 37eb3518c48e..256e8cde9038 100644--- a/products/conversations/backend/temporal/tests/test_coordinator.py+++ b/products/conversations/backend/temporal/tests/test_coordinator.py@@ -406,7 +406,7 @@ class TestCollectEligibleAwaitingClarification:ticket.refresh_from_db()return team, ticket- def _comment(self, team, ticket, *, author_type: str, minutes_ago: int):+ def _comment(self, team, ticket, *, author_type: str, minutes_ago: int, automated_update_key: str | None = None):from posthog.models.comment import Commentcreated = timezone.now() - timedelta(minutes=minutes_ago)@@ -415,7 +415,12 @@ class TestCollectEligibleAwaitingClarification:scope="conversations_ticket",item_id=str(ticket.id),content=author_type,- item_context={"author_type": author_type, "is_private": False, "persist_as": "clarification"},+ item_context={+ "author_type": author_type,+ "is_private": False,+ "persist_as": "clarification",+ **({"automated_update_key": automated_update_key} if automated_update_key else {}),+ },)Comment.objects.filter(id=comment.id).update(created_at=created)from products.conversations.backend.models.ticket import Ticket as TicketModel@@ -424,6 +429,23 @@ class TestCollectEligibleAwaitingClarification:ticket.refresh_from_db()return comment+ @pytest.mark.django_db+ @patch(f"{COORD_MODULE}._is_master_flag_enabled", return_value=True)+ def test_automated_pr_update_does_not_answer_a_customer_followup(self, mock_master_flag):+ team, ticket = self._team_and_ticket()+ self._comment(team, ticket, author_type="customer", minutes_ago=10)+ self._comment(team, ticket, author_type="AI", minutes_ago=5)+ self._comment(team, ticket, author_type="customer", minutes_ago=3)+ self._comment(+ team,+ ticket,+ author_type="AI",+ minutes_ago=1,+ automated_update_key="signals_pr:report:pr",+ )++ assert [item.ticket_id for item in _collect_eligible()] == [str(ticket.id)]+@parameterized.expand([(diff --git a/products/conversations/backend/tests/test_slack_delivery.py b/products/conversations/backend/tests/test_slack_delivery.pyindex 854148d17133..fb3b3ee364d8 100644--- a/products/conversations/backend/tests/test_slack_delivery.py+++ b/products/conversations/backend/tests/test_slack_delivery.py@@ -99,6 +99,108 @@ class TestSlackDelivery(BaseTest):def _part(self) -> ConversationDeliveryPart:return ConversationDeliveryPart.objects.unscoped().select_related("delivery").get()+ @parameterized.expand(+ [+ ("shared", {"is_channel": True, "is_ext_shared": True}, True, False, "channel_not_internal"),+ ("internal", {"is_channel": True}, True, True, ""),+ ("approval_removed", {"is_channel": True}, False, False, "channel_not_allowlisted"),+ ]+ )+ @patch("products.conversations.backend.tasks.slack.get_slack_client")+ def test_automated_update_checks_channel_before_delivery(+ self,+ _name: str,+ channel_info: dict,+ approved: bool,+ expected_sent: bool,+ expected_error: str,+ mock_get_client: MagicMock,+ ) -> None:+ self.team.conversations_settings = {+ **self.team.conversations_settings,+ "automated_update_slack_channel_ids": ["C123"] if approved else [],+ }+ self.team.save(update_fields=["conversations_settings"])+ Comment.objects.create(+ team=self.team,+ scope="conversations_ticket",+ item_id=str(self.ticket.id),+ content="[PostHog bot] Pull request opened",+ item_context={+ "author_type": "AI",+ "is_private": False,+ "automated_update_key": "signals_pr:report:pr",+ "internal_channel_only": True,+ },+ )+ part = self._part()+ payload = part.payload+ assert isinstance(payload, dict)+ assert payload["internal_channel_only"] is True+ client = MagicMock()+ client.conversations_info.return_value = {"channel": channel_info}+ client.chat_postMessage.return_value = {"ts": "1700.1"}+ mock_get_client.return_value = client++ process_slack_delivery_part(str(part.id))++ part.refresh_from_db()+ if expected_sent:+ assert part.status == ConversationDeliveryPart.Status.ACCEPTED+ kwargs = client.chat_postMessage.call_args.kwargs+ assert kwargs["unfurl_links"] is False+ assert kwargs["unfurl_media"] is False+ else:+ assert part.status == ConversationDeliveryPart.Status.FAILED+ assert part.last_error_code == expected_error+ client.chat_postMessage.assert_not_called()++ @parameterized.expand(+ [+ ("timeout", TimeoutError("Slack unavailable"), None),+ ("rate_limited", _slack_api_error("ratelimited", retry_after="17", status_code=429), 17),+ ]+ )+ @patch("products.conversations.backend.tasks.slack.get_slack_client")+ def test_automated_update_retries_failed_channel_lookup(+ self, _name: str, error: Exception, retry_after: int | None, mock_get_client: MagicMock+ ) -> None:+ self.team.conversations_settings = {+ **self.team.conversations_settings,+ "automated_update_slack_channel_ids": ["C123"],+ }+ self.team.save(update_fields=["conversations_settings"])+ Comment.objects.create(+ team=self.team,+ scope="conversations_ticket",+ item_id=str(self.ticket.id),+ content="[PostHog bot] Pull request opened",+ item_context={"author_type": "AI", "is_private": False, "internal_channel_only": True},+ )+ part = self._part()+ client = MagicMock()+ client.conversations_info.side_effect = [error, {"channel": {"is_channel": True}}]+ client.chat_postMessage.return_value = {"ts": "1700.1"}+ mock_get_client.return_value = client++ with time_machine.travel("2026-09-21 12:00:00", tick=False):+ ConversationDeliveryPart.objects.unscoped().filter(id=part.id).update(due_at=timezone.now())+ process_slack_delivery_part(str(part.id))+ part.refresh_from_db()+ assert part.status == ConversationDeliveryPart.Status.PENDING+ assert part.last_error_code == "channel_lookup_failed"+ assert part.due_at > timezone.now()+ if retry_after is not None:+ assert part.due_at == timezone.now() + timedelta(seconds=retry_after)+ client.chat_postMessage.assert_not_called()++ ConversationDeliveryPart.objects.unscoped().filter(id=part.id).update(due_at=timezone.now())+ process_slack_delivery_part(str(part.id))++ part.refresh_from_db()+ assert part.status == ConversationDeliveryPart.Status.ACCEPTED+ client.chat_postMessage.assert_called_once()+def test_enqueue_failure_rolls_back_the_comment(self) -> None:with (self.assertRaises(RuntimeError),diff --git a/products/conversations/frontend/components/Chat/aiDraftAction.test.ts b/products/conversations/frontend/components/Chat/aiDraftAction.test.tsindex b1bb5faf15bd..fcdc76abfb63 100644--- a/products/conversations/frontend/components/Chat/aiDraftAction.test.ts+++ b/products/conversations/frontend/components/Chat/aiDraftAction.test.ts@@ -21,6 +21,7 @@ describe('aiDraftAction', () => {['public auto-sent reply', { isPrivate: false, persistAs: 'reply' as const }, null],['public clarifying question', { isPrivate: false, persistAs: 'clarification' as const }, null],['human private note', { authorType: 'human' as const }, null],+ ['automated private note', { automatedUpdate: true }, null],])('%s', (_name, overrides, expected) => {expect(aiDraftAction({ ...base, ...overrides })).toBe(expected)})diff --git a/products/conversations/frontend/components/Chat/aiDraftAction.ts b/products/conversations/frontend/components/Chat/aiDraftAction.tsindex 62581edc392f..b96e43985dc2 100644--- a/products/conversations/frontend/components/Chat/aiDraftAction.ts+++ b/products/conversations/frontend/components/Chat/aiDraftAction.ts@@ -18,9 +18,9 @@ export function firstClarifyingQuestion(questions: unknown): string | null {}export function aiDraftAction(- message: Pick<ChatMessage, 'authorType' | 'isPrivate' | 'persistAs' | 'clarifyingQuestions'>+ message: Pick<ChatMessage, 'authorType' | 'isPrivate' | 'persistAs' | 'clarifyingQuestions' | 'automatedUpdate'>): AiDraftActionKind | null {- if (message.authorType !== 'AI' || !message.isPrivate) {+ if (message.authorType !== 'AI' || !message.isPrivate || message.automatedUpdate) {return null}if (message.persistAs === 'clarification') {diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.tsindex bf8d8e5d32d3..360f7844f140 100644--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts@@ -164,6 +164,19 @@ describe('supportTicketSceneLogic ai reply feedback', () => {})})+ it('keeps feedback on the AI reply after an automated update', () => {+ logic.actions.setMessages([+ makeAiComment('msg-ai-1', false),+ {+ ...makeAiComment('pr-update', false),+ created_at: '2026-01-01T00:01:00Z',+ item_context: { author_type: 'AI', is_private: false, automated_update_key: 'pr-123' },+ } as unknown as CommentType,+ ])++ expect(logic.values.latestAiMessage?.id).toBe('msg-ai-1')+ })+it('calls backend relay on good feedback', async () => {await expectLogic(logic, () => {logic.actions.submitAiReplyFeedback('msg-ai-1', 'good')@@ -348,6 +361,19 @@ describe('supportTicketSceneLogic chatMessages mapping', () => {expect(logic.values.latestAiDraftId).toBe('new-draft')})+ it('shows automated private notes without treating them as AI drafts', () => {+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.PRODUCT_SUPPORT_AI_NOTES]: false })+ logic.actions.setMessages([+ {+ ...makeAiComment('pr-update'),+ item_context: { author_type: 'AI', is_private: true, automated_update_key: 'pr-123' },+ } as unknown as CommentType,+ ])++ expect(logic.values.chatMessages).toEqual([expect.objectContaining({ id: 'pr-update', automatedUpdate: true })])+ expect(logic.values.latestAiDraftId).toBeNull()+ })+it('selects widget delivery statuses for public team messages', () => {logic.actions.setTicket({ ...makeTicket(), unread_customer_count: 1 })logic.actions.setMessages([diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.tsindex c39b85fa48b6..149a4106f1ff 100644--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts@@ -281,7 +281,11 @@ export function getEmailReplyBlockedReason(* make the thread misrepresent the conversation.*/export function isAiPrivateNote(message: Pick<CommentType, 'item_context'>): boolean {- return message.item_context?.author_type === 'AI' && message.item_context?.is_private === true+ return (+ message.item_context?.author_type === 'AI' &&+ message.item_context?.is_private === true &&+ !message.item_context?.automated_update_key+ )}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -1226,6 +1230,7 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([createdBy: message.created_by,createdAt: message.created_at,isPrivate: message.item_context?.is_private || false,+ automatedUpdate: !!message.item_context?.automated_update_key,version: message.version,emailDeliveryStatus: message.item_context?.email_delivery_status,fromZendesk: message.item_context?.from_zendesk === true,@@ -1301,7 +1306,7 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([(s) => [s.chatMessages],(chatMessages: ChatMessage[]): ChatMessage | null => {for (let i = chatMessages.length - 1; i >= 0; i--) {- if (chatMessages[i].authorType === 'AI') {+ if (chatMessages[i].authorType === 'AI' && !chatMessages[i].automatedUpdate) {return chatMessages[i]}}diff --git a/products/conversations/frontend/types.ts b/products/conversations/frontend/types.tsindex 9c0eb580fdc2..30cf45427af8 100644--- a/products/conversations/frontend/types.ts+++ b/products/conversations/frontend/types.ts@@ -234,6 +234,7 @@ export interface ChatMessage {createdBy?: MessageAuthor | nullcreatedAt: stringisPrivate?: boolean+ automatedUpdate?: boolean/** Edit count from the comment row. 0 means never edited. */version?: numberemailDeliveryStatus?: EmailDeliveryStatusdiff --git a/products/signals/backend/emission/fetchers/conversations.py b/products/signals/backend/emission/fetchers/conversations.pyindex 9ec58ca1436e..1f2c75a0e4ea 100644--- a/products/signals/backend/emission/fetchers/conversations.py+++ b/products/signals/backend/emission/fetchers/conversations.py@@ -81,6 +81,11 @@ def conversations_ticket_fetcher()# Exclude private notes and AI drafts (mirrors widget.py / suggest.py semantics).filter(~Q(item_context__is_private=True) | Q(item_context__is_private__isnull=True))+ .exclude(+ created_by__isnull=True,+ item_context__author_type="AI",+ item_context__automated_update_key__isnull=False,+ ).order_by("created_at").values_list("item_id", "content", "item_context", "rich_content"))diff --git a/products/signals/backend/emission/tests/test_conversations_fetcher.py b/products/signals/backend/emission/tests/test_conversations_fetcher.pyindex 386c234ef5df..e7b02e0fcba7 100644--- a/products/signals/backend/emission/tests/test_conversations_fetcher.py+++ b/products/signals/backend/emission/tests/test_conversations_fetcher.py@@ -3,6 +3,7 @@ from datetime import timedeltaimport pytestfrom posthog.test.base import BaseTest+from unittest.mock import patchfrom django.utils import timezone@@ -113,6 +114,27 @@ class TestConversationsTicketFetcherEligibility(BaseTest):assert conversations_ticket_fetcher(self.team, CONVERSATIONS_TICKETS_CONFIG, {}) == []+ def test_automated_pr_update_does_not_resnapshot_ticket(self):+ ticket = _make_ticket(self.team)+ _backdate_ticket(ticket, hours=48)+ assert len(conversations_ticket_fetcher(self.team, CONVERSATIONS_TICKETS_CONFIG, {})) == 1+ _backdate_emission(self.team, ticket, hours=30)++ with patch("products.conversations.backend.signals.capture_message_sent") as capture_reply:+ with self.captureOnCommitCallbacks(execute=True):+ Comment.objects.create(+ team=self.team,+ scope="conversations_ticket",+ item_id=str(ticket.id),+ content="A pull request is open",+ item_context={"author_type": "AI", "is_private": False, "automated_update_key": "pr-123"},+ )+ capture_reply.assert_not_called()++ ticket.refresh_from_db()+ assert ticket.last_message_at is None+ assert conversations_ticket_fetcher(self.team, CONVERSATIONS_TICKETS_CONFIG, {}) == []+@pytest.mark.django_dbclass TestConversationsTicketFetcherMessages(BaseTest):@@ -131,6 +153,28 @@ class TestConversationsTicketFetcherMessages(BaseTest):assert len(messages) == 1assert messages[0] == ("customer", "Hello there")+ def test_excludes_automated_pr_update_from_snapshot(self):+ _add_comment(self.team, self.ticket, content="Real customer message")+ Comment.objects.create(+ team=self.team,+ scope="conversations_ticket",+ item_id=str(self.ticket.id),+ content="A pull request is open",+ item_context={"author_type": "AI", "is_private": False, "automated_update_key": "pr-123"},+ )+ Comment.objects.create(+ team=self.team,+ scope="conversations_ticket",+ item_id=str(self.ticket.id),+ created_by=self.user,+ content="A team message",+ item_context={"author_type": "AI", "is_private": False, "automated_update_key": "user-supplied"},+ )++ result = conversations_ticket_fetcher(self.team, CONVERSATIONS_TICKETS_CONFIG, {})++ assert result[0]["messages"] == [("customer", "Real customer message"), ("AI", "A team message")]+def test_attaches_multiple_messages_across_author_types(self):_add_comment(self.team, self.ticket, content="User question", author_type="customer")_add_comment(self.team, self.ticket, content="Team reply", author_type="team")diff --git a/products/signals/backend/pull_requests.py b/products/signals/backend/pull_requests.pyindex 5daef029ae49..c1d60f53ef47 100644--- a/products/signals/backend/pull_requests.py+++ b/products/signals/backend/pull_requests.py@@ -142,7 +142,8 @@ def link_pull_request(claim_id=claim_id,type=SignalReportArtefact.ArtefactType.PULL_REQUEST,)- if not links.exists():+ new_link = not links.exists()+ if new_link:link = SignalReportArtefact.add_log(team_id=report.team_id,report_id=str(report.id),@@ -175,6 +176,31 @@ def link_pull_request(schedule_pull_request_label(team_id=report.team_id, report_id=str(report.id), pr_url=pr.url, pr_state=pr.state)+ if (+ actor.kind == "task"+ and actor.task_id+ and (new_link or state_source == PullRequestStateSource.TASK_OUTPUT)+ and state_source != PullRequestStateSource.LEGACY_ASSIGNMENT+ and pr.state+ in {+ SignalReportPullRequest.State.DRAFT,+ SignalReportPullRequest.State.OPEN,+ SignalReportPullRequest.State.UNKNOWN,+ }+ ):+ from products.signals.backend.support_writeback import task_can_write_support_ticket_update++ if task_can_write_support_ticket_update(+ team_id=report.team_id, report_id=str(report.id), task_id=actor.task_id, pr_url=pr.url+ ):+ from products.signals.backend.tasks import write_pull_request_to_support_tickets++ transaction.on_commit(+ partial(+ write_pull_request_to_support_tickets.delay, report.team_id, str(report.id), pr.url, actor.task_id+ ),+ robust=True,+ )if notify_reviewers and state_source != PullRequestStateSource.LEGACY_ASSIGNMENT:# Every verified PR refresh can change paths, ownership, membership, or linked identities.# The assignment worker is bounded and replaces only the owners named by its own latestdiff --git a/products/signals/backend/support_writeback.py b/products/signals/backend/support_writeback.pyindex f93ff5dd00d2..f22f4c6deb9d 100644--- a/products/signals/backend/support_writeback.py+++ b/products/signals/backend/support_writeback.py@@ -8,18 +8,32 @@ them to draw on, which closes the loop without putting agent output in front offrom __future__ import annotations+from urllib.parse import quote+import structlogfrom posthog.models import Team+from posthog.models.github_integration_base import GitHubIntegrationBasefrom products.conversations.backend.facade import api as conversations_facadefrom products.signals.backend.enums import SignalSourceProduct-from products.signals.backend.models import SignalReport+from products.signals.backend.models import SignalReport, SignalReportTaskfrom products.signals.backend.report_urls import ReportLinkSource, build_report_urllogger = structlog.get_logger(__name__)+def task_can_write_support_ticket_update(*, team_id: int, report_id: str, task_id: str, pr_url: str) -> bool:+ from products.tasks.backend.facade import api as tasks_facade++ return SignalReportTask.objects.filter(+ team_id=team_id,+ report_id=report_id,+ task_id=task_id,+ relationship="implementation",+ ).exists() and tasks_facade.is_verified_task_pr_url(task_id=task_id, team_id=team_id, pr_url=pr_url)++def _note_body(report_url: str) -> str:"""A pointer, deliberately carrying none of the report's own content.@@ -34,19 +48,55 @@ def _note_body(report_url: str) -> str:)-def post_report_findings_to_tickets(team: Team, report_id: str, signals: list[dict]) -> int:- """Post a ready report's findings as a private note on each support ticket that contributed to it.-- Returns the number of notes posted. Best-effort: a failure here must not fail the report's- notification flow, so per-ticket errors are logged rather than raised.- """- ticket_ids = sorted(+def _ticket_ids(signals: list[dict]) -> list[str]:+ return sorted({str(signal.get("source_id") or "")for signal in signalsif signal.get("source_product") == SignalSourceProduct.CONVERSATIONS and signal.get("source_id")})+++def _post_notes(team: Team, report_id: str, ticket_ids: list[str], body: str, dedupe_key: str, kind: str) -> int:+ posted = 0+ for ticket_id in ticket_ids:+ try:+ comment_id = conversations_facade.post_ticket_internal_note(+ team_id=team.pk,+ ticket_id=ticket_id,+ content=body,+ dedupe_key=dedupe_key,+ )+ except Exception:+ logger.exception(+ "Failed to post signals note to support ticket",+ report_id=report_id,+ ticket_id=ticket_id,+ team_id=team.pk,+ kind=kind,+ )+ continue+ if comment_id is not None:+ posted += 1+ logger.info(+ "Posted signals notes to support tickets",+ report_id=report_id,+ team_id=team.pk,+ tickets=len(ticket_ids),+ posted=posted,+ kind=kind,+ )+ return posted+++def post_report_findings_to_tickets(team: Team, report_id: str, signals: list[dict]) -> int:+ """Post a ready report's findings as a private note on each support ticket that contributed to it.++ Returns the number of notes posted. Best-effort: a failure here must not fail the report's+ notification flow, so per-ticket errors are logged rather than raised.+ """+ ticket_ids = _ticket_ids(signals)if not ticket_ids:return 0@@ -55,27 +105,51 @@ def post_report_findings_to_tickets(team: Team, report_id: str, signals: list[dibody = _note_body(build_report_url(team.pk, report_id, ReportLinkSource.SUPPORT))+ return _post_notes(team, report_id, ticket_ids, body, f"signals_report:{report_id}", "report")+++def post_pull_request_to_tickets(team: Team, report_id: str, pr_url: str, signals: list[dict]) -> int:+ parsed = GitHubIntegrationBase.parse_pull_request_url(pr_url)+ if parsed is None:+ return 0+ pr_url = f"https://github.com/{quote(parsed.owner, safe='')}/{quote(parsed.repo, safe='')}/pull/{parsed.number}"+ ticket_ids = _ticket_ids(signals)+ if not ticket_ids or not SignalReport.objects.filter(id=report_id, team_id=team.pk).exists():+ return 0++ body = (+ "[PostHog bot] **Self-driving linked a pull request to this report.** Internal note, not sent to the customer.\n\n"+ f"Pull request: {pr_url}\n"+ f"Report: {build_report_url(team.pk, report_id, ReportLinkSource.SUPPORT)}"+ )+ public_body = f"[PostHog bot] Self-driving opened a pull request related to this ticket: {pr_url}"posted = 0+ first_error: Exception | None = Nonefor ticket_id in ticket_ids:try:- comment_id = conversations_facade.post_ticket_internal_note(+ comment_id = conversations_facade.post_ticket_automated_update(team_id=team.pk,ticket_id=ticket_id,- content=body,- dedupe_key=f"signals_report:{report_id}",+ public_content=public_body,+ private_content=body,+ dedupe_key=f"signals_pr:{report_id}:{pr_url}",)- except Exception:+ except Exception as exc:logger.exception(- "Failed to post signals findings to support ticket",+ "Failed to post signals pull request to support ticket",report_id=report_id,ticket_id=ticket_id,team_id=team.pk,)+ if first_error is None:+ first_error = exccontinueif comment_id is not None:posted += 1+ if first_error is not None:+ raise first_errorlogger.info(- "Posted signals findings to support tickets",+ "Posted signals pull request to support tickets",report_id=report_id,team_id=team.pk,tickets=len(ticket_ids),diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.pyindex 6217f4278b01..0015f362cbb4 100644--- a/products/signals/backend/tasks.py+++ b/products/signals/backend/tasks.py@@ -14,6 +14,7 @@ from slack_sdk.errors import SlackApiErrorfrom posthog.celery_queues import CeleryQueuefrom posthog.clickhouse.client.connection import ClickHouseUser+from posthog.clickhouse.workload import Workloadfrom posthog.cloud_utils import get_cached_instance_licensefrom posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitErrorfrom posthog.egress.limiter.policies import Priority@@ -79,14 +80,31 @@ from products.signals.backend.scout_harness.slack_delivery import (post_scout_report_to_slack,slack_api_error_code,)+from products.signals.backend.signal_metadata import fetch_signals_for_report_syncfrom products.signals.backend.slack_inbox_notifications import dispatch_reviewer_added_notificationsfrom products.signals.backend.slack_report_threads import record_scout_report_slack_replies, scout_report_slack_message+from products.signals.backend.support_writeback import (+ post_pull_request_to_tickets,+ task_can_write_support_ticket_update,+)from products.signals.backend.tracker_issues import close_tracker_issue_for_report, link_pull_request_to_tracker_issuefrom products.tasks.backend.facade.repo_activity import RepositoryCommitActivityErrorlogger = structlog.get_logger(__name__)+@shared_task(ignore_result=True, autoretry_for=(Exception,), retry_backoff=True, max_retries=5)+@with_team_scope()+def write_pull_request_to_support_tickets(team_id: int, report_id: str, pr_url: str, task_id: str) -> None:+ if not task_can_write_support_ticket_update(team_id=team_id, report_id=report_id, task_id=task_id, pr_url=pr_url):+ return+ team = Team.objects.filter(id=team_id).first()+ if team is None:+ return+ signals = fetch_signals_for_report_sync(team, report_id, ch_user=ClickHouseUser.SIGNALS, workload=Workload.OFFLINE)+ post_pull_request_to_tickets(team, report_id, pr_url, signals)++@shared_task(bind=True,ignore_result=True,diff --git a/products/signals/backend/test/test_support_writeback.py b/products/signals/backend/test/test_support_writeback.pyindex e163ff59c3ee..6237aa599f40 100644--- a/products/signals/backend/test/test_support_writeback.py+++ b/products/signals/backend/test/test_support_writeback.py@@ -2,12 +2,22 @@ import uuidimport pytestfrom posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from parameterized import parameterizedfrom posthog.models.comment import Comment-from products.conversations.backend.models import Ticket-from products.signals.backend.models import SignalReport-from products.signals.backend.support_writeback import post_report_findings_to_tickets+from products.conversations.backend.facade import api as conversations_facade+from products.conversations.backend.models import ConversationDelivery, TeamConversationsSlackConfig, Ticket+from products.conversations.backend.models.constants import TicketMessageType+from products.conversations.backend.services.messages import ticket_message_type+from products.signals.backend.artefact_attribution import ArtefactAttribution+from products.signals.backend.models import SignalReport, SignalReportTask+from products.signals.backend.pull_requests import PullRequestStateSource, link_pull_request+from products.signals.backend.report_assignments import PullRequestDetails+from products.signals.backend.support_writeback import post_pull_request_to_tickets, post_report_findings_to_tickets+from products.tasks.backend.models import Task, TaskRunWRITEBACK_MODULE_PATH = "products.signals.backend.support_writeback"@@ -67,6 +77,192 @@ class TestPostReportFindingsToTickets(BaseTest):assert (first, second) == (1, 0)assert _ticket_notes(self.team, self.ticket).count() == 1+ def test_pull_request_note_is_private_and_idempotent(self):+ pr_url = "https://github.com/PostHog/posthog/pull/123"++ first = post_pull_request_to_tickets(self.team, str(self.report.id), pr_url, [self.signal])+ second = post_pull_request_to_tickets(self.team, str(self.report.id), pr_url, [self.signal])++ assert (first, second) == (1, 0)+ note = _ticket_notes(self.team, self.ticket).get()+ assert note.item_context["is_private"] is True+ assert note.item_context["author_type"] == "AI"+ assert pr_url in note.content+ assert f"/project/{self.team.pk}/inbox/reports/{self.report.id}?link_source=support" in note.content+ assert self.report.summary not in note.content++ @parameterized.expand([("first", 1), ("second", 2)])+ def test_pull_request_note_failure_retries_without_duplicate_notes(self, _name, failing_call):+ other_ticket = _make_ticket(self.team)+ signals = [self.signal, {"source_product": "conversations", "source_id": str(other_ticket.id)}]+ pr_url = "https://github.com/PostHog/posthog/pull/123"+ original_post = conversations_facade.post_ticket_automated_update+ calls = 0++ def fail_once(**kwargs):+ nonlocal calls+ calls += 1+ if calls == failing_call:+ raise ConnectionError("temporary write failure")+ return original_post(**kwargs)++ with patch(f"{WRITEBACK_MODULE_PATH}.conversations_facade.post_ticket_automated_update", side_effect=fail_once):+ with pytest.raises(ConnectionError, match="temporary write failure"):+ post_pull_request_to_tickets(self.team, str(self.report.id), pr_url, signals)+ post_pull_request_to_tickets(self.team, str(self.report.id), pr_url, signals)++ assert _ticket_notes(self.team, self.ticket).count() == 1+ assert _ticket_notes(self.team, other_ticket).count() == 1+ assert calls == 4++ @parameterized.expand(+ [+ ("approved_internal", {"is_channel": True}, True, True),+ ("not_approved", {"is_channel": True}, False, False),+ ("shared", {"is_channel": True, "is_ext_shared": True}, True, False),+ ("unknown", {}, True, False),+ ("unreadable", None, True, False),+ ]+ )+ def test_pull_request_reply_only_enters_an_approved_internal_slack_thread(+ self, _name, channel_info, approved, expected_public+ ):+ self.team.conversations_settings = {"automated_update_slack_channel_ids": ["C123"] if approved else []}+ self.team.save(update_fields=["conversations_settings"])+ TeamConversationsSlackConfig.objects.update_or_create(+ team=self.team, defaults={"slack_team_id": "T123", "slack_bot_token": "xoxb-test"}+ )+ ticket = Ticket.objects.create_with_number(+ team=self.team,+ widget_session_id="",+ distinct_id="slack-user",+ channel_source="slack",+ slack_channel_id="C123",+ slack_thread_ts="1700000000.000100",+ )+ signal = {"source_product": "conversations", "source_id": str(ticket.id)}+ pr_url = "https://github.com/Post<@U123>Hog/posthog/pull/123?text=<@here>"+ client = MagicMock()+ if channel_info is None:+ client.conversations_info.side_effect = ConnectionError("Slack unavailable")+ else:+ client.conversations_info.return_value = {"channel": channel_info}++ with patch("products.conversations.backend.facade.api.get_slack_client", return_value=client):+ first = post_pull_request_to_tickets(self.team, str(self.report.id), pr_url, [signal])+ second = post_pull_request_to_tickets(self.team, str(self.report.id), pr_url, [signal])++ if not approved:+ client.conversations_info.assert_not_called()++ assert (first, second) == (1, 0)+ reply = _ticket_notes(self.team, ticket).get()+ assert reply.item_context["is_private"] is not expected_public+ assert reply.content.startswith("[PostHog bot]")+ assert "https://github.com/Post%3C%40U123%3EHog/posthog/pull/123" in reply.content+ assert "<@" not in reply.content+ if expected_public:+ assert str(self.report.id) not in reply.content+ assert ticket_message_type(reply.item_context, reply.created_by_id) == TicketMessageType.SENT_REPLY+ delivery = ConversationDelivery.objects.for_team(self.team.id).get(comment_id=reply.id)+ assert delivery.route == {"channel": "C123", "thread_ts": "1700000000.000100"}+ else:+ assert ticket_message_type(reply.item_context, reply.created_by_id) == TicketMessageType.INTERNAL_NOTE+ assert not ConversationDelivery.objects.for_team(self.team.id).filter(comment_id=reply.id).exists()++ def test_linking_pull_request_queues_ticket_note_only_after_verification(self):+ pr_url = "https://github.com/PostHog/posthog/pull/123"+ task = Task.objects.create(team=self.team, created_by=self.user)+ SignalReportTask.objects.create(team=self.team, report=self.report, task=task, relationship="implementation")+ details = PullRequestDetails(+ url=pr_url, repository="PostHog/posthog", number=123, state="unknown", merged=False+ )++ with (+ patch("products.tasks.backend.facade.api.is_verified_task_pr_url") as verified,+ patch("products.signals.backend.tasks.write_pull_request_to_support_tickets.delay") as send_note,+ ):+ verified.return_value = False+ with self.captureOnCommitCallbacks(execute=True):+ link_pull_request(+ report=self.report,+ details=details,+ actor=ArtefactAttribution.from_task(str(task.id)),+ claim_id=None,+ state_source=PullRequestStateSource.TASK_OUTPUT,+ notify_reviewers=False,+ )+ send_note.assert_not_called()+ verified.return_value = True+ with self.captureOnCommitCallbacks(execute=True):+ for _ in range(2):+ link_pull_request(+ report=self.report,+ details=details,+ actor=ArtefactAttribution.from_task(str(task.id)),+ claim_id=None,+ state_source=PullRequestStateSource.TASK_OUTPUT,+ notify_reviewers=False,+ )+ link_pull_request(+ report=self.report,+ details=PullRequestDetails(+ url="https://github.com/PostHog/posthog/pull/124",+ repository="PostHog/posthog",+ number=124,+ state="unknown",+ merged=False,+ ),+ actor=ArtefactAttribution.from_user(self.user.id),+ claim_id=None,+ state_source=PullRequestStateSource.GITHUB,+ notify_reviewers=False,+ )++ assert send_note.call_count == 2+ send_note.assert_called_with(self.team.pk, str(self.report.id), pr_url, str(task.id))++ def test_unrelated_task_cannot_queue_ticket_note(self):+ task = Task.objects.create(team=self.team, created_by=self.user)+ details = PullRequestDetails(+ url="https://github.com/PostHog/posthog/pull/123",+ repository="PostHog/posthog",+ number=123,+ state="unknown",+ merged=False,+ )+ with (+ patch("products.tasks.backend.facade.api.is_verified_task_pr_url", return_value=True),+ patch("products.signals.backend.tasks.write_pull_request_to_support_tickets.delay") as send_note,+ self.captureOnCommitCallbacks(execute=True),+ ):+ link_pull_request(+ report=self.report,+ details=details,+ actor=ArtefactAttribution.from_task(str(task.id)),+ claim_id=None,+ notify_reviewers=False,+ )+ send_note.assert_not_called()++ def test_worker_rechecks_verified_task_pr_before_ticket_write(self):+ from products.signals.backend.tasks import write_pull_request_to_support_tickets++ pr_url = "https://github.com/PostHog/posthog/pull/123"+ task = Task.objects.create(team=self.team, created_by=self.user)+ SignalReportTask.objects.create(team=self.team, report=self.report, task=task, relationship="implementation")+ run = TaskRun.objects.create(team=self.team, task=task, state={})++ with patch("products.signals.backend.tasks.fetch_signals_for_report_sync", return_value=[self.signal]):+ write_pull_request_to_support_tickets.run(self.team.pk, str(self.report.id), pr_url, str(task.id))+ assert not _ticket_notes(self.team, self.ticket).exists()++ run.state = {"verified_pr_urls": [pr_url]}+ run.save(update_fields=["state"])+ write_pull_request_to_support_tickets.run(self.team.pk, str(self.report.id), pr_url, str(task.id))++ assert _ticket_notes(self.team, self.ticket).count() == 1+def test_ignores_signals_from_other_products(self):error_signal = {"source_product": "error_tracking", "source_id": "issue-1"}