:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(conversations): add a create-only private ticket note endpoint (#104698)
posthog[bot]9a06e1e4bb9c
diff --git a/posthog/rate_limit.py b/posthog/rate_limit.pyindex c92c78cb7b05..b2c6056d1c69 100644--- a/posthog/rate_limit.py+++ b/posthog/rate_limit.py@@ -1940,6 +1940,21 @@ class ComposeTicketSustainedThrottle(UserRateThrottle):rate = "60/hour"+class TicketNoteBurstThrottle(UserRateThrottle):+ """+ Private notes get their own bucket, so an agent writing notes cannot use up the compose+ budget that the same user needs for customer replies.+ """++ scope = "ticket_note_burst"+ rate = "10/minute"+++class TicketNoteSustainedThrottle(UserRateThrottle):+ scope = "ticket_note_sustained"+ rate = "60/hour"++class TeamsAdminGraphThrottle(UserRateThrottle):"""Protect the bot's per-tenant Graph API quota. The TeamsTeamsView /diff --git a/products/conversations/backend/api/tests/test_tickets.py b/products/conversations/backend/api/tests/test_tickets.pyindex ecf6ee8a04ef..ca8a57d1c78c 100644--- a/products/conversations/backend/api/tests/test_tickets.py+++ b/products/conversations/backend/api/tests/test_tickets.py@@ -2581,6 +2581,8 @@ class TestTicketPersonalAPIKeyScopes(APIBaseTest):("delete_note_with_write", "delete", ["ticket:write"], status.HTTP_204_NO_CONTENT),("delete_note_with_read_only", "delete", ["ticket:read"], status.HTTP_403_FORBIDDEN),("delete_note_wrong_scope", "delete", ["insight:write"], status.HTTP_403_FORBIDDEN),+ ("create_note_with_write", "post", ["ticket:write"], status.HTTP_201_CREATED),+ ("create_note_with_read_only", "post", ["ticket:read"], status.HTTP_403_FORBIDDEN),])def test_note_scopes(self, _name, method, scopes, expected_status):@@ -2594,7 +2596,15 @@ class TestTicketPersonalAPIKeyScopes(APIBaseTest):)self._auth_with_pak(scopes)url = f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/notes/{note.id}/"- if method == "patch":+ if method == "post":+ self.team.conversations_enabled = True+ self.team.save(update_fields=["conversations_enabled"])+ response = self.client.post(+ f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/notes/",+ {"message": "New note"},+ format="json",+ )+ elif method == "patch":response = self.client.patch(url, {"message": "Updated note"}, format="json")else:response = self.client.delete(url)@@ -3053,13 +3063,14 @@ class TestTicketReplyAPI(APIBaseTest):@parameterized.expand([- ("public_reply_is_emailed", False, True),- ("private_note_is_not_emailed", True, False),+ ("public_reply_is_emailed", "reply", {"is_private": False}, True),+ ("private_note_is_not_emailed", "reply", {"is_private": True}, False),+ ("note_endpoint_ignores_is_private", "notes", {"is_private": False}, False),])@patch("products.conversations.backend.signals.send_email_reply")def test_reply_fans_out_to_customer_only_when_public(- self, _name, is_private, expect_delivery, mock_send_email_reply, mock_on_commit+ self, _name, path, extra, expect_delivery, mock_send_email_reply, mock_on_commit):# The post_save signal only delivers over email when the ticket is an# email channel with email enabled and a sender address.@@ -3068,8 +3079,10 @@ class TestTicketReplyAPI(APIBaseTest):self.team.conversations_settings = {"email_enabled": True}self.team.save(update_fields=["conversations_settings"])- response = self.client.post(self.url, {"message": "Reply body", "is_private": is_private}, format="json")+ url = f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/{path}/"+ response = self.client.post(url, {"message": "Reply body", **extra}, format="json")assert response.status_code == status.HTTP_201_CREATED+ assert response.json()["is_private"] is not expect_deliveryif expect_delivery:mock_send_email_reply.delay.assert_called_once()diff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.pyindex 6e324afa3dbd..b236bb57e65d 100644--- a/products/conversations/backend/api/tickets.py+++ b/products/conversations/backend/api/tickets.py@@ -54,7 +54,12 @@ from posthog.models.person.person import Personfrom posthog.models.person.util import get_person_by_distinct_id, get_persons_by_distinct_idsfrom posthog.permissions import APIScopePermissionfrom posthog.personhog_client.caller_tag import personhog_caller_tag-from posthog.rate_limit import ComposeTicketBurstThrottle, ComposeTicketSustainedThrottle+from posthog.rate_limit import (+ ComposeTicketBurstThrottle,+ ComposeTicketSustainedThrottle,+ TicketNoteBurstThrottle,+ TicketNoteSustainedThrottle,+)from products.access_control.backend.models.role import Rolefrom products.access_control.backend.presentation.access_control import (@@ -182,6 +187,20 @@ class TicketNoteUpdateRequestSerializer(serializers.Serializer):return value+class TicketNoteCreateRequestSerializer(TicketNoteUpdateRequestSerializer):+ """Payload for adding a private note to a ticket. It has no privacy field: the note is always private."""++ message = serializers.CharField(+ max_length=5000,+ help_text="Note content in markdown. The note is visible to your team only and is never sent to the customer.",+ )+ rich_content = serializers.JSONField(+ required=False,+ allow_null=True,+ help_text="Optional TipTap rich content JSON for the note. Omit it to show the markdown message.",+ )++class TicketReplyRequestSerializer(serializers.Serializer):"""Payload for posting a reply or internal note to a ticket."""@@ -725,6 +744,7 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessContro"ai_human_outcome","note","delete_note",+ "create_note",]queryset = Ticket.objects.all()serializer_class = TicketSerializer@@ -1581,19 +1601,27 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessControserializer = TicketReplyRequestSerializer(data=request.data)serializer.is_valid(raise_exception=True)data = serializer.validated_data+ return self._create_message(+ ticket,+ message=data["message"],+ rich_content=data.get("rich_content"),+ is_private=data["is_private"],+ )- item_context = {"author_type": "support", "is_private": data["is_private"]}+ def _create_message(self, ticket: Ticket, *, message: str, rich_content: object, is_private: bool) -> Response:+ request = self.request+ item_context = {"author_type": "support", "is_private": is_private}def create_comment() -> Comment:# ATOMIC_REQUESTS is off, so wrap the comment insert with the email-outbox write.with transaction.atomic():return Comment.objects.create(team=self.team,- created_by=request.user,+ created_by=cast("User", request.user),scope="conversations_ticket",item_id=str(ticket.id),- content=data["message"],- rich_content=data.get("rich_content"),+ content=message,+ rich_content=rich_content,item_context=item_context,)@@ -1602,8 +1630,8 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessControcreated_by_id=request.user.id,scope="conversations_ticket",item_id=str(ticket.id),- content=data["message"],- rich_content=data.get("rich_content"),+ content=message,+ rich_content=rich_content,item_context=item_context,)if fingerprint is None:@@ -1628,6 +1656,56 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessControstatus=drf_status.HTTP_201_CREATED if created else drf_status.HTTP_200_OK,)+ @extend_schema(+ parameters=[TICKET_ID_PARAM],+ request=TicketNoteCreateRequestSerializer,+ responses={+ 200: OpenApiResponse(+ response=TicketMessageSerializer,+ description=(+ "An identical note was already posted by a recent request. The original "+ "note is returned and nothing new is written."+ ),+ ),+ 201: OpenApiResponse(response=TicketMessageSerializer),+ 400: OpenApiResponse(response=TicketErrorSerializer),+ 409: OpenApiResponse(+ response=TicketErrorSerializer,+ description="An identical note is still being created by another request.",+ ),+ },+ )+ @action(+ detail=True,+ methods=["post"],+ url_path="notes",+ pagination_class=None,+ throttle_classes=[TicketNoteBurstThrottle, TicketNoteSustainedThrottle],+ )+ def create_note(self, request, *args, **kwargs):+ """Add a private note to a ticket.++ The note is visible to your team only. The request has no privacy field, so this+ endpoint never sends anything to the customer.+ """+ ticket = self.get_object()++ if not self.team.conversations_enabled:+ return Response(+ {"detail": "Support is not enabled."},+ status=drf_status.HTTP_400_BAD_REQUEST,+ )++ serializer = TicketNoteCreateRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ data = serializer.validated_data+ return self._create_message(+ ticket,+ message=data["message"],+ rich_content=data.get("rich_content"),+ is_private=True,+ )+@extend_schema(parameters=[TICKET_ID_PARAM, NOTE_MESSAGE_ID_PARAM],request=TicketNoteUpdateRequestSerializer,diff --git a/products/conversations/frontend/generated/api.schemas.ts b/products/conversations/frontend/generated/api.schemas.tsindex 717a6b6be136..979d4e4308b3 100644--- a/products/conversations/frontend/generated/api.schemas.ts+++ b/products/conversations/frontend/generated/api.schemas.ts@@ -502,6 +502,19 @@ export interface TicketFullEmailApi {readonly content: string}+/**+ * Payload for adding a private note to a ticket. It has no privacy field: the note is always private.+ */+export interface TicketNoteCreateRequestApi {+ /**+ * Note content in markdown. The note is visible to your team only and is never sent to the customer.+ * @maxLength 5000+ */+ message: string+ /** Optional TipTap rich content JSON for the note. Omit it to show the markdown message. */+ rich_content?: unknown+}+/*** Payload for updating a private note on a ticket.*/diff --git a/products/conversations/frontend/generated/api.ts b/products/conversations/frontend/generated/api.tsindex 48e3f7989aab..075c743e2dfa 100644--- a/products/conversations/frontend/generated/api.ts+++ b/products/conversations/frontend/generated/api.ts@@ -31,6 +31,7 @@ import type {TicketApi,TicketFullEmailApi,TicketMessageApi,+ TicketNoteCreateRequestApi,TicketReplyRequestApi,TicketUnreadCountResponseApi,TicketUpdateRequestApi,@@ -295,6 +296,30 @@ export const conversationsTicketsMessagesFullEmailRetrieve = async ()}+export const getConversationsTicketsNotesCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/conversations/tickets/${id}/notes/`+}++/**+ * Add a private note to a ticket.+ *+ * The note is visible to your team only. The request has no privacy field, so this+ * endpoint never sends anything to the customer.+ */+export const conversationsTicketsNotesCreate = async (+ projectId: string,+ id: string,+ ticketNoteCreateRequestApi: TicketNoteCreateRequestApi,+ options?: RequestInit+): Promise<TicketMessageApi> => {+ return apiMutator<TicketMessageApi>(getConversationsTicketsNotesCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(ticketNoteCreateRequestApi),+ })+}+export const getConversationsTicketsNotesPartialUpdateUrl = (projectId: string, id: string, messageId: string) => {return `/api/projects/${projectId}/conversations/tickets/${id}/notes/${messageId}/`}diff --git a/products/conversations/frontend/generated/api.zod.ts b/products/conversations/frontend/generated/api.zod.tsindex 2b7f5b02ed10..4affac43689a 100644--- a/products/conversations/frontend/generated/api.zod.ts+++ b/products/conversations/frontend/generated/api.zod.ts@@ -159,6 +159,29 @@ export const ConversationsTicketsAiHumanOutcomeCreateBody = /* @__PURE__ */ zod}).describe('Payload for recording whether a human adopted an AI draft.')+/**+ * Add a private note to a ticket.+ *+ * The note is visible to your team only. The request has no privacy field, so this+ * endpoint never sends anything to the customer.+ */+export const conversationsTicketsNotesCreateBodyMessageMax = 5000++export const ConversationsTicketsNotesCreateBody = /* @__PURE__ */ zod+ .object({+ message: zod+ .string()+ .max(conversationsTicketsNotesCreateBodyMessageMax)+ .describe(+ 'Note content in markdown. The note is visible to your team only and is never sent to the customer.'+ ),+ rich_content: zod+ .unknown()+ .optional()+ .describe('Optional TipTap rich content JSON for the note. Omit it to show the markdown message.'),+ })+ .describe('Payload for adding a private note to a ticket. It has no privacy field: the note is always private.')+/*** Update a private note on a ticket.*diff --git a/products/conversations/mcp/tools.yaml b/products/conversations/mcp/tools.yamlindex 87936511a8e7..fd315581996b 100644--- a/products/conversations/mcp/tools.yaml+++ b/products/conversations/mcp/tools.yaml@@ -88,6 +88,22 @@ tools:from the response envelope. Includes all messages from the customer, team members, and AI, as well asprivate internal notes. Each message contains author_type, author_name, content, and an is_private flagindicating internal notes.+ conversations-tickets-notes-create:+ operation: conversations_tickets_notes_create+ enabled: false+ scopes:+ - ticket:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Add private note to support ticket+ description: >+ Add a private note to a support ticket. The note is visible to your team only and is never sent to the+ customer; this tool has no privacy option. Use it to leave findings where the support engineer works. To+ reply to the customer, use conversations-tickets-reply-create instead. To change a note later, use+ conversations-tickets-notes-partial-update. An identical note posted again within a short window returns the+ original note instead of adding a second one. Returns the note as it appears in the thread.conversations-tickets-notes-destroy:operation: conversations_tickets_notes_destroyenabled: truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 4f0c82a0c38c..2d0103d68273 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -99762,6 +99762,19 @@ export namespace Schemas {readonly content: string;}+ /**+ * Payload for adding a private note to a ticket. It has no privacy field: the note is always private.+ */+ export interface TicketNoteCreateRequest {+ /**+ * Note content in markdown. The note is visible to your team only and is never sent to the customer.+ * @maxLength 5000+ */+ message: string;+ /** Optional TipTap rich content JSON for the note. Omit it to show the markdown message. */+ rich_content?: unknown;+ }+/*** Payload for posting a reply or internal note to a ticket.*/