:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(conversations): enable discussions on support tickets (#67057)
Luke Belton72d002492854
diff --git a/ee/hogai/context/activity_log/context.py b/ee/hogai/context/activity_log/context.pyindex 99f9ac0d593b..3b89d3659eb0 100644--- a/ee/hogai/context/activity_log/context.py+++ b/ee/hogai/context/activity_log/context.py@@ -34,6 +34,7 @@ SCOPE_DISPLAY_NAMES: dict[str, str] = {"HogFunction": "Data pipeline","PersonalAPIKey": "Personal API key","LLMTrace": "LLM trace",+ "Ticket": "Support ticket",}diff --git a/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx b/frontend/src/lib/components/ActivityLog/humanizeActivity.tsxindex e05496fc856e..f20a1c5e35b8 100644--- a/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx+++ b/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx@@ -174,6 +174,7 @@ const SCOPE_DISPLAY_NAMES: Partial<Record<ActivityScope, { singular: string; plusingular: 'Project secret API key',plural: 'Project secret API keys',},+ [ActivityScope.TICKET]: { singular: 'Support ticket', plural: 'Support tickets' },}export function humanizeScope(scope: ActivityScope | string, singular = false): string {diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 554adde9ca6b..0e31c5799f2b 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -294,6 +294,7 @@ export const FEATURE_FLAGS = {DATA_WAREHOUSE_SCENE: 'data-warehouse-scene', // owner: #team-data-modelingDATA_WAREHOUSE_SEMANTIC_ENRICHMENT: 'data-warehouse-semantic-enrichment', // owner: #team-warehouse-sourcesDEFAULT_EVALUATION_ENVIRONMENTS: 'default-evaluation-environments', // owner: @dmarticus #team-feature-flags+ DISCUSSIONS_SLACK_SYNC: 'discussions-slack-sync', // owner: #team-platform-featuresDROP_PERSON_LIST_ORDER_BY: 'drop-person-list-order-by', // owner: @arthurdedeus #team-customer-analyticsDWH_POSTGRES_CDC: 'dwh-postgres-cdc', // owner: #team-warehouse-sourcesDWH_SOURCE_METRICS: 'dwh-source-metrics', // owner: #team-warehouse-sourcesdiff --git a/posthog/api/comments.py b/posthog/api/comments.pyindex 529e14ff1739..23f7ed7b1d43 100644--- a/posthog/api/comments.py+++ b/posthog/api/comments.py@@ -18,7 +18,7 @@ from posthog.models import Userfrom posthog.models.activity_logging.activity_log import Change, Detail, log_activityfrom posthog.models.activity_logging.model_activity import get_was_impersonatedfrom posthog.models.comment import Comment-from posthog.models.comment.comment import activity_log_scope_for+from posthog.models.comment.comment import TICKET_COMMENT_SCOPES, activity_log_scope_forfrom posthog.models.comment.utils import produce_discussion_mention_events, send_mention_notificationsfrom posthog.tasks.email import send_discussions_mentioned@@ -26,12 +26,22 @@ if TYPE_CHECKING:from posthog.rbac.user_access_control import UserAccessControl+def _normalize_scope(scope: Any) -> Any:+ """Match how the serializer will store a submitted scope.++ `scope` is a CharField, so DRF trims surrounding whitespace before saving — comparing the+ raw value here would let " Ticket " read as non-ticket while persisting as "Ticket".+ """+ return scope.strip() if isinstance(scope, str) else scope++def _require_ticket_editor_access(*, team_id: int, item_id: str | None, user_access_control: "UserAccessControl") -> None:- """Comments with scope=conversations_ticket are ticket messages (see TicketViewSet.reply) —- enforce the same object-level RBAC here, since the generic comments API is the write path the- Support UI actually uses and isn't gated by TicketViewSet's own access control."""+ """Ticket-carrying comments (customer messages and internal ticket discussions) are ticket+ content (see TicketViewSet.reply) — enforce the same object-level RBAC here, since the generic+ comments API is the write path the Support UI actually uses and isn't gated by TicketViewSet's+ own access control."""if not item_id:return@@ -128,22 +138,42 @@ class CommentSerializer(serializers.ModelSerializer):if "is_task" in data and bool(data["is_task"]) != bool(instance.is_task):raise exceptions.ValidationError({"is_task": "Cannot change task state after creation."})- # Check both the comment's persisted (scope, item_id) and the submitted target — so losing- # ticket editor access after creation, and re-scoping a comment into or out of a ticket,- # are all caught, not just fresh ticket-message creation.- scopes_and_items = {- (- data.get("scope", instance.scope if instance else None),- data.get("item_id", instance.item_id if instance else None),- )- }+ # A reply lives in its parent's thread: a scope mismatch would let content cross the+ # authorization boundary between ticket and non-ticket discussions in either direction.+ source_comment = (+ data["source_comment"] if "source_comment" in data else getattr(instance, "source_comment", None)+ )+ scope = data["scope"] if "scope" in data else getattr(instance, "scope", None)+ item_id = data["item_id"] if "item_id" in data else getattr(instance, "item_id", None)+ if source_comment is not None:+ if source_comment.team_id != self.context["team_id"]:+ raise exceptions.ValidationError({"source_comment": "Comment not found."})+ if source_comment.scope != scope:+ raise exceptions.ValidationError(+ {"scope": "A reply must use the same scope as the comment it replies to."}+ )+ # /thread selects replies by source_comment_id alone, so a ticket reply carrying a+ # different item_id would render in a thread on a ticket its author never had to pass+ # the editor check for.+ if scope in TICKET_COMMENT_SCOPES and source_comment.item_id != item_id:+ raise exceptions.ValidationError(+ {"item_id": "A reply must belong to the same ticket as the comment it replies to."}+ )++ # Check the comment's persisted (scope, item_id), the submitted target, and a reply's+ # parent — so losing ticket editor access after creation, re-scoping a comment into or out+ # of a ticket, and replying into a thread on another ticket are all caught, not just fresh+ # ticket-message creation.+ scopes_and_items = {(scope, item_id)}if instance:scopes_and_items.add((instance.scope, instance.item_id))- for scope, item_id in scopes_and_items:- if scope == "conversations_ticket":+ if source_comment is not None:+ scopes_and_items.add((source_comment.scope, source_comment.item_id))+ for target_scope, target_item_id in scopes_and_items:+ if target_scope in TICKET_COMMENT_SCOPES:_require_ticket_editor_access(team_id=self.context["get_team"]().id,- item_id=item_id,+ item_id=target_item_id,user_access_control=self.context["get_user_access_control"](),)@@ -238,7 +268,10 @@ class CommentPagination(pagination.CursorPagination):class CommentListQueryParamsSerializer(serializers.Serializer):scope = serializers.CharField(required=False,- help_text="Filter by resource type (e.g. Dashboard, FeatureFlag, Insight, Replay).",+ help_text=(+ "Filter by resource type (e.g. Dashboard, FeatureFlag, Insight, Replay). "+ "Support-ticket scopes (Ticket, conversations_ticket) additionally require ticket API scope access."+ ),)item_id = serializers.CharField(required=False, help_text="Filter by the ID of the resource being commented on.")search = serializers.CharField(required=False, help_text="Full-text search within comment content.")@@ -269,6 +302,51 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVscope_object = "comment"scope_object_read_actions = ["list", "retrieve", "thread", "count"]+ def dangerously_get_required_scopes(self, request: Request, view: Any) -> list[str] | None:+ """Ticket-scoped comments require ticket API scope access instead of comment access.++ Candidate scopes are the union of every scope that determines what the request can+ read or write: the query-param scope (the queryset always filters by it, including for+ detail lookups and /thread), the stored scope of the pk target (authoritative — a+ mismatched body scope can't sidestep it), and the body scope on writes only (what+ create writes and update can rewrite; a body on a GET selects nothing). If any+ candidate is ticket-carrying the request needs ticket access, and any non-ticket+ candidate keeps the default comment requirement alongside it (the scopes are ANDed).+ """+ candidate_scopes: set[Any] = set()+ if query_scope := request.GET.get("scope"):+ candidate_scopes.add(_normalize_scope(query_scope))+ if pk := self.kwargs.get("pk"):+ try:+ candidate_scopes.add(+ Comment.objects.filter(team_id=self.team_id, pk=pk).values_list("scope", flat=True).first()+ )+ except (ValueError, django_exceptions.ValidationError):+ return None+ if request.method not in ("GET", "HEAD", "OPTIONS") and isinstance(request.data, dict):+ if body_scope := request.data.get("scope"):+ candidate_scopes.add(_normalize_scope(body_scope))+ # A reply is read back through its parent's thread, so the parent's stored scope+ # gates the write too — a non-ticket body scope must not attach a reply to a+ # ticket thread (nor a ticket reply to a non-ticket parent).+ if source_comment := request.data.get("source_comment"):+ try:+ candidate_scopes.add(+ Comment.objects.filter(team_id=self.team_id, pk=source_comment)+ .values_list("scope", flat=True)+ .first()+ )+ except (ValueError, django_exceptions.ValidationError):+ return None+ candidate_scopes.discard(None)+ if not candidate_scopes & TICKET_COMMENT_SCOPES:+ return None+ access = "read" if self.action in self.scope_object_read_actions else "write"+ required: list[str] = [f"ticket:{access}"]+ if candidate_scopes - TICKET_COMMENT_SCOPES:+ required.append(f"comment:{access}")+ return required+@extend_schema(parameters=[CommentListQueryParamsSerializer])def list(self, request, *args, **kwargs):return super().list(request, *args, **kwargs)@@ -278,9 +356,41 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVcontext["get_user_access_control"] = lambda: self.user_access_controlreturn context+ def _require_ticket_viewer_access_for_pk(self) -> None:+ """Gate a detail action on the ticket its target comment belongs to.++ Detail actions carry no scope param, so the queryset-level ticket filter never runs for+ them — and API scope access doesn't help a session caller denied the ticket. An item_id+ that resolves to no ticket is left alone: the write path rejects those, so only fixtures+ have them and there is no ticket content to protect.+ """+ from products.conversations.backend.models.ticket import ( # noqa: PLC0415 — keeps the generic comments API decoupled from the conversations product, only imported for ticket-scoped reads+ Ticket,+ )++ pk = self.kwargs.get("pk")+ if not pk:+ return+ try:+ target = Comment.objects.filter(team_id=self.team_id, pk=pk).values_list("scope", "item_id").first()+ except (ValueError, django_exceptions.ValidationError):+ return+ if not target:+ return+ scope, item_id = target+ if scope not in TICKET_COMMENT_SCOPES or not item_id:+ return+ try:+ ticket = Ticket.objects.get(team_id=self.team_id, id=item_id)+ except (Ticket.DoesNotExist, ValueError, django_exceptions.ValidationError):+ return+ if not self.user_access_control.check_access_level_for_object(ticket, required_level="viewer"):+ # Match the list path, where a denied ticket's comments are simply absent.+ raise exceptions.NotFound()+def _filter_ticket_scoped_queryset(self, queryset: QuerySet, item_id: str | None) -> QuerySet:- """conversations_ticket comments are ticket messages — restrict them to tickets the- caller has viewer access to, mirroring TicketViewSet's own object-level filtering."""+ """Ticket-carrying comments are ticket content — restrict them to tickets the caller has+ viewer access to, mirroring TicketViewSet's own object-level filtering."""from products.conversations.backend.models.ticket import ( # noqa: PLC0415 — keeps the generic comments API decoupled from the conversations product, only imported for ticket-scoped readsTicket,)@@ -319,12 +429,17 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVscope = params.get("scope")if scope:queryset = queryset.filter(scope=scope)- if scope == "conversations_ticket":+ if scope in TICKET_COMMENT_SCOPES:queryset = self._filter_ticket_scoped_queryset(queryset, params.get("item_id"))+ elif self.action in ("list", "count"):+ # Ticket-carrying comments (customer messages and internal ticket discussions) never+ # appear in unscoped enumeration — only when explicitly requested by scope.+ queryset = queryset.exclude(scope__in=TICKET_COMMENT_SCOPES)else:- # Exclude conversations_ticket comments by default - they use rich content- # from SupportEditor and should only be viewed in the conversations product- queryset = queryset.exclude(scope="conversations_ticket")+ # Detail actions (retrieve, thread, send_to_slack, ...) carry no scope param, so the+ # branch above never gates them — and API scope access doesn't cover session callers+ # denied the ticket. Check the pk target's own ticket instead.+ self._require_ticket_viewer_access_for_pk()if params.get("item_id"):queryset = queryset.filter(item_id=params.get("item_id"))@@ -382,7 +497,7 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVcomment = self.get_object()if not comment.is_task:raise exceptions.ValidationError("Only tasks can be marked complete")- if comment.scope == "conversations_ticket":+ if comment.scope in TICKET_COMMENT_SCOPES:_require_ticket_editor_access(team_id=self.team_id, item_id=comment.item_id, user_access_control=self.user_access_control)@@ -408,7 +523,7 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVcomment = self.get_object()if not comment.is_task:raise exceptions.ValidationError("Only tasks can be reopened")- if comment.scope == "conversations_ticket":+ if comment.scope in TICKET_COMMENT_SCOPES:_require_ticket_editor_access(team_id=self.team_id, item_id=comment.item_id, user_access_control=self.user_access_control)diff --git a/posthog/api/test/test_comments.py b/posthog/api/test/test_comments.pyindex 6c342279afca..5ed55eb4a6da 100644--- a/posthog/api/test/test_comments.py+++ b/posthog/api/test/test_comments.py@@ -576,11 +576,216 @@ class TestComments(APIBaseTest, QueryMatchingTest):assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED+ def _scoped_key_headers(self, scopes: list[str]) -> dict[str, str]:+ from posthog.models.personal_api_key import PersonalAPIKey, hash_key_value+ from posthog.models.utils import generate_random_token_personal++ value = generate_random_token_personal()+ PersonalAPIKey.objects.create(label="scoped", user=self.user, secure_value=hash_key_value(value), scopes=scopes)+ return {"authorization": f"Bearer {value}"}++ @parameterized.expand(+ [+ ("comment_read_ticket_discussions", ["comment:read"], "Ticket", status.HTTP_403_FORBIDDEN),+ ("comment_read_ticket_messages", ["comment:read"], "conversations_ticket", status.HTTP_403_FORBIDDEN),+ ("ticket_read_ticket_discussions", ["ticket:read"], "Ticket", status.HTTP_200_OK),+ ("comment_read_other_scopes", ["comment:read"], "Notebook", status.HTTP_200_OK),+ ]+ )+ def test_ticket_scoped_comments_require_ticket_api_scope(+ self, _name: str, scopes: list[str], comment_scope: str, expected_status: int+ ) -> None:+ response = self.client.get(+ f"/api/projects/{self.team.id}/comments?scope={comment_scope}",+ headers=self._scoped_key_headers(scopes),+ )+ assert response.status_code == expected_status++ @parameterized.expand([("exact", "Ticket"), ("whitespace_padded", " Ticket ")])+ def test_creating_ticket_scoped_comment_requires_ticket_write_scope(self, _name: str, scope: str) -> None:+ # DRF trims the scope before storing it, so a padded value must not read as non-ticket here.+ response = self.client.post(+ f"/api/projects/{self.team.id}/comments",+ {"content": "internal note", "scope": scope, "item_id": "some-ticket-id"},+ headers=self._scoped_key_headers(["comment:write"]),+ )+ assert response.status_code == status.HTTP_403_FORBIDDEN++ def test_ticket_scoped_comments_excluded_from_default_list(self) -> None:+ Comment.objects.create(team=self.team, scope="Ticket", item_id="t1", content="discussion", created_by=self.user)+ Comment.objects.create(+ team=self.team, scope="conversations_ticket", item_id="t1", content="message", created_by=self.user+ )+ self._create_comment({"scope": "Notebook", "content": "normal"})++ response = self.client.get(f"/api/projects/{self.team.id}/comments")+ assert response.status_code == status.HTTP_200_OK+ assert [c["scope"] for c in response.json()["results"]] == ["Notebook"]++ def test_ticket_scoped_comment_detail_actions_work_for_session_users(self) -> None:+ # Detail actions carry no scope param; the default-list exclusion must not 404 them.+ comment = Comment.objects.create(+ team=self.team, scope="Ticket", item_id="t1", content="discussion", created_by=self.user+ )+ response = self.client.get(f"/api/projects/{self.team.id}/comments/{comment.id}")+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["scope"] == "Ticket"++ def test_ticket_scoped_comment_detail_requires_ticket_api_scope(self) -> None:+ comment = Comment.objects.create(+ team=self.team, scope="Ticket", item_id="t1", content="discussion", created_by=self.user+ )+ response = self.client.get(+ f"/api/projects/{self.team.id}/comments/{comment.id}",+ headers=self._scoped_key_headers(["comment:read"]),+ )+ assert response.status_code == status.HTTP_403_FORBIDDEN++ def test_query_scope_cannot_override_ticket_body_scope_on_create(self) -> None:+ # ?scope= filters lists; the created object's scope comes from the body — the body decides.+ response = self.client.post(+ f"/api/projects/{self.team.id}/comments?scope=Notebook",+ {"content": "internal note", "scope": "Ticket", "item_id": "some-ticket-id"},+ headers=self._scoped_key_headers(["comment:write"]),+ )+ assert response.status_code == status.HTTP_403_FORBIDDEN++ def test_body_scope_cannot_override_stored_ticket_scope_on_detail(self) -> None:+ comment = Comment.objects.create(+ team=self.team, scope="Ticket", item_id="t1", content="discussion", created_by=self.user+ )+ response = self.client.patch(+ f"/api/projects/{self.team.id}/comments/{comment.id}",+ {"scope": "Notebook", "content": "rewritten"},+ headers=self._scoped_key_headers(["comment:write"]),+ )+ assert response.status_code == status.HTTP_403_FORBIDDEN++ def test_ticket_scope_key_cannot_write_non_ticket_comment_via_body_scope(self) -> None:+ comment = Comment.objects.create(+ team=self.team, scope="Notebook", item_id="n1", content="note", created_by=self.user+ )+ response = self.client.patch(+ f"/api/projects/{self.team.id}/comments/{comment.id}",+ {"scope": "Ticket", "content": "rewritten"},+ headers=self._scoped_key_headers(["ticket:write"]),+ )+ assert response.status_code == status.HTTP_403_FORBIDDEN++ def test_comment_key_cannot_attach_reply_to_ticket_thread(self) -> None:+ # The parent's stored scope gates a reply's create — a non-ticket body scope must not+ # smuggle a reply into a ticket discussion (it would render in the ticket's /thread).+ parent = Comment.objects.create(+ team=self.team, scope="Ticket", item_id="t1", content="root", created_by=self.user+ )+ response = self.client.post(+ f"/api/projects/{self.team.id}/comments",+ {"content": "sneaky", "scope": "Notebook", "item_id": "n1", "source_comment": str(parent.id)},+ headers=self._scoped_key_headers(["comment:write"]),+ )+ assert response.status_code == status.HTTP_403_FORBIDDEN+ assert Comment.objects.filter(source_comment=parent).count() == 0++ def test_reply_scope_must_match_parent_scope(self) -> None:+ # Even with both API scopes granted, a cross-scope reply row must never exist: a Ticket+ # reply under a non-ticket parent would leak through the parent's /thread to comment:read.+ parent = Comment.objects.create(+ team=self.team, scope="Notebook", item_id="n1", content="root", created_by=self.user+ )+ response = self.client.post(+ f"/api/projects/{self.team.id}/comments",+ {"content": "cross-scope", "scope": "Ticket", "item_id": "t1", "source_comment": str(parent.id)},+ headers=self._scoped_key_headers(["ticket:write", "comment:write"]),+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert Comment.objects.filter(source_comment=parent).count() == 0++ def test_reply_cannot_reference_another_teams_comment(self) -> None:+ other_team = self.organization.teams.create(name="other")+ parent = Comment.objects.create(+ team=other_team, scope="Notebook", item_id="n1", content="root", created_by=self.user+ )+ response = self.client.post(+ f"/api/projects/{self.team.id}/comments",+ {"content": "cross-team", "scope": "Notebook", "item_id": "n1", "source_comment": str(parent.id)},+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert Comment.objects.filter(source_comment=parent).count() == 0++ def test_get_body_cannot_mask_ticket_query_scope(self) -> None:+ # A JSON body on a GET selects nothing — the query scope drives the queryset and must+ # drive the requirement.+ response = self.client.generic(+ "GET",+ f"/api/projects/{self.team.id}/comments?scope=Ticket",+ data='{"scope": "Notebook"}',+ content_type="application/json",+ headers=self._scoped_key_headers(["comment:read"]),+ )+ assert response.status_code == status.HTTP_403_FORBIDDEN++ def test_thread_query_scope_requires_ticket_access(self) -> None:+ # The stored parent scope must not mask a ticket query scope that still filters the replies.+ parent = Comment.objects.create(+ team=self.team, scope="Notebook", item_id="n1", content="root", created_by=self.user+ )+ response = self.client.get(+ f"/api/projects/{self.team.id}/comments/{parent.id}/thread?scope=Ticket",+ headers=self._scoped_key_headers(["comment:read"]),+ )+ assert response.status_code == status.HTTP_403_FORBIDDEN++ def test_ticket_comment_content_masked_in_activity_log(self) -> None:+ # Activity logs are readable with activity_log:read only — ticket bodies must not leak there.+ Comment.objects.create(+ team=self.team, scope="Ticket", item_id="t1", content="internal discussion", created_by=self.user+ )+ entry = ActivityLog.objects.filter(team_id=self.team.id, scope="Ticket", activity="commented").first()+ assert entry is not None+ assert entry.detail is not None+ assert entry.detail["changes"][0]["after"] == "masked"+ assert "internal discussion" not in str(entry.detail)++ def test_ticket_reply_content_masked_in_activity_log(self) -> None:+ # Replies are logged under the parent thread's "Comment" activity scope, not the ticket+ # scope — masking must key off the comment's own scope or reply bodies leak.+ parent = Comment.objects.create(+ team=self.team, scope="Ticket", item_id="t1", content="internal discussion", created_by=self.user+ )+ Comment.objects.create(+ team=self.team,+ scope="Ticket",+ item_id="t1",+ content="secret reply",+ created_by=self.user,+ source_comment=parent,+ )+ entry = ActivityLog.objects.filter(+ team_id=self.team.id, scope="Comment", item_id=str(parent.id), activity="commented"+ ).first()+ assert entry is not None+ assert entry.detail is not None+ assert entry.detail["changes"][0]["after"] == "masked"+ assert "secret reply" not in str(entry.detail)++ def test_non_ticket_comment_content_not_masked_in_activity_log(self) -> None:+ Comment.objects.create(+ team=self.team, scope="Notebook", item_id="n1", content="plain note", created_by=self.user+ )+ entry = ActivityLog.objects.filter(team_id=self.team.id, scope="Notebook", activity="commented").first()+ assert entry is not None+ assert entry.detail is not None+ assert entry.detail["changes"][0]["after"] == "plain note"+++TICKET_SCOPE_CASES = [("conversations_ticket",), ("Ticket",)]+class TestCommentsTicketAccessControl(APIBaseTest):- """conversations_ticket comments are ticket messages read/written through this generic- endpoint by the Support UI (not TicketViewSet) — object-level ticket RBAC must be- enforced here too, or a denied member can read/write a ticket's messages directly."""+ """Ticket-carrying comments — customer messages (conversations_ticket) and internal ticket+ discussions (Ticket) — are read/written through this generic endpoint by the Support UI (not+ TicketViewSet), so object-level ticket RBAC must be enforced here too, or a denied member can+ read/write a ticket's contents directly."""def setUp(self) -> None:super().setUp()@@ -602,26 +807,36 @@ class TestCommentsTicketAccessControl(APIBaseTest):team=self.team,access_level="none",)- Comment.objects.create(- team=self.team,- scope="conversations_ticket",- item_id=str(self.ticket.id),- content="a private message",- )-- def test_denied_member_cannot_list_ticket_messages(self) -> None:- response = self.client.get(- f"/api/projects/{self.team.id}/comments?scope=conversations_ticket&item_id={self.ticket.id}"- )+ for scope in ("conversations_ticket", "Ticket"):+ Comment.objects.create(+ team=self.team,+ scope=scope,+ item_id=str(self.ticket.id),+ content="a private message",+ )++ @parameterized.expand(TICKET_SCOPE_CASES)+ def test_denied_member_cannot_list_ticket_messages(self, scope: str) -> None:+ response = self.client.get(f"/api/projects/{self.team.id}/comments?scope={scope}&item_id={self.ticket.id}")assert response.status_code == status.HTTP_200_OKassert response.json()["results"] == []- def test_denied_member_cannot_create_ticket_message(self) -> None:+ @parameterized.expand(TICKET_SCOPE_CASES)+ def test_denied_member_cannot_retrieve_ticket_message_by_id(self, scope: str) -> None:+ # Detail actions carry no scope param, so the queryset-level ticket filter never runs.+ message = Comment.objects.get(scope=scope, item_id=str(self.ticket.id))++ response = self.client.get(f"/api/projects/{self.team.id}/comments/{message.id}")++ assert response.status_code == status.HTTP_404_NOT_FOUND++ @parameterized.expand(TICKET_SCOPE_CASES)+ def test_denied_member_cannot_create_ticket_message(self, scope: str) -> None:response = self.client.post(f"/api/projects/{self.team.id}/comments",{"content": "sneaking in a reply",- "scope": "conversations_ticket",+ "scope": scope,"item_id": str(self.ticket.id),"item_context": {"author_type": "support", "is_private": False},},@@ -629,59 +844,61 @@ class TestCommentsTicketAccessControl(APIBaseTest):assert response.status_code == status.HTTP_403_FORBIDDENassert not Comment.objects.filter(item_id=str(self.ticket.id), content="sneaking in a reply").exists()- def test_viewer_can_list_but_not_create_ticket_message(self) -> None:+ @parameterized.expand(TICKET_SCOPE_CASES)+ def test_viewer_can_list_but_not_create_ticket_message(self, scope: str) -> None:AccessControl.objects.filter(resource_id=str(self.ticket.id)).update(access_level="viewer")- list_response = self.client.get(- f"/api/projects/{self.team.id}/comments?scope=conversations_ticket&item_id={self.ticket.id}"- )+ list_response = self.client.get(f"/api/projects/{self.team.id}/comments?scope={scope}&item_id={self.ticket.id}")assert len(list_response.json()["results"]) == 1create_response = self.client.post(f"/api/projects/{self.team.id}/comments",{"content": "viewer trying to reply",- "scope": "conversations_ticket",+ "scope": scope,"item_id": str(self.ticket.id),"item_context": {"author_type": "support", "is_private": False},},)assert create_response.status_code == status.HTTP_403_FORBIDDEN- def test_editor_can_list_and_create_ticket_message(self) -> None:+ @parameterized.expand(TICKET_SCOPE_CASES)+ def test_editor_can_list_and_create_ticket_message(self, scope: str) -> None:AccessControl.objects.filter(resource_id=str(self.ticket.id)).update(access_level="editor")create_response = self.client.post(f"/api/projects/{self.team.id}/comments",{"content": "editor reply",- "scope": "conversations_ticket",+ "scope": scope,"item_id": str(self.ticket.id),"item_context": {"author_type": "support", "is_private": False},},)assert create_response.status_code == status.HTTP_201_CREATED- def test_creator_downgraded_to_viewer_cannot_edit_own_ticket_message(self) -> None:+ @parameterized.expand(TICKET_SCOPE_CASES)+ def test_creator_downgraded_to_viewer_cannot_edit_own_ticket_message(self, scope: str) -> None:AccessControl.objects.filter(resource_id=str(self.ticket.id)).update(access_level="editor")own_message = Comment.objects.create(team=self.team,created_by=self.member,- scope="conversations_ticket",+ scope=scope,item_id=str(self.ticket.id),content="my reply",)AccessControl.objects.filter(resource_id=str(self.ticket.id)).update(access_level="viewer")response = self.client.patch(- f"/api/projects/{self.team.id}/comments/{own_message.id}?scope=conversations_ticket",+ f"/api/projects/{self.team.id}/comments/{own_message.id}?scope={scope}",{"content": "edited after being downgraded"},)assert response.status_code == status.HTTP_403_FORBIDDENown_message.refresh_from_db()assert own_message.content == "my reply"- def test_cannot_rescope_existing_comment_into_denied_ticket(self) -> None:+ @parameterized.expand(TICKET_SCOPE_CASES)+ def test_cannot_rescope_existing_comment_into_denied_ticket(self, scope: str) -> None:own_comment = Comment.objects.create(team=self.team,created_by=self.member,@@ -692,7 +909,7 @@ class TestCommentsTicketAccessControl(APIBaseTest):response = self.client.patch(f"/api/projects/{self.team.id}/comments/{own_comment.id}",- {"scope": "conversations_ticket", "item_id": str(self.ticket.id)},+ {"scope": scope, "item_id": str(self.ticket.id)},)assert response.status_code == status.HTTP_403_FORBIDDENown_comment.refresh_from_db()@@ -708,15 +925,19 @@ class TestCommentsTicketAccessControl(APIBaseTest):access_level="none",)- def test_member_denied_ticket_resource_cannot_list_messages_across_tickets(self) -> None:+ @parameterized.expand(TICKET_SCOPE_CASES)+ def test_member_denied_ticket_resource_cannot_list_messages_across_tickets(self, scope: str) -> None:self._deny_ticket_resource()- response = self.client.get(f"/api/projects/{self.team.id}/comments?scope=conversations_ticket")+ response = self.client.get(f"/api/projects/{self.team.id}/comments?scope={scope}")assert response.status_code == status.HTTP_200_OKassert response.json()["results"] == []- def test_member_denied_ticket_resource_still_lists_messages_of_specifically_granted_ticket(self) -> None:+ @parameterized.expand(TICKET_SCOPE_CASES)+ def test_member_denied_ticket_resource_still_lists_messages_of_specifically_granted_ticket(+ self, scope: str+ ) -> None:self._deny_ticket_resource()AccessControl.objects.create(resource="ticket",@@ -726,28 +947,61 @@ class TestCommentsTicketAccessControl(APIBaseTest):access_level="viewer",)- response = self.client.get(f"/api/projects/{self.team.id}/comments?scope=conversations_ticket")+ response = self.client.get(f"/api/projects/{self.team.id}/comments?scope={scope}")assert [result["content"] for result in response.json()["results"]] == ["a private message"]- def test_viewer_cannot_complete_ticket_task(self) -> None:+ @parameterized.expand(TICKET_SCOPE_CASES)+ def test_viewer_cannot_complete_ticket_task(self, scope: str) -> None:AccessControl.objects.filter(resource_id=str(self.ticket.id)).update(access_level="viewer")task = Comment.objects.create(team=self.team,created_by=self.member,- scope="conversations_ticket",+ scope=scope,item_id=str(self.ticket.id),content="a ticket task",is_task=True,)response = self.client.post(- f"/api/projects/{self.team.id}/comments/{task.id}/complete?scope=conversations_ticket",+ f"/api/projects/{self.team.id}/comments/{task.id}/complete?scope={scope}",)assert response.status_code == status.HTTP_403_FORBIDDENtask.refresh_from_db()assert task.completed_at is None+ @parameterized.expand(TICKET_SCOPE_CASES)+ def test_cannot_reply_into_a_denied_ticket_using_an_editable_ticket_item_id(self, scope: str) -> None:+ # /thread selects by source_comment_id, so a reply naming a ticket the member can edit+ # would still render in the denied ticket's thread if item_id weren't pinned to the parent.+ editable_ticket = Ticket.objects.create_with_number(+ team=self.team,+ channel_source=Channel.WIDGET,+ widget_session_id="editable-session",+ distinct_id="editable-user",+ status=Status.OPEN,+ )+ AccessControl.objects.create(+ resource="ticket",+ resource_id=str(editable_ticket.id),+ organization_member=self.member.organization_memberships.get(organization=self.organization),+ team=self.team,+ access_level="editor",+ )+ parent = Comment.objects.get(scope=scope, item_id=str(self.ticket.id))++ response = self.client.post(+ f"/api/projects/{self.team.id}/comments",+ {+ "content": "injected into a denied ticket",+ "scope": scope,+ "item_id": str(editable_ticket.id),+ "source_comment": str(parent.id),+ },+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert not Comment.objects.filter(source_comment=parent).exists()+class TestDiscussionMentionInternalEvents(APIBaseTest, QueryMatchingTest):@mock.patch("posthog.models.comment.utils.produce_internal_event")diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex 510228c8aaea..c7afc5f29b7a 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -1,6 +1,6 @@import jsonimport dataclasses-from typing import TYPE_CHECKING, Any, Literal, Optional, Required, TypedDict, Union+from typing import TYPE_CHECKING, Any, Literal, Optional, Required, TypedDict, Union, castfrom uuid import UUIDfrom django.conf import settings@@ -313,6 +313,14 @@ field_with_masked_contents: dict[AuditableScope, list[str]] = {"temporary_token","pending_email",],+ # Support-ticket comment bodies are gated on ticket access and must not be readable via+ # activity_log:read. Both ticket comment scopes mask `content`: internal ticket discussions+ # ("Ticket") and customer-facing ticket messages ("conversations_ticket" — the literal scope+ # the conversations product writes, not an ActivityScope member, hence the cast). Comment rows+ # never go through changes_between; the Comment post_save signal consults these entries+ # directly, keyed by the comment's own scope.+ "Ticket": ["content"],+ cast(AuditableScope, "conversations_ticket"): ["content"],}field_name_overrides: dict[AuditableScope, dict[str, str]] = {@@ -466,6 +474,25 @@ activity_visibility_restrictions: list[dict[str, Any]] = ["exclude_when": {},"allow_staff": True,},+ {+ # Support-ticket comment rows: bodies are gated on ticket access, and rows written before+ # write-time masking (see field_with_masked_contents) still hold plaintext content readable+ # with only activity_log:read. People with ticket access read the discussion on the ticket+ # itself, so nothing needs these rows in the feeds. Ticket lifecycle activities+ # (created/updated) stay visible — only comment rows are hidden.+ "scope": "Ticket",+ "activities": ["commented", "created task"],+ "exclude_when": {},+ "allow_staff": True,+ },+ {+ # As above, for customer-facing ticket messages (the literal scope the conversations+ # product writes).+ "scope": "conversations_ticket",+ "activities": ["commented", "created task"],+ "exclude_when": {},+ "allow_staff": True,+ },]field_exclusions: dict[AuditableScope, list[str]] = {diff --git a/posthog/models/comment/comment.py b/posthog/models/comment/comment.pyindex b88698db1aab..50b95f4c056f 100644--- a/posthog/models/comment/comment.py+++ b/posthog/models/comment/comment.py@@ -4,7 +4,13 @@ from django.contrib.postgres.indexes import GinIndex, OpClassfrom django.db import modelsfrom django.db.models.functions import Upper-from posthog.models.activity_logging.activity_log import Change, Detail, log_activity+from posthog.models.activity_logging.activity_log import (+ AuditableScope,+ Change,+ Detail,+ field_with_masked_contents,+ log_activity,+)from posthog.models.activity_logging.model_activity import get_was_impersonatedfrom posthog.models.signals import mutable_receiverfrom posthog.models.utils import RootTeamMixin, UUIDTModel@@ -61,6 +67,13 @@ class Comment(UUIDTModel, RootTeamMixin):]+# Comment scopes that carry support-ticket data: customer-facing ticket messages+# (conversations_ticket) and internal ticket discussions (Ticket). Reading or writing these+# requires ticket access, not just comment access — and their content must not leak through+# surfaces gated on weaker scopes (e.g. activity logs).+TICKET_COMMENT_SCOPES = frozenset({"Ticket", "conversations_ticket"})++def activity_log_scope_for(comment: Comment) -> str:# Map legacy "recording" → "Replay"; replies are logged under the parent thread.corrected = "Replay" if comment.scope == "recording" else comment.scope@@ -90,6 +103,14 @@ def log_comment_activity(sender, instance: Comment, created: bool, **kwargs):scope = activity_log_scope_for(instance)activity = "created task" if instance.is_task else "commented"+ # Ticket comment bodies are gated on ticket access; the activity log is readable with+ # only activity_log:read, so the content must not ride along in the change record.+ # Masking is driven by field_with_masked_contents, keyed by the comment's own scope+ # (not the activity scope) so ticket replies — logged under the parent thread's+ # "Comment" scope — are masked too.+ masked_fields = field_with_masked_contents.get(cast(AuditableScope, instance.scope), [])+ logged_content = "masked" if "content" in masked_fields else instance.content+log_activity(organization_id=None,team_id=instance.team_id,@@ -101,6 +122,6 @@ def log_comment_activity(sender, instance: Comment, created: bool, **kwargs):detail=Detail(# name=TODO,# short_id=TODO,- changes=[Change(type="Comment", field="content", action="created", after=instance.content)],+ changes=[Change(type="Comment", field="content", action="created", after=logged_content)],),)diff --git a/posthog/models/comment/utils.py b/posthog/models/comment/utils.pyindex 7a2f881a0473..4f72b3449a8f 100644--- a/posthog/models/comment/utils.py+++ b/posthog/models/comment/utils.py@@ -22,9 +22,11 @@ SCOPE_TO_SOURCE_TYPE: dict[str, str] = {"Survey": "survey","Experiment": "experiment","ErrorTracking": "error_tracking",- # Unlike the PascalCase model-name scopes above, ticket comments are written with the literal- # "conversations_ticket" scope (see products/conversations). This must match that literal.+ # Unlike the PascalCase model-name scopes above, customer-facing ticket messages are written+ # with the literal "conversations_ticket" scope (see products/conversations), while internal+ # ticket discussions use the "Ticket" scope. Both are ticket-sourced."conversations_ticket": "ticket",+ "Ticket": "ticket",}SCOPE_TO_PATH_MAPPING: dict[str, str] = {@@ -35,8 +37,10 @@ SCOPE_TO_PATH_MAPPING: dict[str, str] = {"Dashboard": "/dashboard/{item_id}","Survey": "/surveys/{item_id}","Experiment": "/experiments/{item_id}",- # See note above: ticket comments use the "conversations_ticket" scope literal, not "Ticket".+ # See note above: customer-facing ticket messages use the "conversations_ticket" scope literal,+ # while internal ticket discussions use the "Ticket" scope. Both land on the ticket page."conversations_ticket": "/support/tickets/{item_id}",+ "Ticket": "/support/tickets/{item_id}",}diff --git a/posthog/test/activity_logging/test_activity_logging.py b/posthog/test/activity_logging/test_activity_logging.pyindex cd7062605b5d..849ae79bbf14 100644--- a/posthog/test/activity_logging/test_activity_logging.py+++ b/posthog/test/activity_logging/test_activity_logging.py@@ -239,6 +239,14 @@ class TestActivityLogVisibilityManager(BaseTest):("instance_setting_updated", "InstanceSetting", "updated", False, True),# AI-gateway top-ups are staff-only and must be hidden from non-staff viewers("ai_gateway_credit_added", "AIGatewayCredit", "credit_added", False, True),+ # Ticket comment rows reference support-ticket bodies (rows written before write-time+ # masking still hold plaintext) and must be hidden from non-staff viewers+ ("ticket_comment", "Ticket", "commented", False, True),+ ("ticket_task_comment", "Ticket", "created task", False, True),+ ("conversations_ticket_comment", "conversations_ticket", "commented", False, True),+ ("conversations_ticket_task_comment", "conversations_ticket", "created task", False, True),+ # Ticket lifecycle activities stay visible — only comment rows are hidden+ ("ticket_updated", "Ticket", "updated", False, False),# Non-User scopes are unaffected("feature_flag_created", "FeatureFlag", "created", False, False),("feature_flag_updated", "FeatureFlag", "updated", True, False),@@ -270,6 +278,9 @@ class TestActivityLogVisibilityManager(BaseTest):("instance_setting_updated_staff_bypass", "InstanceSetting", "updated", False, False),# Staff can also see AI-gateway top-ups (allow_staff=True)("ai_gateway_credit_added_staff_bypass", "AIGatewayCredit", "credit_added", False, False),+ # Staff can also see ticket comment rows (allow_staff=True)+ ("ticket_comment_staff_bypass", "Ticket", "commented", False, False),+ ("conversations_ticket_comment_staff_bypass", "conversations_ticket", "commented", False, False),# Non-User activities still not restricted for anyone("feature_flag_created", "FeatureFlag", "created", False, False),]@@ -320,6 +331,28 @@ class TestActivityLogVisibilityManager(BaseTest):staff = activity_visibility_manager.apply_to_queryset(queryset, is_staff=True)assert staff.filter(scope="AIGatewayCredit").exists()+ def test_queryset_excludes_ticket_comment_rows_for_non_staff(self) -> None:+ # Pin the API-facing exclusion path: ticket comment rows written before write-time masking+ # hold plaintext ticket bodies, so they must not come back through activity log endpoints.+ # Ticket lifecycle rows stay visible.+ ActivityLog.objects.create(+ team_id=self.team.id,+ scope="conversations_ticket",+ activity="commented",+ detail={"changes": [{"type": "Comment", "field": "content", "action": "created", "after": "plaintext"}]},+ )+ ActivityLog.objects.create(team_id=self.team.id, scope="Ticket", activity="commented")+ ActivityLog.objects.create(team_id=self.team.id, scope="Ticket", activity="updated")+ queryset = ActivityLog.objects.filter(team_id=self.team.id)++ non_staff = activity_visibility_manager.apply_to_queryset(queryset, is_staff=False)+ assert not non_staff.filter(scope="conversations_ticket", activity="commented").exists()+ assert not non_staff.filter(scope="Ticket", activity="commented").exists()+ assert non_staff.filter(scope="Ticket", activity="updated").exists()++ staff = activity_visibility_manager.apply_to_queryset(queryset, is_staff=True)+ assert staff.filter(scope="conversations_ticket", activity="commented").exists()+def test_queryset_includes_all_logs_for_staff(self) -> None:ActivityLog.objects.create(team_id=self.team.id, scope="User", activity="logged_in", was_impersonated=True)ActivityLog.objects.create(team_id=self.team.id, scope="User", activity="logged_out", was_impersonated=True)diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.tsindex 7f04a7fc1580..8be01b187d17 100644--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts@@ -1,8 +1,12 @@import { expectLogic } from 'kea-test-utils'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { tagsModel } from '~/models/tagsModel'import { initKeaTests } from '~/test/init'import type { CommentType } from '~/types'+import { ActivityScope } from '~/types'import type { TicketAssignee } from '../../components/Assignee'import type { Ticket, TicketStatus } from '../../types'@@ -684,3 +688,36 @@ describe('supportTicketSceneLogic private note editing', () => {expect(logic.values.draftContent).toEqual(draft)})})++describe('supportTicketSceneLogic sidePanelContext', () => {+ let logic: ReturnType<typeof supportTicketSceneLogic.build>++ beforeEach(() => {+ initKeaTests()+ logic = supportTicketSceneLogic({ id: 'new' })+ logic.mount()+ logic.actions.setTicket(makeTicket())+ })++ // Access control and discussions are separate consumers of the same selector key. Defining+ // one selector per concern silently drops all but the last, so assert they coexist.+ it('exposes access control and discussion context together', () => {+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.DISCUSSIONS_SLACK_SYNC]: true })++ expect(logic.values.sidePanelContext).toEqual({+ access_control_resource: 'ticket',+ access_control_resource_id: 'ticket-1',+ activity_scope: ActivityScope.TICKET,+ activity_item_id: 'ticket-1',+ })+ })++ it('keeps access control context when the discussions flag is off', () => {+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.DISCUSSIONS_SLACK_SYNC]: false })++ expect(logic.values.sidePanelContext).toEqual({+ access_control_resource: 'ticket',+ access_control_resource_id: 'ticket-1',+ })+ })+})diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.tsindex 7a3d95660bbc..bc46c3ca0b44 100644--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts@@ -18,8 +18,10 @@ import { beforeUnload, router } from 'kea-router'import { lemonToast } from '@posthog/lemon-ui'+import { FEATURE_FLAGS } from 'lib/constants'import { dayjs } from 'lib/dayjs'import { LemonDialog } from 'lib/lemon-ui/LemonDialog'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { getCurrentTeamId } from 'lib/utils/getAppContext'import { isUUIDLike } from 'lib/utils/guards'import { markdownToHtml } from 'lib/utils/markdown'@@ -36,7 +38,7 @@ 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 { PropertyFilterType, PropertyOperator, Region } from '~/types'+import { ActivityScope, PropertyFilterType, PropertyOperator, Region } from '~/types'import {businessKnowledgeGapSuggestionsDismissCreate,@@ -49,6 +51,7 @@ import {import { signalsReportsList } from 'products/signals/frontend/generated/api'import type { SignalReportApi } from 'products/signals/frontend/generated/api.schemas'+import type { FeatureFlagsSet } from '../../../../../frontend/src/lib/logic/featureFlagLogic'import type { TeamPublicType, TeamType } from '../../../../../frontend/src/types'import { assigneeSelectLogic } from '../../components/Assignee'import type { Assignee, TicketAssignee } from '../../components/Assignee'@@ -179,6 +182,7 @@ export function getEmailReplyBlockedReason(export interface supportTicketSceneLogicValues {resolveAssignee: (assignee: TicketAssignee) => Assignee // assigneeSelectLogicdraftModeDefault: boolean // conversationsDraftModeLogic+ featureFlags: FeatureFlagsSet // featureFlagLogicavailableTags: string[] // tagsModelcurrentTeam: TeamPublicType | TeamType | null // teamLogicassignee: TicketAssignee@@ -446,6 +450,7 @@ export interface supportTicketSceneLogicMeta {ticket: Ticket | null,currentTeam: TeamPublicType | TeamType | null) => EmailReplyBlockedReason | null+ sidePanelContext: (ticket: Ticket | null, featureFlags: FeatureFlagsSet) => SidePanelSceneContext | nullreplyRecipientDescription: (ticket: Ticket | null) => stringunsavedTicketChanges: (priority: TicketPriority | null,@@ -465,7 +470,6 @@ export interface supportTicketSceneLogicMeta {eventsQuery: (ticket: Ticket | null) => DataTableNode | nullexceptionsQuery: (ticket: Ticket | null) => DataTableNode | nulllatestAiMessage: (chatMessages: ChatMessage[]) => ChatMessage | null- sidePanelContext: (ticket: Ticket | null) => SidePanelSceneContext | null}}@@ -485,6 +489,8 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([values: [teamLogic,['currentTeam'],+ featureFlagLogic,+ ['featureFlags'],conversationsDraftModeLogic,['draftModeDefault'],assigneeSelectLogic,@@ -847,6 +853,25 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([): EmailReplyBlockedReason | null =>getEmailReplyBlockedReason(ticket, currentTeam?.conversations_settings),],+ [SIDE_PANEL_CONTEXT_KEY]: [+ (s) => [s.ticket, s.featureFlags],+ (ticket: Ticket | null, featureFlags: FeatureFlagsSet): SidePanelSceneContext | null =>+ ticket?.id+ ? {+ access_control_resource: 'ticket',+ access_control_resource_id: `${ticket.id}`,+ // Scoping the discussion thread to the ticket is still flag-gated; the+ // access control fields above are not, so the panel stays gated on+ // ticket access either way.+ ...(featureFlags[FEATURE_FLAGS.DISCUSSIONS_SLACK_SYNC]+ ? {+ activity_scope: ActivityScope.TICKET,+ activity_item_id: `${ticket.id}`,+ }+ : {}),+ }+ : null,+ ],replyRecipientDescription: [(s) => [s.ticket],(ticket: Ticket | null): string => {@@ -1024,17 +1049,6 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([return null},],- [SIDE_PANEL_CONTEXT_KEY]: [- (s) => [s.ticket],- (ticket: Ticket | null): SidePanelSceneContext | null => {- return ticket?.id- ? {- access_control_resource: 'ticket',- access_control_resource_id: `${ticket.id}`,- }- : null- },- ],}),listeners(({ actions, values, props, cache }) => ({loadTicket: async () => {diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.tsindex 1aa6b279f022..2fcc77ae80f1 100644--- a/products/platform_features/frontend/generated/api.schemas.ts+++ b/products/platform_features/frontend/generated/api.schemas.ts@@ -1425,7 +1425,7 @@ export type CommentsListParams = {*/kind?: CommentsListKind/**- * Filter by resource type (e.g. Dashboard, FeatureFlag, Insight, Replay).+ * Filter by resource type (e.g. Dashboard, FeatureFlag, Insight, Replay). Support-ticket scopes (Ticket, conversations_ticket) additionally require ticket API scope access.* @minLength 1*/scope?: stringdiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex fcc245905358..f58ec5cd9dd1 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -78715,7 +78715,7 @@ export namespace Schemas {*/kind?: CommentsListKind;/**- * Filter by resource type (e.g. Dashboard, FeatureFlag, Insight, Replay).+ * Filter by resource type (e.g. Dashboard, FeatureFlag, Insight, Replay). Support-ticket scopes (Ticket, conversations_ticket) additionally require ticket API scope access.* @minLength 1*/scope?: string;diff --git a/services/mcp/src/generated/platform_features/api.ts b/services/mcp/src/generated/platform_features/api.tsindex b3f424866e6a..ba43bdb76b71 100644--- a/services/mcp/src/generated/platform_features/api.ts+++ b/services/mcp/src/generated/platform_features/api.ts@@ -359,7 +359,9 @@ export const CommentsListQueryParams = /* @__PURE__ */ zod.object({.string().min(1).optional()- .describe('Filter by resource type (e.g. Dashboard, FeatureFlag, Insight, Replay).'),+ .describe(+ 'Filter by resource type (e.g. Dashboard, FeatureFlag, Insight, Replay). Support-ticket scopes (Ticket, conversations_ticket) additionally require ticket API scope access.'+ ),search: zod.string().min(1).optional().describe('Full-text search within comment content.'),source_comment: zod.string().min(1).optional().describe('Filter replies to a specific parent comment.'),})diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/comments-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/comments-list.jsonindex d98c52cbf8b3..bd4dba4941e4 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/comments-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/comments-list.json@@ -21,7 +21,7 @@"type": "string"},"scope": {- "description": "Filter by resource type (e.g. Dashboard, FeatureFlag, Insight, Replay).",+ "description": "Filter by resource type (e.g. Dashboard, FeatureFlag, Insight, Replay). Support-ticket scopes (Ticket, conversations_ticket) additionally require ticket API scope access.","minLength": 1,"type": "string"},