: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): allow editing and deleting own private notes (#77752)
Alex V5861fb1667a9
diff --git a/frontend/src/lib/components/RichContentEditor/types.ts b/frontend/src/lib/components/RichContentEditor/types.tsindex 3af2530d5ace..f19161665099 100644--- a/frontend/src/lib/components/RichContentEditor/types.ts+++ b/frontend/src/lib/components/RichContentEditor/types.ts@@ -35,7 +35,7 @@ export interface RichContentEditorType {getCurrentPosition: () => numbergetAdjacentNodes: (pos: number) => { previous: RichContentNode | null; next: RichContentNode | null }setEditable: (editable: boolean) => void- setContent: (content: JSONContent) => void+ setContent: (content: JSONContent | string) => voidsetSelection: (position: number) => voidsetTextSelection: (position: number | EditorRange) => voidfocus: (position?: EditorFocusPosition) => voiddiff --git a/frontend/src/lib/components/RichContentEditor/utils.ts b/frontend/src/lib/components/RichContentEditor/utils.tsindex df142c552820..3e816b1564cf 100644--- a/frontend/src/lib/components/RichContentEditor/utils.ts+++ b/frontend/src/lib/components/RichContentEditor/utils.ts@@ -19,7 +19,7 @@ export function createEditor(editor: TTEditor): RichContentEditorType {getCurrentPosition: () => editor.state.selection.$anchor.pos,getAdjacentNodes: (pos: number) => getAdjacentNodes(editor, pos),setEditable: (editable: boolean) => queueMicrotask(() => editor.setEditable(editable, false)),- setContent: (content: JSONContent) =>+ setContent: (content: JSONContent | string) =>queueMicrotask(() => editor.commands.setContent(content, { emitUpdate: false })),setSelection: (position: number) => editor.commands.setNodeSelection(position),setTextSelection: (position: number | EditorRange) =>diff --git a/frontend/src/lib/utils/markdown.ts b/frontend/src/lib/utils/markdown.tsindex 71f82bd759b7..15c3bfd96430 100644--- a/frontend/src/lib/utils/markdown.ts+++ b/frontend/src/lib/utils/markdown.ts@@ -3,6 +3,14 @@ import { MarkdownManager } from '@tiptap/markdown'import { Extensions } from '@tiptap/react'import { marked } from 'marked'+/**+ * Convert markdown to HTML for TipTap's setContent / HTML parser.+ * Prefer createTiptapMarkdownConverter when you need TipTap JSON instead.+ */+export function markdownToHtml(markdown: string): string {+ return marked.parse(markdown, { async: false }) as string+}+const TABLE_DELIMITER_SEGMENT_RE = /^\|(?:\s*:?-{2,}:?\s*\|)+\s*$/// Matches the boundary between two flattened rows: a closing `|` directly followed by the// next row's opening `|`. The whitespace is optional because some sources (e.g. AI chatdiff --git a/posthog/api/comments.py b/posthog/api/comments.pyindex 29de65754804..529e14ff1739 100644--- a/posthog/api/comments.py+++ b/posthog/api/comments.py@@ -213,8 +213,9 @@ class CommentSerializer(serializers.ModelSerializer):locked_instance = Comment.objects.select_for_update().get(pk=instance.pk)if locked_instance.created_by != request.user:- raise+ raise exceptions.PermissionDenied("You can only modify your own comments")+ updated_instance = locked_instanceif validated_data.keys():if validated_data.get("content"):validated_data["version"] = locked_instance.version + 1diff --git a/products/conversations/backend/api/tests/test_tickets.py b/products/conversations/backend/api/tests/test_tickets.pyindex ebcc055c8b56..04f650686a6d 100644--- a/products/conversations/backend/api/tests/test_tickets.py+++ b/products/conversations/backend/api/tests/test_tickets.py@@ -2009,6 +2009,33 @@ class TestTicketPersonalAPIKeyScopes(APIBaseTest):response = getattr(self.client, method)(url)assert response.status_code == expected_status, f"{_name}: {response.status_code} != {expected_status}"+ @parameterized.expand(+ [+ ("note_with_write", "patch", ["ticket:write"], status.HTTP_200_OK),+ ("note_with_read_only", "patch", ["ticket:read"], status.HTTP_403_FORBIDDEN),+ ("note_wrong_scope", "patch", ["insight:write"], status.HTTP_403_FORBIDDEN),+ ("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),+ ]+ )+ def test_note_scopes(self, _name, method, scopes, expected_status):+ note = Comment.objects.create(+ team=self.team,+ created_by=self.user,+ scope="conversations_ticket",+ item_id=str(self.ticket.id),+ content="Original note",+ item_context={"author_type": "support", "is_private": True},+ )+ self._auth_with_pak(scopes)+ url = f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/notes/{note.id}/"+ if method == "patch":+ response = self.client.patch(url, {"message": "Updated note"}, format="json")+ else:+ response = self.client.delete(url)+ assert response.status_code == expected_status, f"{_name}: {response.status_code} != {expected_status}"+@patch.object(transaction, "on_commit", side_effect=immediate_on_commit)class TestTicketMessagesAPI(APIBaseTest):@@ -2118,6 +2145,7 @@ class TestTicketMessagesAPI(APIBaseTest):"author_name","is_private","created_at",+ "version",}def test_messages_lookup_by_ticket_number(self, mock_on_commit):@@ -2768,3 +2796,149 @@ class TestTicketViewParamFilter(APIBaseTest):response = self.client.get(f"/api/projects/{self.team.id}/conversations/tickets/", data={"view": view.short_id})assert response.status_code == status.HTTP_200_OKassert [r["id"] for r in response.json()["results"]] == [str(first.id), str(second.id)]++[email protected](transaction, "on_commit", side_effect=immediate_on_commit)+class TestTicketNoteAPI(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.team.conversations_enabled = True+ self.team.save()+ self.ticket = Ticket.objects.create_with_number(+ team=self.team,+ channel_source=Channel.WIDGET,+ widget_session_id="note-session",+ distinct_id="user-1",+ status=Status.OPEN,+ )+ self.note = Comment.objects.create(+ team=self.team,+ created_by=self.user,+ scope="conversations_ticket",+ item_id=str(self.ticket.id),+ content="Original private note",+ rich_content={+ "type": "doc",+ "content": [{"type": "paragraph", "content": [{"type": "text", "text": "Original private note"}]}],+ },+ item_context={"author_type": "support", "is_private": True},+ )+ self.url = f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/notes/{self.note.id}/"++ def test_patch_updates_content_and_bumps_version(self, mock_on_commit):+ response = self.client.patch(+ self.url,+ {"message": "Updated note", "rich_content": {"type": "doc", "content": []}},+ format="json",+ )+ assert response.status_code == status.HTTP_200_OK+ body = response.json()+ assert body["content"] == "Updated note"+ assert body["is_private"] is True+ assert body["version"] == 1++ self.note.refresh_from_db()+ assert self.note.content == "Updated note"+ assert self.note.version == 1++ def test_patch_message_only_clears_stale_rich_content(self, mock_on_commit):+ response = self.client.patch(self.url, {"message": "Markdown-only update"}, format="json")+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["content"] == "Markdown-only update"+ assert response.json()["rich_content"] is None++ self.note.refresh_from_db()+ assert self.note.content == "Markdown-only update"+ assert self.note.rich_content is None++ def test_delete_soft_deletes_and_hides_from_messages(self, mock_on_commit):+ response = self.client.delete(self.url)+ assert response.status_code == status.HTTP_204_NO_CONTENT++ self.note.refresh_from_db()+ assert self.note.deleted is True++ messages = self.client.get(f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/messages/")+ assert messages.status_code == status.HTTP_200_OK+ assert all(m["id"] != str(self.note.id) for m in messages.json()["results"])++ @parameterized.expand(+ [+ ("other_user_author", "other_user", True, status.HTTP_403_FORBIDDEN, "not_note_author"),+ ("ai_note_no_author", "ai", True, status.HTTP_403_FORBIDDEN, "not_note_author"),+ ("public_reply", "self", False, status.HTTP_400_BAD_REQUEST, "not_private_note"),+ ("other_ticket", "other_ticket", True, status.HTTP_404_NOT_FOUND, "note_not_found"),+ ("already_deleted", "deleted", True, status.HTTP_404_NOT_FOUND, "note_not_found"),+ ("invalid_uuid", "invalid_id", True, status.HTTP_404_NOT_FOUND, "note_not_found"),+ ]+ )+ def test_guard_matrix(self, mock_on_commit, _name, setup_kind, is_private, expected_status, expected_error):+ if setup_kind == "other_user":+ other = User.objects.create_and_join(self.organization, "[email protected]", "pass")+ note = Comment.objects.create(+ team=self.team,+ created_by=other,+ scope="conversations_ticket",+ item_id=str(self.ticket.id),+ content="Someone else's note",+ item_context={"author_type": "support", "is_private": True},+ )+ url = f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/notes/{note.id}/"+ elif setup_kind == "ai":+ note = Comment.objects.create(+ team=self.team,+ created_by=None,+ scope="conversations_ticket",+ item_id=str(self.ticket.id),+ content="AI note",+ item_context={"author_type": "AI", "is_private": True},+ )+ url = f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/notes/{note.id}/"+ elif setup_kind == "self":+ note = Comment.objects.create(+ team=self.team,+ created_by=self.user,+ scope="conversations_ticket",+ item_id=str(self.ticket.id),+ content="Public reply",+ item_context={"author_type": "support", "is_private": is_private},+ )+ url = f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/notes/{note.id}/"+ elif setup_kind == "other_ticket":+ other_ticket = Ticket.objects.create_with_number(+ team=self.team,+ channel_source=Channel.WIDGET,+ widget_session_id="other-note-session",+ distinct_id="user-2",+ status=Status.OPEN,+ )+ url = f"/api/projects/{self.team.id}/conversations/tickets/{other_ticket.id}/notes/{self.note.id}/"+ elif setup_kind == "deleted":+ self.note.deleted = True+ self.note.save(update_fields=["deleted"])+ url = self.url+ else:+ url = f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/notes/not-a-uuid/"++ response = self.client.patch(url, {"message": "Hacked"}, format="json")+ assert response.status_code == expected_status+ body = response.json()+ assert body["error_type"] == expected_error+ if expected_error == "not_note_author":+ assert "You can only edit your own private notes." == body["detail"]+ elif expected_error == "not_private_note":+ assert "Only private notes can be edited." == body["detail"]++ # DELETE must produce the same error shape (with delete verbs).+ response = self.client.delete(url)+ assert response.status_code == expected_status+ body = response.json()+ assert body["error_type"] == expected_error+ if expected_error == "not_note_author":+ assert "You can only delete your own private notes." == body["detail"]+ elif expected_error == "not_private_note":+ assert "Only private notes can be deleted." == body["detail"]++ def test_blank_message_rejected(self, mock_on_commit):+ response = self.client.patch(self.url, {"message": " "}, format="json")+ assert response.status_code == status.HTTP_400_BAD_REQUESTdiff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.pyindex 6ee43fc96a7c..7808ca3b8988 100644--- a/products/conversations/backend/api/tickets.py+++ b/products/conversations/backend/api/tickets.py@@ -89,9 +89,43 @@ class TicketMessageSerializer(serializers.Serializer):is_private = serializers.BooleanField(read_only=True, help_text="True for internal notes not visible to the customer.")+ version = serializers.IntegerField(read_only=True, help_text="Edit count. 0 means never edited.")created_at = serializers.DateTimeField(read_only=True)+class TicketNoteUpdateRequestSerializer(serializers.Serializer):+ """Payload for updating a private note on a ticket."""++ message = serializers.CharField(+ max_length=5000,+ help_text="Updated note content in markdown.",+ )+ rich_content = serializers.JSONField(+ required=False,+ allow_null=True,+ help_text=(+ "Optional TipTap rich content JSON. Omit or pass null to clear previous rich content "+ "so the thread falls back to the markdown message."+ ),+ )++ def validate_message(self, value: str) -> str:+ if not value or not value.strip():+ raise serializers.ValidationError("Message content is required.")+ return value.strip()++ def validate_rich_content(self, value: object) -> object:+ if value is None:+ return value+ try:+ serialized = json.dumps(value)+ except (TypeError, ValueError) as e:+ raise serializers.ValidationError("Rich content must be JSON-serializable.") from e+ if len(serialized) > 100_000:+ raise serializers.ValidationError("Rich content too large (max 100KB).")+ return value++class TicketReplyRequestSerializer(serializers.Serializer):"""Payload for posting a reply or internal note to a ticket."""@@ -358,6 +392,13 @@ TICKET_ID_PARAM = OpenApiParameter(description="The ticket's UUID or its numeric ticket number.",)+NOTE_MESSAGE_ID_PARAM = OpenApiParameter(+ name="message_id",+ type=OpenApiTypes.UUID,+ location=OpenApiParameter.PATH,+ description="The UUID of the private note (comment) to edit or delete.",+)+@extend_schema_view(retrieve=extend_schema(parameters=[TICKET_ID_PARAM]),@@ -370,7 +411,17 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessControscope_object_read_actions = ["list", "retrieve", "unread_count", "messages"]# "create" stays listed so a ticket:write token reaches the create() override below and# gets a clear 405 (pointing to the SDK), rather than a misleading "not supported" 403.- scope_object_write_actions = ["create", "update", "partial_update", "patch", "compose", "reply", "ai_feedback"]+ scope_object_write_actions = [+ "create",+ "update",+ "partial_update",+ "patch",+ "compose",+ "reply",+ "ai_feedback",+ "note",+ "delete_note",+ ]queryset = Ticket.objects.all()serializer_class = TicketSerializerpermission_classes = [IsAuthenticated, APIScopePermission]@@ -1094,9 +1145,59 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessContro"author_type": author_type,"author_name": author_name,"is_private": item_context.get("is_private") is True,+ "version": comment.version,"created_at": comment.created_at,}+ def _get_editable_private_note(+ self, ticket: Ticket, message_id: str, *, action: str+ ) -> tuple[Comment | None, Response | None]:+ """Look up a private note the caller may edit/delete, or return an error response.++ `action` is the present-tense verb ("edit" / "delete") used in author-facing errors.+ """+ action_participle = {"edit": "edited", "delete": "deleted"}[action]++ try:+ uuid.UUID(str(message_id))+ except (ValueError, TypeError, AttributeError):+ return None, Response(+ {"detail": "Note not found.", "error_type": "note_not_found"},+ status=drf_status.HTTP_404_NOT_FOUND,+ )++ try:+ comment = Comment.objects.get(+ id=message_id,+ team_id=self.team_id,+ scope="conversations_ticket",+ item_id=str(ticket.id),+ deleted=False,+ )+ except Comment.DoesNotExist:+ return None, Response(+ {"detail": "Note not found.", "error_type": "note_not_found"},+ status=drf_status.HTTP_404_NOT_FOUND,+ )++ item_context = comment.item_context or {}+ if item_context.get("is_private") is not True:+ return None, Response(+ {"detail": f"Only private notes can be {action_participle}.", "error_type": "not_private_note"},+ status=drf_status.HTTP_400_BAD_REQUEST,+ )++ if comment.created_by_id != self.request.user.id:+ return None, Response(+ {+ "detail": f"You can only {action} your own private notes.",+ "error_type": "not_note_author",+ },+ status=drf_status.HTTP_403_FORBIDDEN,+ )++ return comment, None+@extend_schema(parameters=[TICKET_ID_PARAM],request=TicketReplyRequestSerializer,@@ -1146,6 +1247,104 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessControstatus=drf_status.HTTP_201_CREATED,)+ @extend_schema(+ parameters=[TICKET_ID_PARAM, NOTE_MESSAGE_ID_PARAM],+ request=TicketNoteUpdateRequestSerializer,+ responses={+ 200: OpenApiResponse(response=TicketMessageSerializer),+ 400: OpenApiResponse(response=TicketErrorSerializer),+ 403: OpenApiResponse(response=TicketErrorSerializer),+ 404: OpenApiResponse(response=TicketErrorSerializer),+ },+ )+ @action(+ detail=True,+ methods=["patch"],+ url_path=r"notes/(?P<message_id>[^/.]+)",+ pagination_class=None,+ )+ def note(self, request, message_id: str | None = None, *args, **kwargs):+ """Update a private note on a ticket.++ Only the note's author can edit it. Customer-facing replies cannot be+ edited (outbound delivery only runs on create).+ """+ ticket = self.get_object()+ comment, error = self._get_editable_private_note(ticket, message_id or "", action="edit")+ if error is not None:+ return error+ assert comment is not None++ serializer = TicketNoteUpdateRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ data = serializer.validated_data++ with transaction.atomic():+ locked = Comment.objects.select_for_update().get(pk=comment.pk)+ if locked.deleted:+ return Response(+ {"detail": "Note not found.", "error_type": "note_not_found"},+ status=drf_status.HTTP_404_NOT_FOUND,+ )+ if locked.created_by_id != request.user.id:+ return Response(+ {+ "detail": "You can only edit your own private notes.",+ "error_type": "not_note_author",+ },+ status=drf_status.HTTP_403_FORBIDDEN,+ )+ locked.content = data["message"]+ # Always write rich_content: omitting it clears stale TipTap JSON so markdown-only+ # MCP/API edits don't keep rendering the previous note body.+ locked.rich_content = data.get("rich_content")+ locked.version = locked.version + 1+ locked.save(update_fields=["content", "rich_content", "version"])++ return Response(TicketMessageSerializer(self._serialize_message(locked, ticket)).data)++ @extend_schema(+ parameters=[TICKET_ID_PARAM, NOTE_MESSAGE_ID_PARAM],+ responses={+ 204: OpenApiResponse(description="Note soft-deleted."),+ 400: OpenApiResponse(response=TicketErrorSerializer),+ 403: OpenApiResponse(response=TicketErrorSerializer),+ 404: OpenApiResponse(response=TicketErrorSerializer),+ },+ )+ @note.mapping.delete+ def delete_note(self, request, message_id: str | None = None, *args, **kwargs):+ """Soft-delete a private note on a ticket.++ Only the note's author can delete it. Customer-facing replies cannot be+ deleted via this endpoint.+ """+ ticket = self.get_object()+ comment, error = self._get_editable_private_note(ticket, message_id or "", action="delete")+ if error is not None:+ return error+ assert comment is not None++ with transaction.atomic():+ locked = Comment.objects.select_for_update().get(pk=comment.pk)+ if locked.deleted:+ return Response(+ {"detail": "Note not found.", "error_type": "note_not_found"},+ status=drf_status.HTTP_404_NOT_FOUND,+ )+ if locked.created_by_id != request.user.id:+ return Response(+ {+ "detail": "You can only delete your own private notes.",+ "error_type": "not_note_author",+ },+ status=drf_status.HTTP_403_FORBIDDEN,+ )+ locked.deleted = True+ locked.save(update_fields=["deleted"])++ return Response(status=drf_status.HTTP_204_NO_CONTENT)+@extend_schema(parameters=[TICKET_ID_PARAM],request=AiFeedbackRequestSerializer,diff --git a/products/conversations/frontend/components/Chat/ChatView.tsx b/products/conversations/frontend/components/Chat/ChatView.tsxindex 52c1b2f4174a..9b72c056487b 100644--- a/products/conversations/frontend/components/Chat/ChatView.tsx+++ b/products/conversations/frontend/components/Chat/ChatView.tsx@@ -33,7 +33,7 @@ export interface ChatViewProps {/** Whether to show delivery status on team messages */showDeliveryStatus?: boolean/** Draft content to restore (for tab persistence) */- draftContent?: JSONContent | null+ draftContent?: JSONContent | string | null/** Called when draft content changes */onDraftChange?: (content: JSONContent | null) => void/** Whether the private note checkbox is checked */@@ -63,6 +63,13 @@ export interface ChatViewProps {showAiReplyFeedback?: booleanaiReplyFeedbackDisabledReason?: stringonSubmitAiReplyFeedback?: (messageId: string, rating: AiReplyFeedbackRating, feedbackText?: string) => void+ currentUserId?: number | null+ /** False when the caller lacks ticket editor access (e.g. viewer-only). */+ canEditTicket?: boolean+ editingMessageId?: string | null+ onEditMessage?: (message: ChatMessage) => void+ onDeleteMessage?: (messageId: string) => void+ onCancelEdit?: () => void}export function ChatView({@@ -98,6 +105,12 @@ export function ChatView({showAiReplyFeedback,aiReplyFeedbackDisabledReason,onSubmitAiReplyFeedback,+ currentUserId,+ canEditTicket = false,+ editingMessageId,+ onEditMessage,+ onDeleteMessage,+ onCancelEdit,}: ChatViewProps): JSX.Element {const listMinHeight = minHeight ?? '400px'const listMaxHeight = maxHeight ?? '600px'@@ -122,6 +135,10 @@ export function ChatView({aiReplyFeedbackDisabledReason={aiReplyFeedbackDisabledReason}onSubmitAiReplyFeedback={onSubmitAiReplyFeedback}extras={threadExtras}+ currentUserId={currentUserId}+ canEditTicket={canEditTicket}+ onEditMessage={onEditMessage}+ onDeleteMessage={onDeleteMessage}/><div className="border-t pt-3"><MessageInput@@ -141,6 +158,8 @@ export function ChatView({sendConfirmationMessage={sendConfirmationMessage}sendAndSetStatusOptions={sendAndSetStatusOptions}unsavedTicketChanges={unsavedTicketChanges}+ editingMessageId={editingMessageId}+ onCancelEdit={onCancelEdit}/></div></LemonCard>diff --git a/products/conversations/frontend/components/Chat/Message.tsx b/products/conversations/frontend/components/Chat/Message.tsxindex 29c805b8e68d..2626e87b8955 100644--- a/products/conversations/frontend/components/Chat/Message.tsx+++ b/products/conversations/frontend/components/Chat/Message.tsx@@ -3,10 +3,12 @@ import { useRef, useState } from 'react'import {IconCopy,+ IconPencil,IconThumbsDown,IconThumbsDownFilled,IconThumbsUp,IconThumbsUpFilled,+ IconTrash,IconWarning,} from '@posthog/icons'import { LemonButton, LemonInput, ProfilePicture, Tooltip } from '@posthog/lemon-ui'@@ -26,6 +28,8 @@ export interface MessageProps {aiReplyFeedbackRating?: AiReplyFeedbackRating | nullaiReplyFeedbackDisabledReason?: stringonSubmitAiReplyFeedback?: (rating: AiReplyFeedbackRating, feedbackText?: string) => void+ onEdit?: () => void+ onDelete?: () => void}export function Message({@@ -36,6 +40,8 @@ export function Message({aiReplyFeedbackRating = null,aiReplyFeedbackDisabledReason,onSubmitAiReplyFeedback,+ onEdit,+ onDelete,}: MessageProps): JSX.Element {const profileType = message.authorType === 'AI' ? 'bot' : 'person'const isPrivate = message.isPrivate@@ -80,6 +86,7 @@ export function Message({{isPrivate && <TeamOnlyBadge label="Private note" />}<span className="text-xs text-muted-alt"><TZLabel time={message.createdAt} />+ {(message.version ?? 0) > 0 ? ' (edited)' : null}</span></div></div>@@ -94,7 +101,28 @@ export function Message({} [&_img]:max-h-64 [&_.SupportEditor__image]:max-h-64`}>{isPrivate && (- <div className="flex items-center justify-end">+ <div className="flex items-center justify-end gap-2">+ {onEdit && (+ <Tooltip title="Edit note">+ <LemonButton+ size="xsmall"+ icon={<IconPencil />}+ noPadding+ onClick={onEdit}+ />+ </Tooltip>+ )}+ {onDelete && (+ <Tooltip title="Delete note">+ <LemonButton+ size="xsmall"+ icon={<IconTrash />}+ noPadding+ status="danger"+ onClick={onDelete}+ />+ </Tooltip>+ )}<Tooltip title="Copy message"><LemonButtonsize="xsmall"diff --git a/products/conversations/frontend/components/Chat/MessageInput.test.tsx b/products/conversations/frontend/components/Chat/MessageInput.test.tsxindex c0d0ddb7ba44..61245ee83d22 100644--- a/products/conversations/frontend/components/Chat/MessageInput.test.tsx+++ b/products/conversations/frontend/components/Chat/MessageInput.test.tsx@@ -24,7 +24,12 @@ jest.mock('../Editor', () => {disabled?: boolean}) => {React.useEffect(() => {- onCreate({ getJSON: () => ({ type: 'doc' }), clear: () => {} })+ onCreate({+ getJSON: () => ({ type: 'doc' }),+ clear: () => {},+ setContent: () => {},+ isEmpty: () => false,+ })// eslint-disable-next-line react-hooks/exhaustive-deps}, [])return React.createElement(@@ -109,3 +114,39 @@ describe('MessageInput', () => {expect(onSendMessage).toHaveBeenCalledWith('hello', { type: 'doc' }, isPrivate, expect.any(Function), 'pending')})})++describe('MessageInput editing mode', () => {+ beforeEach(() => {+ initKeaTests()+ })++ afterEach(() => {+ cleanup()+ })++ test('shows Save and Cancel, and locks the private checkbox', () => {+ const onCancelEdit = jest.fn()++ render(+ <Provider>+ <MessageInput+ onSendMessage={jest.fn()}+ messageSending={false}+ showPrivateOption+ isPrivate+ onPrivateChange={jest.fn()}+ draftContent={{ type: 'doc', content: [] }}+ editingMessageId="note-1"+ onCancelEdit={onCancelEdit}+ />+ </Provider>+ )++ expect(screen.getByText('Save')).toBeInTheDocument()+ expect(screen.getByText('Cancel')).toBeInTheDocument()+ expect(screen.queryByLabelText(/and set ticket status/)).not.toBeInTheDocument()++ const checkbox = screen.getByRole('checkbox')+ expect(checkbox).toBeDisabled()+ })+})diff --git a/products/conversations/frontend/components/Chat/MessageInput.tsx b/products/conversations/frontend/components/Chat/MessageInput.tsxindex 004a25a27d41..5337b40b638a 100644--- a/products/conversations/frontend/components/Chat/MessageInput.tsx+++ b/products/conversations/frontend/components/Chat/MessageInput.tsx@@ -28,7 +28,7 @@ export interface MessageInputProps {/** Whether to show the "Send as private" checkbox */showPrivateOption?: boolean/** Draft content to restore (from parent logic for tab persistence) */- draftContent?: JSONContent | null+ draftContent?: JSONContent | string | null/** Called when draft content changes */onDraftChange?: (content: JSONContent | null) => void/** Whether the private note checkbox is checked (from parent logic for tab persistence) */@@ -51,6 +51,10 @@ export interface MessageInputProps {sendAndSetStatusOptions?: { value: TicketStatus; statusLabel: string }[]/** Other unsaved ticket edits that sending with a status would also persist; when non-empty, asks for confirmation first */unsavedTicketChanges?: string[]+ /** When set, the composer is editing an existing private note */+ editingMessageId?: string | null+ /** Cancel edit mode and restore the previous draft */+ onCancelEdit?: () => void}export function MessageInput({@@ -73,27 +77,81 @@ export function MessageInput({sendConfirmationMessage,sendAndSetStatusOptions,unsavedTicketChanges,+ editingMessageId = null,+ onCancelEdit,}: MessageInputProps): JSX.Element {const [isEmpty, setIsEmpty] = useState(!draftContent)const [isUploading, setIsUploading] = useState(false)const [localIsPrivate, setLocalIsPrivate] = useState(false)const editorRef = useRef<RichContentEditorType | null>(null)+ const lastSeededEditId = useRef<string | null>(null)+ const draftContentRef = useRef(draftContent)+ draftContentRef.current = draftContent+ const isEditing = !!editingMessageIduseEffect(() => {setIsEmpty(!draftContent)}, [draftContent])+ // SupportEditor only applies initialContent at mount; seed/restore via setContent on edit transitions.+ // Defer seeding so kea listeners can apply setDraftContent before we read it.+ useEffect(() => {+ const editor = editorRef.current+ if (!editor) {+ return+ }++ if (!editingMessageId) {+ if (lastSeededEditId.current !== null) {+ lastSeededEditId.current = null+ const content = draftContentRef.current+ if (content) {+ editor.setContent(content)+ queueMicrotask(() => setIsEmpty(editor.isEmpty()))+ } else {+ editor.clear()+ setIsEmpty(true)+ }+ }+ return+ }++ if (lastSeededEditId.current === editingMessageId) {+ return+ }+ const targetId = editingMessageId+ queueMicrotask(() => {+ const ed = editorRef.current+ if (!ed || lastSeededEditId.current === targetId) {+ return+ }+ const content = draftContentRef.current+ if (content == null) {+ return+ }+ lastSeededEditId.current = targetId+ ed.setContent(content)+ queueMicrotask(() => setIsEmpty(ed.isEmpty()))+ })+ }, [editingMessageId])+// Support controlled or uncontrolled isPrivateconst isPrivate = controlledIsPrivate ?? localIsPrivateconst setIsPrivate = onPrivateChange ?? setLocalIsPrivate- const resolvedPlaceholder = placeholder ?? (isPrivate ? 'Type your private note...' : getReplyPlaceholder(channel))- const showChannelLogo = !isPrivate && hasReplyChannelBranding(channel)- const sendVerb = isPrivate ? 'Attach' : 'Send'+ const resolvedPlaceholder =+ placeholder ??+ (isEditing+ ? 'Edit your private note...'+ : isPrivate+ ? 'Type your private note...'+ : getReplyPlaceholder(channel))+ const showChannelLogo = !isPrivate && !isEditing && hasReplyChannelBranding(channel)+ const sendVerb = isEditing ? 'Save' : isPrivate ? 'Attach' : 'Send'const handleSubmit = (statusAfterSend?: TicketStatus): void => {// These guard the Cmd+Enter path, which bypasses the disabled button.- if (sendDisabledReason || (replyDisabledReason && !isPrivate)) {+ if (sendDisabledReason || (replyDisabledReason && !isPrivate && !isEditing)) {return}if (messageSending || isUploading) {@@ -117,11 +175,11 @@ export function MessageInput({setLocalIsPrivate(false)}},- statusAfterSend+ isEditing ? undefined : statusAfterSend)}// Sending with a status saves the whole ticket, so surface any other unsaved edits first.- if (statusAfterSend && unsavedTicketChanges && unsavedTicketChanges.length > 0) {+ if (!isEditing && statusAfterSend && unsavedTicketChanges && unsavedTicketChanges.length > 0) {LemonDialog.open({title: `${sendVerb} and save other changes?`,description: (@@ -142,7 +200,7 @@ export function MessageInput({primaryButton: { children: `${sendVerb} and save`, type: 'primary', onClick: doSend },secondaryButton: { children: 'Cancel' },})- } else if (draftMode && !isPrivate && sendConfirmationMessage) {+ } else if (!isEditing && draftMode && !isPrivate && sendConfirmationMessage) {// Private notes are never sent externally, so they skip the draft-mode confirmation.LemonDialog.open({title: 'Ready to send?',@@ -165,7 +223,7 @@ export function MessageInput({const sendBlockedReason = sendDisabledReason? sendDisabledReason- : replyDisabledReason && !isPrivate+ : replyDisabledReason && !isPrivate && !isEditing? replyDisabledReason: isEmpty? 'No message'@@ -182,11 +240,12 @@ export function MessageInput({return (<div><SupportEditor- initialContent={draftContent}+ initialContent={typeof draftContent === 'string' ? null : draftContent}placeholder={resolvedPlaceholder}onCreate={(editor) => {editorRef.current = editorif (draftContent) {+ editor.setContent(draftContent)setIsEmpty(false)}}}@@ -196,7 +255,7 @@ export function MessageInput({disabled={messageSending || !!sendDisabledReason}minRows={minRows}className={- isPrivate+ isPrivate || isEditing? 'bg-warning-highlight border-warning': draftMode? 'bg-success-highlight border-success'@@ -208,13 +267,13 @@ export function MessageInput({<Tooltip title="Private notes are only visible to your team, not to the customer."><span><LemonCheckbox- checked={isPrivate}+ checked={isPrivate || isEditing}onChange={setIsPrivate}- disabledReason={sendControlDisabledReason}+ disabledReason={isEditing ? 'Editing a private note' : sendControlDisabledReason}label={<span className="inline-flex items-center gap-1"><IconLock className="text-sm" />- Attach as private note+ {isEditing ? 'Editing private note' : 'Attach as private note'}</span>}/>@@ -226,7 +285,11 @@ export function MessageInput({<div className="flex items-center gap-2">{onDraftModeChange && (<Tooltip- title={isPrivate ? null : 'In draft mode, sending asks you to confirm the recipient first.'}+ title={+ isPrivate || isEditing+ ? null+ : 'In draft mode, sending asks you to confirm the recipient first.'+ }><span><LemonSwitch@@ -235,20 +298,27 @@ export function MessageInput({label="Draft mode"disabledReason={sendControlDisabledReason ??- (isPrivate ? 'Draft mode has no effect on private notes' : undefined)+ (isPrivate || isEditing+ ? 'Draft mode has no effect on private notes'+ : undefined)}/></span></Tooltip>)}{extraActions}+ {isEditing && onCancelEdit && (+ <LemonButton type="secondary" onClick={onCancelEdit} disabled={messageSending}>+ Cancel+ </LemonButton>+ )}<LemonButtontype="primary"onClick={() => handleSubmit()}loading={messageSending}disabledReason={sendBlockedReason}sideAction={- sendAndSetStatusOptions?.length+ !isEditing && sendAndSetStatusOptions?.length? {'aria-label': `${sendVerb} and set ticket status`,disabled: messageSending,@@ -270,7 +340,9 @@ export function MessageInput({: undefined}>- {isPrivate ? (+ {isEditing ? (+ 'Save'+ ) : isPrivate ? ('Attach') : showChannelLogo ? (<span className="inline-flex items-center gap-1.5">diff --git a/products/conversations/frontend/components/Chat/MessageList.tsx b/products/conversations/frontend/components/Chat/MessageList.tsxindex 9efd2eaf0831..e559b365fbc7 100644--- a/products/conversations/frontend/components/Chat/MessageList.tsx+++ b/products/conversations/frontend/components/Chat/MessageList.tsx@@ -34,6 +34,11 @@ export interface MessageListProps {/** Non-message timeline entries, placed among the messages by their own timestamp. Opt-in, so a* customer-facing view never receives team-only content. */extras?: TimelineExtra[]+ currentUserId?: number | null+ /** False when the caller lacks ticket editor access (e.g. viewer-only). */+ canEditTicket?: boolean+ onEditMessage?: (message: ChatMessage) => void+ onDeleteMessage?: (messageId: string) => void}/** A non-message entry in the thread, e.g. an agent's findings. `at` is what orders it among the@@ -62,6 +67,10 @@ export function MessageList({aiReplyFeedbackDisabledReason,onSubmitAiReplyFeedback,extras = [],+ currentUserId = null,+ canEditTicket = false,+ onEditMessage,+ onDeleteMessage,}: MessageListProps): JSX.Element {const messagesEndRef = useRef<HTMLDivElement>(null)const containerRef = useRef<HTMLDivElement>(null)@@ -195,12 +204,18 @@ export function MessageList({const timeline: JSX.Element[] = [...messages.map((message) => {const isCustomer = message.authorType === 'customer'+ const canModify =+ canEditTicket &&+ !!message.isPrivate &&+ message.authorType === 'human' &&+ !!currentUserId &&+ message.createdBy?.id === currentUserIdreturn {at: message.createdAt,rank: 0,element: (<Message- key={message.id}+ key={`${message.id}-${message.version ?? 0}`}message={message}isCustomer={isCustomerView ? !isCustomer : isCustomer}deliveryStatus={deliveryStatusMap.get(message.id)}@@ -214,6 +229,8 @@ export function MessageList({? (rating, feedbackText) => onSubmitAiReplyFeedback(message.id, rating, feedbackText): undefined}+ onEdit={canModify && onEditMessage ? () => onEditMessage(message) : undefined}+ onDelete={canModify && onDeleteMessage ? () => onDeleteMessage(message.id) : undefined}/>),}diff --git a/products/conversations/frontend/components/Editor/SupportRichContentPreview.tsx b/products/conversations/frontend/components/Editor/SupportRichContentPreview.tsxindex eba9279345ef..933f1a845740 100644--- a/products/conversations/frontend/components/Editor/SupportRichContentPreview.tsx+++ b/products/conversations/frontend/components/Editor/SupportRichContentPreview.tsx@@ -3,7 +3,7 @@ import './SupportEditor.scss'import { JSONContent, getSchema } from '@tiptap/core'import { Node as ProseMirrorNode } from '@tiptap/pm/model'import { EditorContent } from '@tiptap/react'-import { useMemo } from 'react'+import { useEffect, useMemo } from 'react'import { useRichContentEditor } from 'lib/components/RichContentEditor'import { cn } from 'lib/utils/css-classes'@@ -70,6 +70,17 @@ function RichContentPreviewEditor({ content, className }: { content: JSONContentinitialContent: content,})+ // TipTap only applies initialContent once; push updates when note content changes in place.+ useEffect(() => {+ if (!editor) {+ return+ }+ const next = JSON.stringify(content)+ if (JSON.stringify(editor.getJSON()) !== next) {+ editor.commands.setContent(content, { emitUpdate: false })+ }+ }, [editor, content])+return (<><EditorContentdiff --git a/products/conversations/frontend/generated/api.schemas.ts b/products/conversations/frontend/generated/api.schemas.tsindex 871d33183aa6..c865af761b66 100644--- a/products/conversations/frontend/generated/api.schemas.ts+++ b/products/conversations/frontend/generated/api.schemas.ts@@ -928,6 +928,8 @@ export interface TicketMessageApi {readonly author_name: string/** True for internal notes not visible to the customer. */readonly is_private: boolean+ /** Edit count. 0 means never edited. */+ readonly version: numberreadonly created_at: string}@@ -940,6 +942,24 @@ export interface PaginatedTicketMessageListApi {results: TicketMessageApi[]}+/**+ * Payload for updating a private note on a ticket.+ */+export interface PatchedTicketNoteUpdateRequestApi {+ /**+ * Updated note content in markdown.+ * @maxLength 5000+ */+ message?: string+ /** Optional TipTap rich content JSON. Omit or pass null to clear previous rich content so the thread falls back to the markdown message. */+ rich_content?: unknown+}++export interface TicketErrorApi {+ detail: string+ error_type?: string+}+/*** Payload for posting a reply or internal note to a ticket.*/@@ -1053,11 +1073,6 @@ export interface ComposeTicketResponseApi {ticket_number: number}-export interface TicketErrorApi {- detail: string- error_type?: string-}-/*** * `widget` - widget* * `email` - emaildiff --git a/products/conversations/frontend/generated/api.ts b/products/conversations/frontend/generated/api.tsindex 07a022a64b98..d2841783b0b9 100644--- a/products/conversations/frontend/generated/api.ts+++ b/products/conversations/frontend/generated/api.ts@@ -29,6 +29,7 @@ import type {PaginatedTicketViewListApi,PatchedConversationApi,PatchedTicketApi,+ PatchedTicketNoteUpdateRequestApi,PatchedTicketViewApi,SandboxMessageResponseApi,SandboxOpenApi,@@ -449,6 +450,53 @@ export const conversationsTicketsMessagesList = async (})}+export const getConversationsTicketsNotesPartialUpdateUrl = (projectId: string, id: string, messageId: string) => {+ return `/api/projects/${projectId}/conversations/tickets/${id}/notes/${messageId}/`+}++/**+ * Update a private note on a ticket.+ *+ * Only the note's author can edit it. Customer-facing replies cannot be+ * edited (outbound delivery only runs on create).+ */+export const conversationsTicketsNotesPartialUpdate = async (+ projectId: string,+ id: string,+ messageId: string,+ patchedTicketNoteUpdateRequestApi?: PatchedTicketNoteUpdateRequestApi,+ options?: RequestInit+): Promise<TicketMessageApi> => {+ return apiMutator<TicketMessageApi>(getConversationsTicketsNotesPartialUpdateUrl(projectId, id, messageId), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedTicketNoteUpdateRequestApi),+ })+}++export const getConversationsTicketsNotesDestroyUrl = (projectId: string, id: string, messageId: string) => {+ return `/api/projects/${projectId}/conversations/tickets/${id}/notes/${messageId}/`+}++/**+ * Soft-delete a private note on a ticket.+ *+ * Only the note's author can delete it. Customer-facing replies cannot be+ * deleted via this endpoint.+ */+export const conversationsTicketsNotesDestroy = async (+ projectId: string,+ id: string,+ messageId: string,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getConversationsTicketsNotesDestroyUrl(projectId, id, messageId), {+ ...options,+ method: 'DELETE',+ })+}+export const getConversationsTicketsReplyCreateUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/conversations/tickets/${id}/reply/`}diff --git a/products/conversations/frontend/generated/api.zod.ts b/products/conversations/frontend/generated/api.zod.tsindex 6b030120b63a..441f43a590df 100644--- a/products/conversations/frontend/generated/api.zod.ts+++ b/products/conversations/frontend/generated/api.zod.ts@@ -252,6 +252,30 @@ export const ConversationsTicketsAiFeedbackCreateBody = /* @__PURE__ */ zod}).describe('Payload for recording reviewer feedback on an AI reply.')+/**+ * Update a private note on a ticket.+ *+ * Only the note's author can edit it. Customer-facing replies cannot be+ * edited (outbound delivery only runs on create).+ */+export const conversationsTicketsNotesPartialUpdateBodyMessageMax = 5000++export const ConversationsTicketsNotesPartialUpdateBody = /* @__PURE__ */ zod+ .object({+ message: zod+ .string()+ .max(conversationsTicketsNotesPartialUpdateBodyMessageMax)+ .optional()+ .describe('Updated note content in markdown.'),+ rich_content: zod+ .unknown()+ .optional()+ .describe(+ 'Optional TipTap rich content JSON. Omit or pass null to clear previous rich content so the thread falls back to the markdown message.'+ ),+ })+ .describe('Payload for updating a private note on a ticket.')+/*** Post a reply or internal note to a ticket.*diff --git a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsxindex 831e0cc40ee6..fc85b1855d98 100644--- a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx+++ b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx@@ -11,7 +11,7 @@ import { ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/resizerLimport { TZLabel } from 'lib/components/TZLabel'import { dayjs } from 'lib/dayjs'import { LemonCalendarSelectInput } from 'lib/lemon-ui/LemonCalendar/LemonCalendarSelect'-import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'+import { getAccessControlDisabledReason, accessLevelSatisfied } from 'lib/utils/accessControlUtils'import { newInternalTab } from 'lib/utils/newInternalTab'import { PersonDisplay } from 'scenes/persons/PersonDisplay'import { SceneExport } from 'scenes/sceneTypes'@@ -106,6 +106,7 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.ElememailReplyBlockedReason,latestAiMessage,feedbackByMessageId,+ editingMessageId,} = useValues(logic)// The list's filters / saved view ride along in this page's query string// (the ticket row carries them through on navigation). Preserve them on the@@ -126,6 +127,9 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.ElemsetDraftModeEnabled,dismissKnowledgeGap,submitAiReplyFeedback,+ startEditingMessage,+ cancelEditingMessage,+ deleteMessage,} = useActions(logic)const { user } = useValues(userLogic)@@ -156,6 +160,12 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Elem}[emailReplyBlockedReason]: undefined+ const canEditTicket = accessLevelSatisfied(+ AccessControlResourceType.Ticket,+ ticket?.user_access_level ?? AccessControlLevel.None,+ AccessControlLevel.Editor+ )+const sendDisabledReason =getAccessControlDisabledReason(AccessControlResourceType.Ticket,@@ -253,6 +263,12 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.ElemshowAiReplyFeedback={aiSuggestionsEnabled}aiReplyFeedbackDisabledReason={sendDisabledReason}onSubmitAiReplyFeedback={submitAiReplyFeedback}+ currentUserId={user?.id ?? null}+ canEditTicket={canEditTicket}+ editingMessageId={editingMessageId}+ onEditMessage={startEditingMessage}+ onDeleteMessage={deleteMessage}+ onCancelEdit={cancelEditingMessage}/><div className="hidden lg:block"><Resizer {...resizerLogicProps} className="z-20" />diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.tsindex 01c218a5450d..7f04a7fc1580 100644--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts@@ -45,8 +45,15 @@ jest.mock('products/business_knowledge/frontend/generated/api', () => ({businessKnowledgeGapSuggestionsDismissCreate: jest.fn().mockResolvedValue(undefined),}))+jest.mock('products/conversations/frontend/generated/api', () => ({+ conversationsTicketsNotesPartialUpdate: jest.fn().mockResolvedValue(undefined),+ conversationsTicketsNotesDestroy: jest.fn().mockResolvedValue(undefined),+}))+import api from '~/lib/api'+import { conversationsTicketsNotesPartialUpdate } from 'products/conversations/frontend/generated/api'+const submitAiFeedbackMock = api.conversationsTickets.submitAiFeedback as jest.Mockfunction makeAiComment(id: string): CommentType {@@ -478,3 +485,202 @@ describe('supportTicketSceneLogic loadPreviousTickets email gating', () => {expect(ticketsListMock).toHaveBeenLastCalledWith(expectedParams)})})++describe('supportTicketSceneLogic private note editing', () => {+ let logic: ReturnType<typeof supportTicketSceneLogic.build>++ const ticketGetMock = api.conversationsTickets.get as jest.Mock+ const noteUpdateMock = conversationsTicketsNotesPartialUpdate as jest.Mock+ const commentsCreateMock = api.comments.create as jest.Mock++ const loadedTicket = (): Ticket => ({ ...makeTicket(), priority: 'medium', assignee: null }) as Ticket++ beforeEach(async () => {+ localStorage.clear()+ initKeaTests()+ noteUpdateMock.mockReset().mockResolvedValue(undefined)+ commentsCreateMock.mockReset().mockResolvedValue(undefined)+ ticketGetMock.mockReset().mockResolvedValue(loadedTicket())+ logic = supportTicketSceneLogic({ id: 42 })+ logic.mount()+ // Wait for ticket + initial message load so a late setMessages([]) can't cancel an edit.+ await expectLogic(logic).toDispatchActions(['setTicket', 'setMessages'])+ })++ test('startEditingMessage stashes the in-progress draft and loads the note', async () => {+ const draft = { type: 'doc', content: [{ type: 'paragraph', content: [{ type: 'text', text: 'wip' }] }] }+ logic.actions.setDraftContent(draft)+ logic.actions.setDraftIsPrivate(false)++ const noteRich = {+ type: 'doc',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'note body' }] }],+ }+ logic.actions.startEditingMessage({+ id: 'note-1',+ content: 'note body',+ richContent: noteRich,+ authorType: 'human',+ authorName: 'Me',+ createdBy: { id: 1 },+ createdAt: '2026-01-01T00:00:00Z',+ isPrivate: true,+ version: 0,+ })++ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.editingMessageId).toBe('note-1')+ expect(logic.values.draftIsPrivate).toBe(true)+ expect(logic.values.draftContent).toEqual(noteRich)+ expect(logic.values.stashedDraftContent).toEqual(draft)+ expect(logic.values.stashedDraftIsPrivate).toBe(false)+ })++ test('cancelEditingMessage restores the stashed draft', async () => {+ const draft = { type: 'doc', content: [{ type: 'paragraph', content: [{ type: 'text', text: 'wip' }] }] }+ logic.actions.setDraftContent(draft)+ logic.actions.setDraftIsPrivate(false)+ logic.actions.startEditingMessage({+ id: 'note-1',+ content: 'note',+ richContent: { type: 'doc', content: [] },+ authorType: 'human',+ authorName: 'Me',+ createdAt: '2026-01-01T00:00:00Z',+ isPrivate: true,+ })+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.cancelEditingMessage()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.editingMessageId).toBeNull()+ expect(logic.values.draftContent).toEqual(draft)+ expect(logic.values.draftIsPrivate).toBe(false)+ expect(logic.values.stashedDraftContent).toBeNull()+ })++ test('sendMessage while editing hits the note update endpoint and restores the stashed draft', async () => {+ const draft = { type: 'doc', content: [{ type: 'paragraph', content: [{ type: 'text', text: 'wip' }] }] }+ const updatedRich = {+ type: 'doc',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'updated' }] }],+ }+ const commentsListMock = api.comments.list as jest.Mock+ commentsListMock.mockResolvedValue({+ results: [+ {+ id: 'note-1',+ content: 'updated',+ rich_content: updatedRich,+ version: 1,+ created_at: '2026-01-01T00:00:00Z',+ item_context: { author_type: 'support', is_private: true },+ created_by: { id: 1, uuid: 'u1', distinct_id: 'd1', first_name: 'Me', email: '[email protected]' },+ },+ ],+ })+ logic.actions.setMessages([+ {+ id: 'note-1',+ content: 'note',+ rich_content: { type: 'doc', content: [] },+ created_at: '2026-01-01T00:00:00Z',+ item_context: { author_type: 'support', is_private: true },+ created_by: { id: 1, uuid: 'u1', distinct_id: 'd1', first_name: 'Me', email: '[email protected]' },+ version: 0,+ } as any,+ ])+ logic.actions.setDraftContent(draft)+ logic.actions.setDraftIsPrivate(false)+ logic.actions.startEditingMessage({+ id: 'note-1',+ content: 'note',+ richContent: { type: 'doc', content: [] },+ authorType: 'human',+ authorName: 'Me',+ createdAt: '2026-01-01T00:00:00Z',+ isPrivate: true,+ })+ await expectLogic(logic).toFinishAllListeners()++ const onSuccess = jest.fn()+ await expectLogic(logic, () => {+ logic.actions.sendMessage('updated', updatedRich, true, onSuccess)+ }).toFinishAllListeners()++ expect(noteUpdateMock).toHaveBeenCalledWith(expect.any(String), 'ticket-1', 'note-1', {+ message: 'updated',+ rich_content: updatedRich,+ })+ expect(commentsCreateMock).not.toHaveBeenCalled()+ expect(onSuccess).not.toHaveBeenCalled()+ expect(logic.values.editingMessageId).toBeNull()+ expect(logic.values.draftContent).toEqual(draft)+ expect(logic.values.draftIsPrivate).toBe(false)+ expect(logic.values.stashedDraftContent).toBeNull()+ const updated = logic.values.chatMessages.find((m) => m.id === 'note-1')+ expect(updated?.content).toBe('updated')+ expect(updated?.richContent).toEqual(updatedRich)+ expect(updated?.version).toBe(1)+ })++ test('setMessages aborts edit and restores the stashed draft when the note disappears', async () => {+ const draft = { type: 'doc', content: [{ type: 'paragraph', content: [{ type: 'text', text: 'wip' }] }] }+ logic.actions.setDraftContent(draft)+ logic.actions.setDraftIsPrivate(false)+ logic.actions.startEditingMessage({+ id: 'note-1',+ content: 'note',+ richContent: { type: 'doc', content: [] },+ authorType: 'human',+ authorName: 'Me',+ createdAt: '2026-01-01T00:00:00Z',+ isPrivate: true,+ })+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.setMessages([])+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.editingMessageId).toBeNull()+ expect(logic.values.draftContent).toEqual(draft)+ expect(logic.values.draftIsPrivate).toBe(false)+ })++ test('switching notes while editing keeps the original stashed draft', async () => {+ const draft = { type: 'doc', content: [{ type: 'paragraph', content: [{ type: 'text', text: 'wip' }] }] }+ logic.actions.setDraftContent(draft)+ logic.actions.setDraftIsPrivate(false)+ logic.actions.startEditingMessage({+ id: 'note-1',+ content: 'note one',+ richContent: { type: 'doc', content: [{ type: 'paragraph', content: [{ type: 'text', text: 'one' }] }] },+ authorType: 'human',+ authorName: 'Me',+ createdAt: '2026-01-01T00:00:00Z',+ isPrivate: true,+ })+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.startEditingMessage({+ id: 'note-2',+ content: 'note two',+ richContent: { type: 'doc', content: [{ type: 'paragraph', content: [{ type: 'text', text: 'two' }] }] },+ authorType: 'human',+ authorName: 'Me',+ createdAt: '2026-01-01T00:00:00Z',+ isPrivate: true,+ })+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.editingMessageId).toBe('note-2')+ expect(logic.values.stashedDraftContent).toEqual(draft)++ logic.actions.cancelEditingMessage()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.draftContent).toEqual(draft)+ })+})diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.tsindex ab7c79d3f7e5..7a3d95660bbc 100644--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts@@ -19,8 +19,10 @@ import { beforeUnload, router } from 'kea-router'import { lemonToast } from '@posthog/lemon-ui'import { dayjs } from 'lib/dayjs'+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'import { getCurrentTeamId } from 'lib/utils/getAppContext'import { isUUIDLike } from 'lib/utils/guards'+import { markdownToHtml } from 'lib/utils/markdown'import { fullName } from 'lib/utils/strings'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'@@ -40,6 +42,10 @@ import {businessKnowledgeGapSuggestionsDismissCreate,businessKnowledgeGapSuggestionsList,} from 'products/business_knowledge/frontend/generated/api'+import {+ conversationsTicketsNotesDestroy,+ conversationsTicketsNotesPartialUpdate,+} from 'products/conversations/frontend/generated/api'import { signalsReportsList } from 'products/signals/frontend/generated/api'import type { SignalReportApi } from 'products/signals/frontend/generated/api.schemas'@@ -179,9 +185,10 @@ export interface supportTicketSceneLogicValues {breadcrumbs: Breadcrumb[]chatMessages: ChatMessage[]chatPanelWidth: (desiredSize: number | null) => number- draftContent: JSONContent | null+ draftContent: string | JSONContent | nulldraftIsPrivate: booleandraftModeEnabled: boolean+ editingMessageId: string | nullemailReplyBlockedReason: EmailReplyBlockedReason | nulleventsQuery: DataTableNode | nullexceptionsQuery: DataTableNode | null@@ -206,6 +213,8 @@ export interface supportTicketSceneLogicValues {replyRecipientDescription: stringsidePanelContext: SidePanelSceneContext | nullsnoozedUntil: string | null+ stashedDraftContent: string | JSONContent | null+ stashedDraftIsPrivate: booleanstatus: TicketStatus | nulltags: string[]ticket: Ticket | null@@ -220,6 +229,15 @@ export interface supportTicketSceneLogicActions {value: true} // supportTicketsSceneLogicloadTags: () => any // tagsModel+ cancelEditingMessage: () => {+ value: true+ }+ clearEditingMessage: () => {+ value: true+ }+ deleteMessage: (messageId: string) => {+ messageId: string+ }dismissKnowledgeGap: (suggestionId: string) => {suggestionId: string}@@ -342,8 +360,8 @@ export interface supportTicketSceneLogicActions {setAssignee: (assignee: TicketAssignee) => {assignee: TicketAssignee}- setDraftContent: (content: JSONContent | null) => {- content: JSONContent | null+ setDraftContent: (content: string | JSONContent | null) => {+ content: string | JSONContent | null}setDraftIsPrivate: (isPrivate: boolean) => {isPrivate: boolean@@ -390,6 +408,16 @@ export interface supportTicketSceneLogicActions {setTicketUpdating: (updating: boolean) => {updating: boolean}+ startEditingMessage: (message: ChatMessage) => {+ message: ChatMessage+ }+ stashDraftForEdit: (+ content: string | JSONContent | null,+ isPrivate: boolean+ ) => {+ content: string | JSONContent | null+ isPrivate: boolean+ }submitAiReplyFeedback: (messageId: string,rating: AiReplyFeedbackRating,@@ -432,7 +460,7 @@ export interface supportTicketSceneLogicMeta {ticket: Ticket | null,unsavedTicketChanges: string[]) => boolean- hasPendingWork: (hasUnsavedChanges: boolean) => boolean+ hasPendingWork: (hasUnsavedChanges: boolean, editingMessageId: string | null) => booleanchatMessages: (messages: CommentType[], ticket: Ticket | null) => ChatMessage[]eventsQuery: (ticket: Ticket | null) => DataTableNode | nullexceptionsQuery: (ticket: Ticket | null) => DataTableNode | null@@ -513,11 +541,17 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([dismissKnowledgeGap: (suggestionId: string) => ({ suggestionId }),// Draft message state (persists across tab switches)- setDraftContent: (content: JSONContent | null) => ({ content }),+ setDraftContent: (content: string | JSONContent | null) => ({ content }),setDraftIsPrivate: (isPrivate: boolean) => ({ isPrivate }),// Per-ticket draft mode override, seeded from the browser-local default on opensetDraftModeEnabled: (enabled: boolean) => ({ enabled }),+ startEditingMessage: (message: ChatMessage) => ({ message }),+ cancelEditingMessage: true,+ clearEditingMessage: true,+ stashDraftForEdit: (content: string | JSONContent | null, isPrivate: boolean) => ({ content, isPrivate }),+ deleteMessage: (messageId: string) => ({ messageId }),+submitAiReplyFeedback: (messageId: string, rating: AiReplyFeedbackRating, feedbackText?: string) => ({messageId,rating,@@ -740,7 +774,7 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([},],draftContent: [- null as JSONContent | null,+ null as string | JSONContent | null,{setDraftContent: (_, { content }) => content,},@@ -757,6 +791,27 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([setDraftModeEnabled: (_, { enabled }) => enabled,},],+ editingMessageId: [+ null as string | null,+ {+ startEditingMessage: (_, { message }) => message.id,+ clearEditingMessage: () => null,+ },+ ],+ stashedDraftContent: [+ null as string | JSONContent | null,+ {+ stashDraftForEdit: (_, { content }) => content,+ clearEditingMessage: () => null,+ },+ ],+ stashedDraftIsPrivate: [+ false,+ {+ stashDraftForEdit: (_, { isPrivate }) => isPrivate,+ clearEditingMessage: () => false,+ },+ ],feedbackByMessageId: [{} as Record<string, AiReplyFeedbackRating>,{ persist: true, storageKey: 'conversations_ai_reply_feedback' },@@ -868,7 +923,11 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([return status !== ticket.status || unsavedTicketChanges.length > 0},],- hasPendingWork: [(s) => [s.hasUnsavedChanges], (hasUnsavedChanges: boolean): boolean => hasUnsavedChanges],+ hasPendingWork: [+ (s) => [s.hasUnsavedChanges, s.editingMessageId],+ (hasUnsavedChanges: boolean, editingMessageId: string | null): boolean =>+ hasUnsavedChanges || !!editingMessageId,+ ],chatPanelWidth: [() => [],() =>@@ -929,6 +988,7 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([createdBy: message.created_by,createdAt: message.created_at,isPrivate: message.item_context?.is_private || false,+ version: message.version,emailDeliveryStatus: message.item_context?.email_delivery_status,fromZendesk: message.item_context?.from_zendesk === true,}@@ -978,6 +1038,9 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([}),listeners(({ actions, values, props, cache }) => ({loadTicket: async () => {+ if (values.editingMessageId) {+ actions.cancelEditingMessage()+ }if (props.id === 'new') {actions.setTicket(null)return@@ -1131,6 +1194,38 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([return}try {+ if (values.editingMessageId) {+ const editingId = values.editingMessageId+ await conversationsTicketsNotesPartialUpdate(+ String(getCurrentTeamId()),+ values.ticket.id,+ editingId,+ {+ message: content,+ rich_content: richContent,+ }+ )+ // Optimistic local update so the thread reflects the edit before comments.list returns.+ actions.setMessages(+ values.messages.map((message) =>+ message.id === editingId+ ? {+ ...message,+ content,+ rich_content: richContent,+ version: (message.version ?? 0) + 1,+ }+ : message+ )+ )+ lemonToast.success('Private note updated')+ actions.setMessageSending(false)+ // Restore the stashed composer draft; skip onSuccess (it clears the editor).+ actions.cancelEditingMessage()+ actions.loadMessages()+ return+ }+await api.comments.create({content,@@ -1161,10 +1256,65 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([}, 300)actions.loadTickets()} catch {- lemonToast.error('Failed to send message')+ lemonToast.error(values.editingMessageId ? 'Failed to update note' : 'Failed to send message')actions.setMessageSending(false)}},+ startEditingMessage: ({ message }) => {+ // Only stash the composer draft on first enter; switching notes keeps the original stash.+ if (!cache.noteEditActive) {+ actions.stashDraftForEdit(values.draftContent, values.draftIsPrivate)+ cache.noteEditActive = true+ }+ actions.setDraftIsPrivate(true)+ if (message.richContent) {+ actions.setDraftContent(message.richContent as JSONContent)+ } else {+ // Notes from MCP/reply API are markdown-only; TipTap parses HTML from marked.+ actions.setDraftContent(markdownToHtml(message.content || ''))+ }+ },+ cancelEditingMessage: () => {+ actions.setDraftContent(values.stashedDraftContent)+ actions.setDraftIsPrivate(values.stashedDraftIsPrivate)+ cache.noteEditActive = false+ actions.clearEditingMessage()+ },+ setMessages: ({ messages }) => {+ if (values.editingMessageId && !messages.some((m) => m.id === values.editingMessageId)) {+ actions.cancelEditingMessage()+ }+ },+ deleteMessage: async ({ messageId }) => {+ if (!values.ticket?.id) {+ return+ }+ LemonDialog.open({+ title: 'Delete private note?',+ description: 'This removes the note from the ticket thread.',+ primaryButton: {+ children: 'Delete',+ status: 'danger',+ onClick: async () => {+ try {+ await conversationsTicketsNotesDestroy(+ String(getCurrentTeamId()),+ values.ticket!.id,+ messageId+ )+ lemonToast.success('Private note deleted')+ if (values.editingMessageId === messageId) {+ actions.cancelEditingMessage()+ }+ actions.loadMessages()+ } catch {+ lemonToast.error('Failed to delete note')+ }+ },+ },+ secondaryButton: { children: 'Cancel' },+ })+ },dismissKnowledgeGap: async ({ suggestionId }) => {try {await businessKnowledgeGapSuggestionsDismissCreate(String(getCurrentTeamId()), suggestionId)diff --git a/products/conversations/frontend/types.ts b/products/conversations/frontend/types.tsindex 8ebdfe5a3990..db4a537aa367 100644--- a/products/conversations/frontend/types.ts+++ b/products/conversations/frontend/types.ts@@ -206,6 +206,7 @@ export interface ConversationMessage {}export interface MessageAuthor {+ id?: numberfirst_name?: stringlast_name?: stringemail?: string@@ -223,6 +224,8 @@ export interface ChatMessage {createdBy?: MessageAuthor | nullcreatedAt: stringisPrivate?: boolean+ /** Edit count from the comment row. 0 means never edited. */+ version?: numberemailDeliveryStatus?: EmailDeliveryStatus/** Imported from an external tool (e.g. Zendesk). Such content is untrusted, so its Markdown* is rendered with external image auto-loading disabled. */diff --git a/products/conversations/mcp/tools.yaml b/products/conversations/mcp/tools.yamlindex 8c6fad4d09b2..a74272ae006b 100644--- a/products/conversations/mcp/tools.yaml+++ b/products/conversations/mcp/tools.yaml@@ -75,6 +75,39 @@ 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-destroy:+ operation: conversations_tickets_notes_destroy+ enabled: true+ scopes:+ - ticket:write+ annotations:+ readOnly: false+ destructive: true+ idempotent: true+ title: Delete private note+ description: >+ Soft-delete a private note on a support ticket. Only private notes authored by the calling user can be+ deleted. Customer-facing replies cannot be deleted. Message IDs come from+ conversations-tickets-messages-retrieve. Deleting another user's note or an AI-authored note returns 403+ with error_type not_note_author. Deleting a public reply returns 400 with error_type not_private_note. A+ missing or already-deleted note returns 404 with error_type note_not_found.+ conversations-tickets-notes-partial-update:+ operation: conversations_tickets_notes_partial_update+ enabled: true+ scopes:+ - ticket:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Update private note+ description: >+ Update a private note on a support ticket. Only private notes authored by the calling user can be edited.+ Customer-facing replies cannot be edited. Message IDs come from conversations-tickets-messages-retrieve.+ Editing another user's note or an AI-authored note returns 403 with error_type not_note_author. Editing a+ public reply returns 400 with error_type not_private_note. A missing or deleted note returns 404 with+ error_type note_not_found. Each successful update increments the note's version. Omit rich_content to clear+ previous TipTap JSON so the thread falls back to the markdown message.conversations-tickets-reply-create:operation: conversations_tickets_reply_createenabled: truediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex b1fa84840eee..fd34ed25fe8a 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -1648,6 +1648,34 @@"readOnlyHint": true}},+ "conversations-tickets-notes-destroy": {+ "description": "Soft-delete a private note on a support ticket. Only private notes authored by the calling user can be deleted. Customer-facing replies cannot be deleted. Message IDs come from conversations-tickets-messages-retrieve. Deleting another user's note or an AI-authored note returns 403 with error_type not_note_author. Deleting a public reply returns 400 with error_type not_private_note. A missing or already-deleted note returns 404 with error_type note_not_found.",+ "category": "Conversations",+ "feature": "conversations",+ "summary": "Delete private note",+ "title": "Delete private note",+ "required_scopes": ["ticket:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "conversations-tickets-notes-partial-update": {+ "description": "Update a private note on a support ticket. Only private notes authored by the calling user can be edited. Customer-facing replies cannot be edited. Message IDs come from conversations-tickets-messages-retrieve. Editing another user's note or an AI-authored note returns 403 with error_type not_note_author. Editing a public reply returns 400 with error_type not_private_note. A missing or deleted note returns 404 with error_type note_not_found. Each successful update increments the note's version. Omit rich_content to clear previous TipTap JSON so the thread falls back to the markdown message.",+ "category": "Conversations",+ "feature": "conversations",+ "summary": "Update private note",+ "title": "Update private note",+ "required_scopes": ["ticket:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"conversations-tickets-reply-create": {"description": "Post a reply or internal note to a support ticket. IMPORTANT: With is_private=false (the default), the reply IS DELIVERED to the customer via the ticket's channel (email, Slack, Teams, or GitHub). Set is_private=true to store an internal note visible only to team members.","category": "Conversations",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex e376df2feeda..bbada233f93a 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -1663,6 +1663,34 @@"readOnlyHint": true}},+ "conversations-tickets-notes-destroy": {+ "description": "Soft-delete a private note on a support ticket. Only private notes authored by the calling user can be deleted. Customer-facing replies cannot be deleted. Message IDs come from conversations-tickets-messages-retrieve. Deleting another user's note or an AI-authored note returns 403 with error_type not_note_author. Deleting a public reply returns 400 with error_type not_private_note. A missing or already-deleted note returns 404 with error_type note_not_found.",+ "category": "Conversations",+ "feature": "conversations",+ "summary": "Delete private note",+ "title": "Delete private note",+ "required_scopes": ["ticket:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "conversations-tickets-notes-partial-update": {+ "description": "Update a private note on a support ticket. Only private notes authored by the calling user can be edited. Customer-facing replies cannot be edited. Message IDs come from conversations-tickets-messages-retrieve. Editing another user's note or an AI-authored note returns 403 with error_type not_note_author. Editing a public reply returns 400 with error_type not_private_note. A missing or deleted note returns 404 with error_type note_not_found. Each successful update increments the note's version. Omit rich_content to clear previous TipTap JSON so the thread falls back to the markdown message.",+ "category": "Conversations",+ "feature": "conversations",+ "summary": "Update private note",+ "title": "Update private note",+ "required_scopes": ["ticket:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },"conversations-tickets-reply-create": {"description": "Post a reply or internal note to a support ticket. IMPORTANT: With is_private=false (the default), the reply IS DELIVERED to the customer via the ticket's channel (email, Slack, Teams, or GitHub). Set is_private=true to store an internal note visible only to team members.","category": "Conversations",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex d9cee4e40e15..a48c9bb3844a 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -49442,6 +49442,8 @@ export namespace Schemas {readonly author_name: string;/** True for internal notes not visible to the customer. */readonly is_private: boolean;+ /** Edit count. 0 means never edited. */+ readonly version: number;readonly created_at: string;}@@ -57773,6 +57775,19 @@ export namespace Schemas {readonly user_access_level?: string | null;}+ /**+ * Payload for updating a private note on a ticket.+ */+ export interface PatchedTicketNoteUpdateRequest {+ /**+ * Updated note content in markdown.+ * @maxLength 5000+ */+ message?: string;+ /** Optional TipTap rich content JSON. Omit or pass null to clear previous rich content so the thread falls back to the markdown message. */+ rich_content?: unknown;+ }+export interface PatchedTicketView {readonly id?: string;readonly short_id?: string;diff --git a/services/mcp/src/generated/conversations/api.ts b/services/mcp/src/generated/conversations/api.tsindex 7e74c5a6f02a..dd74e5764e79 100644--- a/services/mcp/src/generated/conversations/api.ts+++ b/services/mcp/src/generated/conversations/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 6 enabled ops+ * PostHog API - MCP 8 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -199,6 +199,56 @@ export const ConversationsTicketsMessagesListQueryParams = /* @__PURE__ */ zod.ooffset: zod.number().optional().describe('The initial index from which to return the results.'),})+/**+ * Update a private note on a ticket.+ *+ * Only the note's author can edit it. Customer-facing replies cannot be+ * edited (outbound delivery only runs on create).+ */+export const ConversationsTicketsNotesPartialUpdateParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe("The ticket's UUID or its numeric ticket number."),+ message_id: zod.string().describe('The UUID of the private note (comment) to edit or delete.'),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const conversationsTicketsNotesPartialUpdateBodyMessageMax = 5000++export const ConversationsTicketsNotesPartialUpdateBody = /* @__PURE__ */ zod+ .object({+ message: zod+ .string()+ .max(conversationsTicketsNotesPartialUpdateBodyMessageMax)+ .optional()+ .describe('Updated note content in markdown.'),+ rich_content: zod+ .unknown()+ .optional()+ .describe(+ 'Optional TipTap rich content JSON. Omit or pass null to clear previous rich content so the thread falls back to the markdown message.'+ ),+ })+ .describe('Payload for updating a private note on a ticket.')++/**+ * Soft-delete a private note on a ticket.+ *+ * Only the note's author can delete it. Customer-facing replies cannot be+ * deleted via this endpoint.+ */+export const ConversationsTicketsNotesDestroyParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe("The ticket's UUID or its numeric ticket number."),+ message_id: zod.string().describe('The UUID of the private note (comment) to edit or delete.'),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})+/*** Post a reply or internal note to a ticket.*diff --git a/services/mcp/src/tools/generated/conversations.ts b/services/mcp/src/tools/generated/conversations.tsindex 405761e703bb..bf9071c9be86 100644--- a/services/mcp/src/tools/generated/conversations.ts+++ b/services/mcp/src/tools/generated/conversations.ts@@ -6,6 +6,9 @@ import {ConversationsTicketsListQueryParams,ConversationsTicketsMessagesListParams,ConversationsTicketsMessagesListQueryParams,+ ConversationsTicketsNotesDestroyParams,+ ConversationsTicketsNotesPartialUpdateBody,+ ConversationsTicketsNotesPartialUpdateParams,ConversationsTicketsPartialUpdateBody,ConversationsTicketsPartialUpdateParams,ConversationsTicketsReplyCreateBody,@@ -104,6 +107,49 @@ const conversationsTicketsMessagesRetrieve = (): ToolBase<},})+const ConversationsTicketsNotesDestroySchema = ConversationsTicketsNotesDestroyParams.omit({ project_id: true })++const conversationsTicketsNotesDestroy = (): ToolBase<typeof ConversationsTicketsNotesDestroySchema, unknown> => ({+ name: 'conversations-tickets-notes-destroy',+ schema: ConversationsTicketsNotesDestroySchema,+ handler: async (context: Context, params: z.infer<typeof ConversationsTicketsNotesDestroySchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<unknown>({+ method: 'DELETE',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/conversations/tickets/${encodeURIComponent(String(params.id))}/notes/${encodeURIComponent(String(params.message_id))}/`,+ })+ return result+ },+})++const ConversationsTicketsNotesPartialUpdateSchema = ConversationsTicketsNotesPartialUpdateParams.omit({+ project_id: true,+}).extend(ConversationsTicketsNotesPartialUpdateBody.shape)++const conversationsTicketsNotesPartialUpdate = (): ToolBase<+ typeof ConversationsTicketsNotesPartialUpdateSchema,+ Schemas.TicketMessage+> => ({+ name: 'conversations-tickets-notes-partial-update',+ schema: ConversationsTicketsNotesPartialUpdateSchema,+ handler: async (context: Context, params: z.infer<typeof ConversationsTicketsNotesPartialUpdateSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.message !== undefined) {+ body['message'] = params.message+ }+ if (params.rich_content !== undefined) {+ body['rich_content'] = params.rich_content+ }+ const result = await context.api.request<Schemas.TicketMessage>({+ method: 'PATCH',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/conversations/tickets/${encodeURIComponent(String(params.id))}/notes/${encodeURIComponent(String(params.message_id))}/`,+ body,+ })+ return result+ },+})+const ConversationsTicketsReplyCreateSchema = ConversationsTicketsReplyCreateParams.omit({ project_id: true }).extend(ConversationsTicketsReplyCreateBody.shape)@@ -246,6 +292,8 @@ const conversationsViewsList = (): ToolBase<export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'conversations-tickets-list': conversationsTicketsList,'conversations-tickets-messages-retrieve': conversationsTicketsMessagesRetrieve,+ 'conversations-tickets-notes-destroy': conversationsTicketsNotesDestroy,+ 'conversations-tickets-notes-partial-update': conversationsTicketsNotesPartialUpdate,'conversations-tickets-reply-create': conversationsTicketsReplyCreate,'conversations-tickets-retrieve': conversationsTicketsRetrieve,'conversations-tickets-update': conversationsTicketsUpdate,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-notes-destroy.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-notes-destroy.jsonnew file mode 100644index 000000000000..816c1de0e5fb--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-notes-destroy.json@@ -0,0 +1,15 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "id": {+ "description": "The ticket's UUID or its numeric ticket number.",+ "type": "string"+ },+ "message_id": {+ "description": "The UUID of the private note (comment) to edit or delete.",+ "type": "string"+ }+ },+ "required": ["id", "message_id"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-notes-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-notes-partial-update.jsonnew file mode 100644index 000000000000..94112396678c--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-notes-partial-update.json@@ -0,0 +1,23 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "id": {+ "description": "The ticket's UUID or its numeric ticket number.",+ "type": "string"+ },+ "message": {+ "description": "Updated note content in markdown.",+ "maxLength": 5000,+ "type": "string"+ },+ "message_id": {+ "description": "The UUID of the private note (comment) to edit or delete.",+ "type": "string"+ },+ "rich_content": {+ "description": "Optional TipTap rich content JSON. Omit or pass null to clear previous rich content so the thread falls back to the markdown message."+ }+ },+ "required": ["id", "message_id"],+ "type": "object"+}