:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(conversations): let support users view full emails (#93588)
Alex V9e257b107453
diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.tsindex c799f326deec..6a25aa86f257 100644--- a/frontend/src/initKea.ts+++ b/frontend/src/initKea.ts@@ -56,6 +56,7 @@ const ERROR_FILTER_ALLOW_LIST = ['loadMonitoringSnapshot', // The managed warehouse Monitoring tab renders its own retry state'loadMonitoringSeries', // The managed warehouse Monitoring tab renders its own partial/error state'loadInstrumentationChecklist', // AI observability hides its checklist entirely rather than accusing a project on data it could not read+ 'loadFullEmail', // Its failure listener shows a retry toast and closes the modal]/*diff --git a/products/conversations/backend/api/email_events.py b/products/conversations/backend/api/email_events.pyindex e79c801bba50..e613fa7bb06c 100644--- a/products/conversations/backend/api/email_events.py+++ b/products/conversations/backend/api/email_events.py@@ -97,6 +97,7 @@ def _find_thread_ticket(message_id=in_reply_to,team_id=team_id,)+ .defer("full_body_plain").select_related("ticket").first())@@ -110,7 +111,9 @@ def _find_thread_ticket(for m in EmailMessageMapping.objects.filter(message_id__in=references,team_id=team_id,- ).select_related("ticket")+ )+ .defer("full_body_plain")+ .select_related("ticket")}for ref_id in reversed(references):if ref_id in mapping_by_id:@@ -542,6 +545,13 @@ def _process_support_email()body = email.body_with_matching_html(prefer_stripped=bool(existing_ticket))+ normalized_body_plain = email.body_plain.replace("\r\n", "\n").replace("\r", "\n").strip()+ normalized_display_body = body.text.replace("\r\n", "\n").replace("\r", "\n").strip()+ full_body_plain = (+ recover_links_from_html(email.body_plain, email.body_html)+ if normalized_body_plain and normalized_body_plain != normalized_display_body+ else None+ )content = recover_links_from_html(body.text, body.html)posthog_user = _resolve_team_member(sender_email, team) if email.sender_authenticated else None@@ -598,6 +608,7 @@ def _process_support_email("email_from_name": sender_name,"email_message_id": email.message_id,"email_attachments": attachments if attachments else None,+ "has_full_email_content": full_body_plain is not None,}comment = Comment.objects.create(@@ -632,6 +643,7 @@ def _process_support_email(team=team,ticket=ticket,comment=comment,+ full_body_plain=full_body_plain,)except IntegrityError:logger.info("email_inbound_duplicate_race", message_id=email.message_id)diff --git a/products/conversations/backend/api/tests/test_email_endpoints.py b/products/conversations/backend/api/tests/test_email_endpoints.pyindex 1b5c959e8453..1527b1dc714b 100644--- a/products/conversations/backend/api/tests/test_email_endpoints.py+++ b/products/conversations/backend/api/tests/test_email_endpoints.py@@ -30,6 +30,7 @@ from products.conversations.backend.models import (EmailChannelKind,EmailChannelSetup,EmailChannelSetupProvider,+ EmailMessageMapping,EmailOutboxMessage,)from products.conversations.backend.models.ticket import Ticket@@ -1681,7 +1682,12 @@ class TestEmailInboundContent(BaseTest):assert response.status_code == 200comment = Comment.objects.get(team=self.team, scope="conversations_ticket")+ mapping = EmailMessageMapping.objects.get(comment=comment)+ item_context = comment.item_context+ assert item_context is not Noneassert comment.content == expected_content+ assert item_context["has_full_email_content"] is False+ assert mapping.full_body_plain is None@patch("products.conversations.backend.api.email_events.validate_webhook_signature", return_value=True)def test_reply_strips_quoted_thread(self, _mock_sig: MagicMock):@@ -1709,6 +1715,75 @@ class TestEmailInboundContent(BaseTest):reply = Comment.objects.filter(team=self.team, scope="conversations_ticket").order_by("created_at")[1]assert reply.content == "Thanks, that worked"+ @parameterized.expand(+ [+ (+ "different_content",+ "I added the details below.\n\nUnsubscribe from this list.",+ "I added the details below.\n\nStep 1: open the report.\nStep 2: run it again."+ "\n\nOn Mon, Support wrote:\n> Initial question",+ (+ "<p>I added the details below.</p>"+ '<p>Step 1: open <a href="https://example.com/report">the report</a>.</p>'+ "<p>Step 2: run it again.</p>"+ "<blockquote>On Mon, Support wrote: Initial question</blockquote>"+ ),+ "I added the details below.\n\nStep 1: open [the report](https://example.com/report)."+ "\nStep 2: run it again.\n\nOn Mon, Support wrote:\n> Initial question",+ ),+ ("line_endings_only", "Same reply\nSame details", "Same reply\r\nSame details", "", None),+ ]+ )+ @patch("products.conversations.backend.api.email_events.validate_webhook_signature", return_value=True)+ def test_reply_full_body_preservation(+ self,+ _name: str,+ stripped_text: str,+ full_body_plain: str,+ body_html: str,+ expected_full_body: str | None,+ _mock_sig: MagicMock,+ ) -> None:+ base = {+ "recipient": "[email protected]",+ "from": "[email protected]",+ "subject": "Help",+ }+ self.client.post(+ "/api/conversations/v1/email/inbound",+ {**base, "Message-Id": "<[email protected]>", "stripped-text": "Initial question"},+ )++ response = self.client.post(+ "/api/conversations/v1/email/inbound",+ {+ **base,+ "Message-Id": f"<full-body-reply-{_name}@example.com>",+ "In-Reply-To": "<[email protected]>",+ "stripped-text": stripped_text,+ "body-plain": full_body_plain,+ "body-html": body_html,+ },+ )+ assert response.status_code == 200++ ticket = Ticket.objects.get(team=self.team)+ reply = Comment.objects.filter(team=self.team, scope="conversations_ticket").order_by("created_at")[1]+ mapping = EmailMessageMapping.objects.get(comment=reply)+ item_context = reply.item_context+ assert item_context is not None+ assert reply.content == stripped_text+ assert item_context["has_full_email_content"] is (expected_full_body is not None)+ assert mapping.full_body_plain == expected_full_body++ self.client.force_login(self.user)+ response = self.client.get(+ f"/api/projects/{self.team.id}/conversations/tickets/{ticket.id}/messages/{reply.id}/full_email/"+ )+ assert response.status_code == (200 if expected_full_body is not None else 404)+ if expected_full_body is not None:+ assert response.json() == {"content": expected_full_body}+class TestSendEmailReplyMultiConfig(BaseTest):def setUp(self):diff --git a/products/conversations/backend/api/tests/test_tickets.py b/products/conversations/backend/api/tests/test_tickets.pyindex 0be34f9ab1ad..f3aa6ba40845 100644--- a/products/conversations/backend/api/tests/test_tickets.py+++ b/products/conversations/backend/api/tests/test_tickets.py@@ -36,7 +36,14 @@ from products.access_control.backend.models.access_control import AccessControlfrom products.access_control.backend.models.role import Rolefrom products.conversations.backend.api.ticket_filters import query_params_to_view_filtersfrom products.conversations.backend.api.tickets import ComposeTicketSerializer, TicketReplyRequestSerializer-from products.conversations.backend.models import EmailChannel, EmailChannelKind, Ticket, TicketAssignment, TicketView+from products.conversations.backend.models import (+ EmailChannel,+ EmailChannelKind,+ EmailMessageMapping,+ Ticket,+ TicketAssignment,+ TicketView,+)from products.conversations.backend.models.constants import Channel, ChannelDetail, Priority, Statusfrom products.conversations.backend.person_lookup import PERSON_EMAIL_LOOKUP_QUERY, _get_persons_by_emailfrom products.conversations.backend.reply_dedupe import REPLY_IN_PROGRESS_ERROR_TYPE, ReplyFingerprint, reserve@@ -2095,6 +2102,20 @@ class TestTicketPersonalAPIKeyScopes(APIBaseTest):("messages_with_read", "messages", "get", ["ticket:read"], status.HTTP_200_OK),("messages_with_write", "messages", "get", ["ticket:write"], status.HTTP_200_OK),("messages_wrong_scope", "messages", "get", ["insight:read"], status.HTTP_403_FORBIDDEN),+ (+ "full_email_with_read",+ "messages/00000000-0000-0000-0000-000000000000/full_email",+ "get",+ ["ticket:read"],+ status.HTTP_404_NOT_FOUND,+ ),+ (+ "full_email_wrong_scope",+ "messages/00000000-0000-0000-0000-000000000000/full_email",+ "get",+ ["insight:read"],+ status.HTTP_403_FORBIDDEN,+ ),("reply_with_write", "reply", "post", ["ticket:write"], status.HTTP_201_CREATED),("reply_with_read_only", "reply", "post", ["ticket:read"], status.HTTP_403_FORBIDDEN),("reply_wrong_scope", "reply", "post", ["insight:write"], status.HTTP_403_FORBIDDEN),@@ -2245,6 +2266,7 @@ class TestTicketMessagesAPI(APIBaseTest):"author_type","author_name","is_private",+ "has_full_email_content","created_at","version",}@@ -2368,6 +2390,46 @@ class TestTicketMessagesAPI(APIBaseTest):assert body["results"] == []assert body["count"] == 0+ @parameterized.expand(+ [+ ("different_ticket", True, False),+ ("deleted_message", False, True),+ ]+ )+ def test_full_email_only_returns_visible_ticket_messages(+ self, mock_on_commit, _name: str, use_different_ticket: bool, deleted: bool+ ) -> None:+ ticket = self.ticket+ if use_different_ticket:+ ticket = Ticket.objects.create_with_number(+ team=self.team,+ channel_source=Channel.EMAIL,+ widget_session_id="other-session",+ distinct_id="user-2",+ status=Status.OPEN,+ )+ comment = Comment.objects.create(+ team=self.team,+ scope="conversations_ticket",+ item_id=str(ticket.id),+ content="Visible reply",+ item_context={"author_type": "customer", "has_full_email_content": True},+ deleted=deleted,+ )+ EmailMessageMapping.objects.create(+ message_id="<[email protected]>",+ team=self.team,+ ticket=ticket,+ comment=comment,+ full_body_plain="Full body",+ )++ response = self.client.get(+ f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/messages/{comment.id}/full_email/"+ )++ assert response.status_code == status.HTTP_404_NOT_FOUND+def test_messages_pagination(self, mock_on_commit):base = timezone.now()for i in range(5):diff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.pyindex c1248a5fb383..e14aeb8349f5 100644--- a/products/conversations/backend/api/tickets.py+++ b/products/conversations/backend/api/tickets.py@@ -31,6 +31,7 @@ from rest_framework import (from rest_framework.decorators import actionfrom rest_framework.exceptions import MethodNotAllowed, ValidationErrorfrom rest_framework.permissions import IsAuthenticated+from rest_framework.request import Requestfrom rest_framework.response import Responsefrom posthog.api.person import get_person_name@@ -73,7 +74,14 @@ from products.conversations.backend.events import (capture_ticket_status_changed,)from products.conversations.backend.metrics import TICKET_SEARCH_DURATION_SECONDS-from products.conversations.backend.models import EmailChannel, EmailChannelKind, Ticket, TicketAssignment, TicketView+from products.conversations.backend.models import (+ EmailChannel,+ EmailChannelKind,+ EmailMessageMapping,+ Ticket,+ TicketAssignment,+ TicketView,+)from products.conversations.backend.models.constants import Channel, ChannelDetail, Statusfrom products.conversations.backend.person_lookup import _get_persons_by_email@@ -114,10 +122,17 @@ class TicketMessageSerializer(serializers.Serializer):is_private = serializers.BooleanField(read_only=True, help_text="True for internal notes not visible to the customer.")+ has_full_email_content = serializers.BooleanField(+ read_only=True, help_text="True when the complete inbound email body can be retrieved."+ )version = serializers.IntegerField(read_only=True, help_text="Edit count. 0 means never edited.")created_at = serializers.DateTimeField(read_only=True)+class TicketFullEmailSerializer(serializers.Serializer):+ content = serializers.CharField(read_only=True, help_text="Full inbound email body in Markdown.")++class TicketNoteUpdateRequestSerializer(serializers.Serializer):"""Payload for updating a private note on a ticket."""@@ -505,6 +520,13 @@ NOTE_MESSAGE_ID_PARAM = OpenApiParameter(description="The UUID of the private note (comment) to edit or delete.",)+TICKET_MESSAGE_ID_PARAM = OpenApiParameter(+ name="message_id",+ type=OpenApiTypes.UUID,+ location=OpenApiParameter.PATH,+ description="The UUID of the ticket message.",+)+def _status_implied_by_snooze(before: datetime | None, after: datetime | None) -> str | None:"""Return the status a snooze change implies, or None when it implies no status change.@@ -612,7 +634,7 @@ class _TicketUpdateDiff:)class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.ModelViewSet):scope_object = "ticket"- scope_object_read_actions = ["list", "retrieve", "unread_count", "messages"]+ scope_object_read_actions = ["list", "retrieve", "unread_count", "messages", "full_email"]# "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 = [@@ -1287,6 +1309,51 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessControreturn self.get_paginated_response(data)return Response(data)+ @extend_schema(+ parameters=[TICKET_ID_PARAM, TICKET_MESSAGE_ID_PARAM],+ responses={+ 200: TicketFullEmailSerializer,+ 404: OpenApiResponse(response=TicketErrorSerializer),+ },+ )+ @action(+ detail=True,+ methods=["get"],+ url_path=r"messages/(?P<message_id>[^/.]+)/full_email",+ pagination_class=None,+ )+ def full_email(self, request: Request, message_id: str | None = None, *args: Any, **kwargs: Any) -> Response:+ """Return the full inbound email body in Markdown."""+ ticket = self.get_object()+ try:+ message_uuid = uuid.UUID(message_id or "")+ except ValueError:+ return Response(+ {"detail": "Full email not found.", "error_type": "full_email_not_found"},+ status=drf_status.HTTP_404_NOT_FOUND,+ )++ full_body_plain = (+ EmailMessageMapping.objects.filter(+ team_id=self.team_id,+ ticket=ticket,+ comment_id=message_uuid,+ comment__team_id=self.team_id,+ comment__scope="conversations_ticket",+ comment__item_id=str(ticket.id),+ comment__deleted=False,+ )+ .values_list("full_body_plain", flat=True)+ .first()+ )+ if full_body_plain is None:+ return Response(+ {"detail": "Full email not found.", "error_type": "full_email_not_found"},+ status=drf_status.HTTP_404_NOT_FOUND,+ )++ return Response(TicketFullEmailSerializer({"content": full_body_plain}).data)+def _serialize_message(self, comment: Comment, ticket: Ticket) -> dict:item_context = comment.item_context or {}author_type = item_context.get("author_type", "customer")@@ -1322,6 +1389,7 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessContro"author_type": author_type,"author_name": author_name,"is_private": item_context.get("is_private") is True,+ "has_full_email_content": item_context.get("has_full_email_content") is True,"version": comment.version,"created_at": comment.created_at,}diff --git a/products/conversations/backend/migrations/0063_emailmessagemapping_full_body_plain.py b/products/conversations/backend/migrations/0063_emailmessagemapping_full_body_plain.pynew file mode 100644index 000000000000..a1b762269e4b--- /dev/null+++ b/products/conversations/backend/migrations/0063_emailmessagemapping_full_body_plain.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.17 on 2026-09-02 14:50++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("conversations", "0062_emailthreadaccountlink"),+ ]++ operations = [+ migrations.AddField(+ model_name="emailmessagemapping",+ name="full_body_plain",+ field=models.TextField(blank=True, null=True),+ ),+ ]diff --git a/products/conversations/backend/migrations/max_migration.txt b/products/conversations/backend/migrations/max_migration.txtindex c184b66d8fcc..9395c1e8d242 100644--- a/products/conversations/backend/migrations/max_migration.txt+++ b/products/conversations/backend/migrations/max_migration.txt@@ -1 +1 @@-0062_emailthreadaccountlink\ No newline at end of file+0063_emailmessagemapping_full_body_plaindiff --git a/products/conversations/backend/models/email_message_mapping.py b/products/conversations/backend/models/email_message_mapping.pyindex d043c48c41da..4c4c39750bea 100644--- a/products/conversations/backend/models/email_message_mapping.py+++ b/products/conversations/backend/models/email_message_mapping.py@@ -10,6 +10,7 @@ class EmailMessageMapping(UUIDModel):team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE)comment = models.ForeignKey("posthog.Comment", on_delete=models.CASCADE)+ full_body_plain = models.TextField(blank=True, null=True)created_at = models.DateTimeField(auto_now_add=True)class Meta:diff --git a/products/conversations/backend/tasks.py b/products/conversations/backend/tasks.pyindex e0753f69ce27..34e603ba9f0a 100644--- a/products/conversations/backend/tasks.py+++ b/products/conversations/backend/tasks.py@@ -757,7 +757,10 @@ def _process_outbox_row(outbox: EmailOutboxMessage) -> None:# Build threading headers from the latest inbound message on this ticketlatest_mapping = (- EmailMessageMapping.objects.filter(ticket_id=ticket.id, team_id=outbox.team_id).order_by("-created_at").first()+ EmailMessageMapping.objects.filter(ticket_id=ticket.id, team_id=outbox.team_id)+ .only("message_id")+ .order_by("-created_at")+ .first())headers: dict[str, str] = {"Message-ID": outbox.message_id}if latest_mapping:diff --git a/products/conversations/frontend/components/Chat/ChatView.tsx b/products/conversations/frontend/components/Chat/ChatView.tsxindex 9b72c056487b..fd16a4566b4b 100644--- a/products/conversations/frontend/components/Chat/ChatView.tsx+++ b/products/conversations/frontend/components/Chat/ChatView.tsx@@ -70,6 +70,8 @@ export interface ChatViewProps {onEditMessage?: (message: ChatMessage) => voidonDeleteMessage?: (messageId: string) => voidonCancelEdit?: () => void+ fullEmailLoadingMessageId?: string | null+ onViewFullEmail?: (messageId: string) => void}export function ChatView({@@ -111,6 +113,8 @@ export function ChatView({onEditMessage,onDeleteMessage,onCancelEdit,+ fullEmailLoadingMessageId,+ onViewFullEmail,}: ChatViewProps): JSX.Element {const listMinHeight = minHeight ?? '400px'const listMaxHeight = maxHeight ?? '600px'@@ -139,6 +143,8 @@ export function ChatView({canEditTicket={canEditTicket}onEditMessage={onEditMessage}onDeleteMessage={onDeleteMessage}+ fullEmailLoadingMessageId={fullEmailLoadingMessageId}+ onViewFullEmail={onViewFullEmail}/><div className="border-t pt-3"><MessageInputdiff --git a/products/conversations/frontend/components/Chat/Message.test.tsx b/products/conversations/frontend/components/Chat/Message.test.tsxnew file mode 100644index 000000000000..b2c6f86cf88d--- /dev/null+++ b/products/conversations/frontend/components/Chat/Message.test.tsx@@ -0,0 +1,31 @@+import '@testing-library/jest-dom'++import { fireEvent, render, screen } from '@testing-library/react'++import type { ChatMessage } from '../../types'+import { Message } from './Message'++jest.mock('../Editor', () => ({+ SupportMarkdown: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,+ SupportRichContentPreview: () => null,+}))+jest.mock('../Editor/richContentToHtml', () => ({ richContentToHtml: () => null }))++describe('Message', () => {+ it('loads the preserved full email body when one is available', () => {+ const onViewFullEmail = jest.fn()+ const message: ChatMessage = {+ id: 'message-id',+ content: 'Visible reply',+ authorType: 'customer',+ authorName: 'Customer',+ createdAt: '2026-01-01T00:00:00Z',+ hasFullEmailContent: true,+ }++ render(<Message message={message} isCustomer onViewFullEmail={onViewFullEmail} />)++ fireEvent.click(screen.getByText('View full email'))+ expect(onViewFullEmail).toHaveBeenCalledTimes(1)+ })+})diff --git a/products/conversations/frontend/components/Chat/Message.tsx b/products/conversations/frontend/components/Chat/Message.tsxindex 1f80a74b39d3..85b5563f90f3 100644--- a/products/conversations/frontend/components/Chat/Message.tsx+++ b/products/conversations/frontend/components/Chat/Message.tsx@@ -31,6 +31,8 @@ export interface MessageProps {onSubmitAiReplyFeedback?: (rating: AiReplyFeedbackRating, feedbackText?: string) => voidonEdit?: () => voidonDelete?: () => void+ fullEmailLoading?: boolean+ onViewFullEmail?: () => void}export function Message({@@ -43,6 +45,8 @@ export function Message({onSubmitAiReplyFeedback,onEdit,onDelete,+ fullEmailLoading = false,+ onViewFullEmail,}: MessageProps): JSX.Element {const isAgent = message.authorType === 'AI'const profileType = isAgent ? 'bot' : 'person'@@ -180,6 +184,19 @@ export function Message({{message.content}</SupportMarkdown>)}+ {message.hasFullEmailContent && onViewFullEmail && (+ <div className="mt-2">+ <LemonButton+ type="tertiary"+ size="xsmall"+ onClick={onViewFullEmail}+ loading={fullEmailLoading}+ data-attr="support-ticket-view-full-email"+ >+ View full email+ </LemonButton>+ </div>+ )}</div>{showAiReplyFeedback && (<div className="mt-1.5 space-y-1.5">diff --git a/products/conversations/frontend/components/Chat/MessageList.tsx b/products/conversations/frontend/components/Chat/MessageList.tsxindex e559b365fbc7..ba360c1b7c77 100644--- a/products/conversations/frontend/components/Chat/MessageList.tsx+++ b/products/conversations/frontend/components/Chat/MessageList.tsx@@ -39,6 +39,8 @@ export interface MessageListProps {canEditTicket?: booleanonEditMessage?: (message: ChatMessage) => voidonDeleteMessage?: (messageId: string) => void+ fullEmailLoadingMessageId?: string | null+ onViewFullEmail?: (messageId: string) => void}/** A non-message entry in the thread, e.g. an agent's findings. `at` is what orders it among the@@ -71,6 +73,8 @@ export function MessageList({canEditTicket = false,onEditMessage,onDeleteMessage,+ fullEmailLoadingMessageId = null,+ onViewFullEmail,}: MessageListProps): JSX.Element {const messagesEndRef = useRef<HTMLDivElement>(null)const containerRef = useRef<HTMLDivElement>(null)@@ -231,6 +235,12 @@ export function MessageList({}onEdit={canModify && onEditMessage ? () => onEditMessage(message) : undefined}onDelete={canModify && onDeleteMessage ? () => onDeleteMessage(message.id) : undefined}+ fullEmailLoading={fullEmailLoadingMessageId === message.id}+ onViewFullEmail={+ onViewFullEmail && message.hasFullEmailContent+ ? () => onViewFullEmail(message.id)+ : undefined+ }/>),}diff --git a/products/conversations/frontend/generated/api.schemas.ts b/products/conversations/frontend/generated/api.schemas.tsindex 69a8535a90fb..47aea9cf4ff2 100644--- a/products/conversations/frontend/generated/api.schemas.ts+++ b/products/conversations/frontend/generated/api.schemas.ts@@ -397,6 +397,8 @@ export interface TicketMessageApi {readonly author_name: string/** True for internal notes not visible to the customer. */readonly is_private: boolean+ /** True when the complete inbound email body can be retrieved. */+ readonly has_full_email_content: boolean/** Edit count. 0 means never edited. */readonly version: numberreadonly created_at: string@@ -411,6 +413,16 @@ export interface PaginatedTicketMessageListApi {results: TicketMessageApi[]}+export interface TicketFullEmailApi {+ /** Full inbound email body in Markdown. */+ readonly content: string+}++export interface TicketErrorApi {+ detail: string+ error_type?: string+}+/*** Payload for updating a private note on a ticket.*/@@ -424,11 +436,6 @@ export interface PatchedTicketNoteUpdateRequestApi {rich_content?: unknown}-export interface TicketErrorApi {- detail: string- error_type?: string-}-/*** Payload for posting a reply or internal note to a ticket.*/diff --git a/products/conversations/frontend/generated/api.ts b/products/conversations/frontend/generated/api.tsindex 4c3c2b08d63e..5786ce1e1f8b 100644--- a/products/conversations/frontend/generated/api.ts+++ b/products/conversations/frontend/generated/api.ts@@ -26,6 +26,7 @@ import type {PatchedTicketUpdateRequestApi,PatchedTicketViewApi,TicketApi,+ TicketFullEmailApi,TicketMessageApi,TicketReplyRequestApi,TicketUpdateRequestApi,@@ -209,6 +210,32 @@ export const conversationsTicketsMessagesList = async (})}+export const getConversationsTicketsMessagesFullEmailRetrieveUrl = (+ projectId: string,+ id: string,+ messageId: string+) => {+ return `/api/projects/${projectId}/conversations/tickets/${id}/messages/${messageId}/full_email/`+}++/**+ * Return the full inbound email body in Markdown.+ */+export const conversationsTicketsMessagesFullEmailRetrieve = async (+ projectId: string,+ id: string,+ messageId: string,+ options?: RequestInit+): Promise<TicketFullEmailApi> => {+ return apiMutator<TicketFullEmailApi>(+ getConversationsTicketsMessagesFullEmailRetrieveUrl(projectId, id, messageId),+ {+ ...options,+ method: 'GET',+ }+ )+}+export const getConversationsTicketsNotesPartialUpdateUrl = (projectId: string, id: string, messageId: string) => {return `/api/projects/${projectId}/conversations/tickets/${id}/notes/${messageId}/`}diff --git a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsxindex f8f61fb6cfea..80a18d683574 100644--- a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx+++ b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx@@ -3,7 +3,7 @@ import { combineUrl, router } from 'kea-router'import { useRef } from 'react'import { IconChevronDown } from '@posthog/icons'-import { LemonButton, LemonCard, LemonSelect, LemonTag, Link, Spinner } from '@posthog/lemon-ui'+import { LemonButton, LemonCard, LemonModal, LemonSelect, LemonTag, Link, Spinner } from '@posthog/lemon-ui'import { AccessControlAction } from 'lib/components/AccessControlAction'import { Resizer } from 'lib/components/Resizer/Resizer'@@ -27,6 +27,7 @@ import { AccessControlLevel, AccessControlResourceType, Breadcrumb } from '~/typimport { AssigneeIconDisplay, AssigneeLabelDisplay, AssigneeSelect } from '../../components/Assignee'import { ChannelsTag, getChannelThreadUrl } from '../../components/Channels/ChannelsTag'import { ChatView } from '../../components/Chat/ChatView'+import { SupportMarkdown } from '../../components/Editor'import { IdentityBadge } from '../../components/IdentityBadge/IdentityBadge'import { SlaDisplay } from '../../components/SlaDisplay/SlaDisplay'import { TicketTags } from '../../components/TicketTags'@@ -109,6 +110,9 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.ElemfeedbackByMessageId,editingMessageId,discussionsEnabled,+ fullEmailContent,+ fullEmailContentLoading,+ fullEmailMessageId,} = 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@@ -132,6 +136,8 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.ElemstartEditingMessage,cancelEditingMessage,deleteMessage,+ loadFullEmail,+ closeFullEmail,} = useActions(logic)const { user } = useValues(userLogic)@@ -230,6 +236,17 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.ElemresourceType={{ type: 'conversation' }}forceBackTo={ticketListBackTo(searchParams)}/>+ <LemonModal title="Full email" isOpen={fullEmailMessageId !== null} onClose={closeFullEmail}>+ {fullEmailContentLoading ? (+ <div className="flex h-40 items-center justify-center">+ <Spinner />+ </div>+ ) : (+ <div className="max-h-96 overflow-y-auto break-words text-sm">+ <SupportMarkdown disableImages>{fullEmailContent ?? ''}</SupportMarkdown>+ </div>+ )}+ </LemonModal><div className="flex flex-col lg:flex-row items-start lg:min-h-0 lg:flex-1"><div@@ -275,6 +292,8 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.ElemonEditMessage={startEditingMessage}onDeleteMessage={deleteMessage}onCancelEdit={cancelEditingMessage}+ fullEmailLoadingMessageId={fullEmailContentLoading ? fullEmailMessageId : null}+ onViewFullEmail={loadFullEmail}/><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 7db577d1ab15..d7df3bdf26fe 100644--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts@@ -3,6 +3,8 @@ import { MOCK_DEFAULT_USER } from '~/lib/api.mock'import { expectLogic } from 'kea-test-utils'import posthog from 'posthog-js'+import { lemonToast } from '@posthog/lemon-ui'+import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { commentsLogic } from 'scenes/comments/commentsLogic'@@ -62,6 +64,7 @@ jest.mock('products/business_knowledge/frontend/generated/api', () => ({}))jest.mock('products/conversations/frontend/generated/api', () => ({+ conversationsTicketsMessagesFullEmailRetrieve: jest.fn().mockResolvedValue({ content: 'Full email body' }),conversationsTicketsNotesPartialUpdate: jest.fn().mockResolvedValue(undefined),conversationsTicketsNotesDestroy: jest.fn().mockResolvedValue(undefined),conversationsTicketsPartialUpdate: jest.fn(),@@ -70,11 +73,13 @@ jest.mock('products/conversations/frontend/generated/api', () => ({import api from '~/lib/api'import {+ conversationsTicketsMessagesFullEmailRetrieve,conversationsTicketsNotesPartialUpdate,conversationsTicketsPartialUpdate,} from 'products/conversations/frontend/generated/api'const submitAiFeedbackMock = api.conversationsTickets.submitAiFeedback as jest.Mock+const fullEmailRetrieveMock = conversationsTicketsMessagesFullEmailRetrieve as jest.Mockfunction makeAiComment(id: string, isPrivate: boolean = true): CommentType {return {@@ -225,11 +230,12 @@ function makeCustomerComment(id: string, itemContext: Record<string, any> = {}):} as unknown as CommentType}-describe('supportTicketSceneLogic chatMessages author attribution', () => {+describe('supportTicketSceneLogic chatMessages mapping', () => {let logic: ReturnType<typeof supportTicketSceneLogic.build>beforeEach(() => {initKeaTests()+ fullEmailRetrieveMock.mockClear()logic = supportTicketSceneLogic({ id: 'new' })logic.mount()logic.actions.setTicket({ ...makeTicket(), anonymous_traits: { name: 'Mark' } } as Ticket)@@ -245,6 +251,29 @@ describe('supportTicketSceneLogic chatMessages author attribution', () => {logic.actions.setMessages([makeCustomerComment('msg-1', itemContext)])expect(logic.values.chatMessages[0].authorName).toBe(expectedName)})++ it('loads the full email when the inbound message retained one', async () => {+ logic.actions.setMessages([makeCustomerComment('msg-1', { has_full_email_content: true })])+ expect(logic.values.chatMessages[0].hasFullEmailContent).toBe(true)++ logic.actions.loadFullEmail('msg-1')+ await expectLogic(logic).toFinishAllListeners()++ expect(fullEmailRetrieveMock).toHaveBeenCalledWith(expect.any(String), 'ticket-1', 'msg-1')+ expect(logic.values.fullEmailContent).toBe('Full email body')+ })++ it('closes the full email modal and shows a retry message when loading fails', async () => {+ const errorToast = jest.spyOn(lemonToast, 'error').mockReturnValue('' as never)+ fullEmailRetrieveMock.mockRejectedValueOnce(new Error('Network failure'))++ logic.actions.loadFullEmail('msg-1')+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.fullEmailMessageId).toBeNull()+ expect(errorToast).toHaveBeenCalledWith("Couldn't load the full email. Try again.")+ errorToast.mockRestore()+ })})describe('supportTicketSceneLogic AI note visibility', () => {diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.tsindex cf3a24731b3b..d813b3fd137f 100644--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts@@ -49,6 +49,7 @@ import {businessKnowledgeGapSuggestionsList,} from 'products/business_knowledge/frontend/generated/api'import {+ conversationsTicketsMessagesFullEmailRetrieve,conversationsTicketsNotesDestroy,conversationsTicketsNotesPartialUpdate,conversationsTicketsPartialUpdate,@@ -248,6 +249,9 @@ export interface supportTicketSceneLogicValues {eventsQuery: DataTableNode | nullexceptionsQuery: DataTableNode | nullfeedbackByMessageId: Record<string, AiReplyFeedbackRating>+ fullEmailContent: string | null+ fullEmailContentLoading: boolean+ fullEmailMessageId: string | nullhasMoreMessages: booleanhasPendingWork: booleanhasUnsavedChanges: boolean@@ -293,6 +297,9 @@ export interface supportTicketSceneLogicActions {clearEditingMessage: () => {value: true}+ closeFullEmail: () => {+ value: true+ }deleteMessage: (messageId: string) => {messageId: string}@@ -302,6 +309,21 @@ export interface supportTicketSceneLogicActions {incrementUnreadCustomerCount: () => {value: true}+ loadFullEmail: (messageId: string) => string+ loadFullEmailFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadFullEmailSuccess: (+ fullEmailContent: string,+ payload?: string+ ) => {+ fullEmailContent: string+ payload?: string+ }loadKnowledgeGaps: () => {value: true}@@ -524,11 +546,7 @@ export interface supportTicketSceneLogicMeta {unsavedTicketChanges: string[]) => booleanhasPendingWork: (hasUnsavedChanges: boolean, editingMessageId: string | null) => boolean- chatMessages: (- messages: CommentType[],- ticket: Ticket | null,- featureFlags: FeatureFlagsSet // featureFlagLogic- ) => ChatMessage[]+ chatMessages: (messages: CommentType[], ticket: Ticket | null, featureFlags: FeatureFlagsSet) => ChatMessage[]eventsQuery: (ticket: Ticket | null) => DataTableNode | nullexceptionsQuery: (ticket: Ticket | null) => DataTableNode | nulllatestAiMessage: (chatMessages: ChatMessage[]) => ChatMessage | null@@ -634,6 +652,7 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([messageId,rating,}),+ closeFullEmail: true,}),loaders(({ values, props }) => ({person: [@@ -750,6 +769,24 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([},},],+ fullEmailContent: [+ null as string | null,+ {+ loadFullEmail: async (messageId: string, breakpoint): Promise<string> => {+ const ticket = values.ticket+ if (!ticket) {+ throw new Error('Ticket is not loaded')+ }+ const response = await conversationsTicketsMessagesFullEmailRetrieve(+ String(getCurrentTeamId()),+ ticket.id,+ messageId+ )+ breakpoint()+ return response.content+ },+ },+ ],})),reducers({ticket: [@@ -776,6 +813,14 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([setTicketLoading: (_, { loading }) => loading,},],+ fullEmailMessageId: [+ null as string | null,+ {+ loadFullEmail: (_, messageId) => messageId,+ loadFullEmailFailure: () => null,+ closeFullEmail: () => null,+ },+ ],status: [null as TicketStatus | null,{@@ -1104,6 +1149,7 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([version: message.version,emailDeliveryStatus: message.item_context?.email_delivery_status,fromZendesk: message.item_context?.from_zendesk === true,+ hasFullEmailContent: message.item_context?.has_full_email_content === true,}})},@@ -1203,6 +1249,10 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([// Load previous tickets after person is loadedactions.loadPreviousTickets()},+ loadFullEmailFailure: () => {+ lemonToast.error("Couldn't load the full email. Try again.")+ actions.closeFullEmail()+ },updateTicket: async (_, breakpoint) => {if (props.id === 'new') {actions.setTicketUpdating(false)diff --git a/products/conversations/frontend/types.ts b/products/conversations/frontend/types.tsindex db4a537aa367..fadc1db4a5b2 100644--- a/products/conversations/frontend/types.ts+++ b/products/conversations/frontend/types.ts@@ -230,6 +230,7 @@ export interface ChatMessage {/** Imported from an external tool (e.g. Zendesk). Such content is untrusted, so its Markdown* is rendered with external image auto-loading disabled. */fromZendesk?: boolean+ hasFullEmailContent?: boolean}export const statusOptions: { value: TicketStatus | 'all'; label: string }[] = [diff --git a/products/conversations/mcp/tools.yaml b/products/conversations/mcp/tools.yamlindex 88886f071118..17327077a722 100644--- a/products/conversations/mcp/tools.yaml+++ b/products/conversations/mcp/tools.yaml@@ -60,6 +60,9 @@ tools:- unread_team_count- created_at- updated_at+ conversations-tickets-messages-full-email-retrieve:+ operation: conversations_tickets_messages_full_email_retrieve+ enabled: falseconversations-tickets-messages-retrieve:operation: conversations_tickets_messages_listenabled: truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex b31e82cfe7ef..84daf3d4312e 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -58586,6 +58586,8 @@ export namespace Schemas {readonly author_name: string;/** True for internal notes not visible to the customer. */readonly is_private: boolean;+ /** True when the complete inbound email body can be retrieved. */+ readonly has_full_email_content: boolean;/** Edit count. 0 means never edited. */readonly version: number;readonly created_at: string;@@ -85863,6 +85865,11 @@ export namespace Schemas {error_type?: string;}+ export interface TicketFullEmail {+ /** Full inbound email body in Markdown. */+ readonly content: string;+ }+/*** Payload for posting a reply or internal note to a ticket.*/