: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(customer-analytics): display account email threads (#80802)
Arthur Moreira de Deusc63cccd6db27
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex e4ced00be398..2facae4bacc0 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5656,6 +5656,10 @@ snapshots:hash: v1.k794b7964.4b8d5226ee154debdf333ff93d65a90ca766bcb25951e1baf36affb8b84b548d.dWZSHssPc83RkHVE-JPJA562bJR7MUim2yfqhjfNE50scenes-app-customer-analytics-accounts--feature-gate-off--light:hash: v1.k794b7964.e8b91bf6a0dd1b5d31064f4cbb94e9791e999c210831c455a498d0c7cc7e6bbb.IkZPJrJz33sKS8zzKwoy8V3s0GvmKpe5EGYTCIljhLs+ scenes-app-customer-analytics-accounts--row-expanded-email-threads--dark:+ hash: v1.k794b7964.0b52a6a4b48bc77bd2f0cf6d4550c4ec9d5262aaf9ac1a1aee9e2e57f311bbf1.moW1nKPfmZWFyn0i-N8hewBU7i250wMB4P8xCmMt9w8+ scenes-app-customer-analytics-accounts--row-expanded-email-threads--light:+ hash: v1.k794b7964.da52699aac9e503b896aefe6f2b8926c4c01b2e13c3a4d258a7de31588b206e8.6CQEFoPFDYN-apCszpwMzOkbxEc8eK4Fvp4KJHaM9Dkscenes-app-customer-analytics-accounts--row-expanded-empty--dark:hash: v1.k794b7964.89995158723a826e4604ddfcf9681dc0c9b50f33219cfccd06ccce637fe1b65b.i40Oi8tI3Ey-wqAdh3EekF8ti9WEdjq6dx-6JQPSvA0scenes-app-customer-analytics-accounts--row-expanded-empty--light:diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 532da8e3026a..4b458300444b 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -592,6 +592,8 @@ SPECTACULAR_SETTINGS = {"IntegrationKindEnum": "posthog.models.integration.Integration.IntegrationKind","TicketStatusEnum": "products.conversations.backend.models.constants.Status","EmailChannelKindEnum": "products.conversations.backend.models.team_conversations_email_config.EmailChannelKind",+ "EmailThreadMessageDirectionEnum": "products.conversations.backend.models.email_thread.EmailThreadMessageDirection",+ "EmailThreadParticipantKindEnum": "products.conversations.backend.models.email_thread.EmailThreadParticipantKind",# Shared by Ticket.priority and TicketViewFilters.priority (same choice set)."TicketPriorityEnum": "products.conversations.backend.models.constants.Priority","TicketChannelFilterEnum": "products.conversations.backend.api.ticket_filters.TICKET_CHANNEL_FILTER_CHOICES",diff --git a/products/conversations/backend/facade/api.py b/products/conversations/backend/facade/api.pyindex 68c539985a39..4b5ed1abc6a0 100644--- a/products/conversations/backend/facade/api.py+++ b/products/conversations/backend/facade/api.py@@ -12,7 +12,7 @@ from typing import Any, Protocol, castfrom django.conf import settingsfrom django.db import transaction-from django.db.models import F, Prefetch+from django.db.models import F, Prefetch, QuerySetimport structlogfrom slack_sdk.errors import SlackApiError@@ -26,7 +26,6 @@ from posthog.temporal.common.client import sync_connectfrom products.conversations.backend.channel_summary_ids import build_channel_summary_workflow_idfrom products.conversations.backend.facade.types import (- AccountEmailThreadDetail as AccountEmailThreadDetail,AccountEmailThreadMessage as AccountEmailThreadMessage,AccountEmailThreadSummary as AccountEmailThreadSummary,EmailThreadAccountLinkInput as EmailThreadAccountLinkInput,@@ -360,7 +359,7 @@ def list_account_email_threads(offset: int = 0,limit: int = 50,) -> tuple[list[AccountEmailThreadSummary], int]:- participants = EmailThreadParticipant.objects.for_team(team_id).order_by("email")+ participants: QuerySet[EmailThreadParticipant] = EmailThreadParticipant.objects.for_team(team_id).order_by("email")threads = (EmailThread.objects.for_team(team_id).filter(account_links__team_id=team_id, account_links__account_id=account_id)@@ -385,12 +384,14 @@ def _email_thread_addresses(value: object) -> list[EmailThreadAddress]:return addresses-def get_account_email_thread(+def list_account_email_thread_messages(team_id: int,account_id: str,thread_id: str,-) -> AccountEmailThreadDetail | None:- participants = EmailThreadParticipant.objects.for_team(team_id).order_by("email")+ *,+ offset: int = 0,+ limit: int = 50,+) -> tuple[list[AccountEmailThreadMessage], int] | None:thread = (EmailThread.objects.for_team(team_id).filter(@@ -398,7 +399,6 @@ def get_account_email_thread(account_links__team_id=team_id,account_links__account_id=account_id,)- .prefetch_related(Prefetch("participants", queryset=participants, to_attr="facade_participants")).first())if thread is None:@@ -410,16 +410,9 @@ def get_account_email_thread(.select_related("comment").order_by("sent_at", "id"))- summary = _account_email_thread_summary(thread)- return AccountEmailThreadDetail(- id=summary.id,- subject=summary.subject,- preview=summary.preview,- first_message_at=summary.first_message_at,- last_message_at=summary.last_message_at,- message_count=summary.message_count,- participants=summary.participants,- messages=[+ count = messages.count()+ return (+ [AccountEmailThreadMessage(id=str(message.id),sent_at=message.sent_at,@@ -430,6 +423,7 @@ def get_account_email_thread(direction=message.direction,content=message.comment.content or "",)- for message in messages+ for message in messages[offset : offset + limit]],+ count,)diff --git a/products/conversations/backend/facade/types.py b/products/conversations/backend/facade/types.pyindex 50eda8380e1f..7a17fa288c80 100644--- a/products/conversations/backend/facade/types.py+++ b/products/conversations/backend/facade/types.py@@ -80,8 +80,3 @@ class AccountEmailThreadMessage:sender_authenticated: booldirection: strcontent: str---@dataclass(frozen=True)-class AccountEmailThreadDetail(AccountEmailThreadSummary):- messages: list[AccountEmailThreadMessage]diff --git a/products/conversations/backend/tests/test_email_thread_account_links.py b/products/conversations/backend/tests/test_email_thread_account_links.pyindex 252919c37ff6..ddc0c96bcc58 100644--- a/products/conversations/backend/tests/test_email_thread_account_links.py+++ b/products/conversations/backend/tests/test_email_thread_account_links.py@@ -5,7 +5,7 @@ from django.utils import timezonefrom posthog.models.comment import Commentfrom products.conversations.backend.facade.api import (- get_account_email_thread,+ list_account_email_thread_messages,list_account_email_threads,list_email_threads_for_account_matching,replace_email_thread_account_links,@@ -94,15 +94,16 @@ class TestEmailThreadAccountLinks(BaseTest):)summaries, count = list_account_email_threads(self.team.id, "account-1")- detail = get_account_email_thread(self.team.id, "account-1", str(self.thread.id))+ message_page = list_account_email_thread_messages(self.team.id, "account-1", str(self.thread.id))assert count == 1assert len(summaries) == 1assert summaries[0].subject == "Account review"- assert detail is not None- assert detail.id == str(self.thread.id)- assert detail.messages[0].content == "Latest update"- assert detail.messages[0].sender_authenticated is True- assert detail.messages[0].to_recipients[0].email == "[email protected]"+ assert message_page is not None+ messages, message_count = message_page+ assert message_count == 1+ assert messages[0].content == "Latest update"+ assert messages[0].sender_authenticated is True+ assert messages[0].to_recipients[0].email == "[email protected]"replace_email_thread_account_links(self.team.id,@@ -120,4 +121,4 @@ class TestEmailThreadAccountLinks(BaseTest):remaining = EmailThreadAccountLink.objects.for_team(self.team.id).get()assert remaining.account_external_id == "renamed-group-2"assert remaining.match_source == "person_group"- assert get_account_email_thread(self.team.id, "account-1", str(self.thread.id)) is None+ assert list_account_email_thread_messages(self.team.id, "account-1", str(self.thread.id)) is Nonediff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 252b6eafa5ad..e88ee655ab33 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -73,9 +73,15 @@ from posthog.models.tagged_item import TaggedItemfrom posthog.models.team import Teamfrom products.conversations.backend.facade.api import (+ AccountEmailThreadMessage as AccountEmailThreadMessage,+ AccountEmailThreadSummary as AccountEmailThreadSummary,+ EmailThreadAddress as EmailThreadAddress,+ EmailThreadParticipantSummary as EmailThreadParticipantSummary,SupportSlackChannelsUnavailable,SupportSlackNotConfigured,TicketSummary as TicketSummary,+ list_account_email_thread_messages,+ list_account_email_threads,list_account_tickets,trigger_immediate_channel_summary,)@@ -3464,6 +3470,37 @@ def get_account_support_tickets(return list_account_tickets(team_id, account.external_id, limit=limit)+def get_account_email_threads(+ team_id: int,+ account_id: str,+ user_access_control: "UserAccessControl",+ *,+ offset: int = 0,+ limit: int = 50,+) -> tuple[list[AccountEmailThreadSummary], int] | None:+ if get_accessible_account_id(team_id, account_id, user_access_control) is None:+ return None+ if not user_access_control.check_access_level_for_resource("ticket", "viewer"):+ raise ResourceForbiddenError()+ return list_account_email_threads(team_id, account_id, offset=offset, limit=limit)+++def get_account_email_thread_messages(+ team_id: int,+ account_id: str,+ thread_id: str,+ user_access_control: "UserAccessControl",+ *,+ offset: int = 0,+ limit: int = 50,+) -> tuple[list[AccountEmailThreadMessage], int] | None:+ if get_accessible_account_id(team_id, account_id, user_access_control) is None:+ return None+ if not user_access_control.check_access_level_for_resource("ticket", "viewer"):+ raise ResourceForbiddenError()+ return list_account_email_thread_messages(team_id, account_id, thread_id, offset=offset, limit=limit)++def list_calendar_sync_statuses(team_id: int) -> list[contracts.CalendarSyncStatus]:"""Sync state of every connected calendar for the team: last completed sync andwhether a run is currently in flight (started but not finished, within the syncdiff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.pyindex d86eb36aa744..92732273e24b 100644--- a/products/customer_analytics/backend/presentation/views/serializers.py+++ b/products/customer_analytics/backend/presentation/views/serializers.py@@ -28,7 +28,13 @@ from rest_framework_dataclasses.serializers import DataclassSerializerfrom posthog.api.shared import UserBasicSerializerfrom posthog.models import OrganizationMembership-from products.customer_analytics.backend.facade.api import TicketSummary+from products.customer_analytics.backend.facade.api import (+ AccountEmailThreadMessage,+ AccountEmailThreadSummary,+ EmailThreadAddress,+ EmailThreadParticipantSummary,+ TicketSummary,+)from products.customer_analytics.backend.facade.constants import (CUSTOM_PROPERTY_DISPLAY_TYPE_CHOICES,CUSTOM_PROPERTY_OPTION_COLORS,@@ -774,6 +780,117 @@ class SupportTicketSerializer(DataclassSerializer):fields = ["id", "ticket_number", "status", "last_message_at", "last_message_text", "deep_link"]+class EmailThreadParticipantSerializer(DataclassSerializer):+ email = serializers.EmailField(read_only=True, help_text="Email address of the thread participant.")+ display_name = serializers.CharField(+ read_only=True,+ allow_blank=True,+ help_text="Display name from the captured email headers.",+ )+ kind = serializers.ChoiceField(+ read_only=True,+ choices=[("internal", "Internal"), ("customer", "Customer")],+ help_text="Whether the participant belongs to the PostHog organization or the customer.",+ )++ class Meta:+ dataclass = EmailThreadParticipantSummary+ ref_name = "AccountEmailThreadParticipant"+ fields = ["email", "display_name", "kind"]+++class AccountEmailThreadSerializer(DataclassSerializer):+ id = serializers.UUIDField(read_only=True, help_text="UUID of the captured email thread.")+ subject = serializers.CharField(read_only=True, allow_blank=True, help_text="Email thread subject.")+ preview = serializers.CharField(+ read_only=True,+ allow_blank=True,+ help_text="Plain-text preview of the latest captured message.",+ )+ first_message_at = serializers.DateTimeField(+ read_only=True,+ allow_null=True,+ help_text="Source timestamp of the first captured message.",+ )+ last_message_at = serializers.DateTimeField(+ read_only=True,+ allow_null=True,+ help_text="Source timestamp of the latest captured message.",+ )+ message_count = serializers.IntegerField(+ read_only=True,+ help_text="Number of captured messages in the thread.",+ )+ participants = EmailThreadParticipantSerializer(+ many=True,+ read_only=True,+ help_text="Participants included in the email thread.",+ )++ class Meta:+ dataclass = AccountEmailThreadSummary+ ref_name = "AccountEmailThread"+ fields = [+ "id",+ "subject",+ "preview",+ "first_message_at",+ "last_message_at",+ "message_count",+ "participants",+ ]+++class EmailThreadAddressSerializer(DataclassSerializer):+ name = serializers.CharField(read_only=True, allow_blank=True, help_text="Name from the email header.")+ email = serializers.EmailField(read_only=True, help_text="Email address from the email header.")++ class Meta:+ dataclass = EmailThreadAddress+ ref_name = "AccountEmailThreadAddress"+ fields = ["name", "email"]+++class AccountEmailThreadMessageSerializer(DataclassSerializer):+ id = serializers.UUIDField(read_only=True, help_text="UUID of the captured email message.")+ sent_at = serializers.DateTimeField(read_only=True, help_text="Timestamp from the source email.")+ sender = EmailThreadAddressSerializer(read_only=True, help_text="Sender from the email From header.")+ to_recipients = EmailThreadAddressSerializer(+ many=True,+ read_only=True,+ help_text="Recipients from the email To header.",+ )+ cc_recipients = EmailThreadAddressSerializer(+ many=True,+ read_only=True,+ help_text="Recipients from the email Cc header.",+ )+ sender_authenticated = serializers.BooleanField(+ read_only=True,+ help_text="Whether Mailgun authentication verified the sender domain.",+ )+ direction = serializers.ChoiceField(+ read_only=True,+ choices=[("inbound", "Inbound"), ("outbound", "Outbound")],+ help_text="Whether PostHog received or sent the message.",+ )+ content = serializers.CharField(read_only=True, allow_blank=True, help_text="Plain-text email content.")++ class Meta:+ dataclass = AccountEmailThreadMessage+ ref_name = "AccountEmailThreadMessage"+ fields = [+ "id",+ "sent_at",+ "sender",+ "to_recipients",+ "cc_recipients",+ "sender_authenticated",+ "direction",+ "content",+ ]++class CalendarSyncStatusSerializer(DataclassSerializer):"""Sync state of one connected calendar (read-only)."""diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.pyindex 2eb3cfef2c87..f4c32149df0a 100644--- a/products/customer_analytics/backend/presentation/views/views.py+++ b/products/customer_analytics/backend/presentation/views/views.py@@ -25,6 +25,7 @@ from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schefrom rest_framework import mixins, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.exceptions import PermissionDenied, ValidationError+from rest_framework.pagination import LimitOffsetPaginationfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.throttling import UserRateThrottle@@ -50,6 +51,8 @@ from products.customer_analytics.backend.facade import api, contractsfrom products.customer_analytics.backend.facade.constants import CUSTOMER_ANALYTICS_FEATURE_REQUESTS_FLAGfrom products.customer_analytics.backend.presentation.views.serializers import (AccountChannelSummarySerializer,+ AccountEmailThreadMessageSerializer,+ AccountEmailThreadSerializer,AccountNotebookSerializer,AccountNoteSerializer,AccountRelationshipDefinitionSerializer,@@ -148,6 +151,11 @@ _ACCOUNT_ID_PARAM = OpenApiParameter(# NOTE: deliberately no class docstring — a docstring here is inherited as the ViewSets'# ``__doc__`` and drf-spectacular would surface it as every operation's description (the# model-backed viewsets had none), drifting the generated clients.+class AccountEmailThreadMessagePagination(LimitOffsetPagination):+ default_limit = 50+ max_limit = 200++class _FacadePaginationMixin:# Drives the standard ``LimitOffsetPagination`` envelope from a facade ``(page, count)``# result. The facade does the slicing (offset/limit), so we set the paginator's state@@ -1262,6 +1270,71 @@ class AccountViewSet(return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)return Response(SupportTicketSerializer(instance=tickets, many=True).data)+ @extend_schema(parameters=[_ACCOUNT_ID_PARAM], responses={200: AccountEmailThreadSerializer(many=True)})+ @action(methods=["GET"], detail=True, url_path="email_threads")+ def email_threads(self, request: Request, *args, **kwargs) -> Response:+ if api.get_accessible_account_id(self.team_id, self.kwargs["pk"], self.user_access_control) is None:+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)++ def fetch(offset: int, limit: int) -> tuple[list[api.AccountEmailThreadSummary], int]:+ try:+ result = api.get_account_email_threads(+ self.team_id,+ self.kwargs["pk"],+ self.user_access_control,+ offset=offset,+ limit=limit,+ )+ except api.ResourceForbiddenError:+ raise PermissionDenied()+ return result if result is not None else ([], 0)++ return self._paginate_via_facade(request, fetch, AccountEmailThreadSerializer)++ @extend_schema(+ operation_id="accounts_email_thread_messages_list",+ parameters=[_ACCOUNT_ID_PARAM],+ responses={200: AccountEmailThreadMessageSerializer(many=True)},+ )+ @action(+ methods=["GET"],+ detail=True,+ url_path=r"email_threads/(?P<thread_id>[^/.]+)",+ url_name="email-thread-detail",+ pagination_class=AccountEmailThreadMessagePagination,+ )+ def email_thread(self, request: Request, thread_id: str, *args, **kwargs) -> Response:+ try:+ parsed_thread_id = str(UUID(thread_id))+ except ValueError:+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)++ paginator = cast(LimitOffsetPagination, self.paginator)+ limit = paginator.get_limit(request)+ assert limit is not None+ offset = paginator.get_offset(request)+ try:+ result = api.get_account_email_thread_messages(+ self.team_id,+ self.kwargs["pk"],+ parsed_thread_id,+ self.user_access_control,+ offset=offset,+ limit=limit,+ )+ except api.ResourceForbiddenError:+ raise PermissionDenied()+ if result is None:+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)++ messages, count = result+ paginator.request = request+ paginator.limit = limit+ paginator.offset = offset+ paginator.count = count+ serializer = AccountEmailThreadMessageSerializer(instance=messages, many=True)+ return paginator.get_paginated_response(serializer.data)+@extend_schema(parameters=[_ACCOUNT_ID_PARAM,@@ -1302,7 +1375,7 @@ class AccountViewSet(return mixin_result# Ticket content behind an account-scoped viewset — a token holding only# account:read must not read it.- if view.action == "support_tickets":+ if view.action in {"support_tickets", "email_threads", "email_thread"}:return ["account:read", "ticket:read"]return Nonediff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.pyindex d968b3d89542..c6e1dd684dac 100644--- a/products/customer_analytics/backend/test/test_views.py+++ b/products/customer_analytics/backend/test/test_views.py@@ -1,3 +1,4 @@+from datetime import timedeltafrom uuid import uuid4import pytest@@ -14,12 +15,22 @@ from rest_framework import statusfrom posthog.constants import AvailableFeaturefrom posthog.models import Tag, TaggedItemfrom posthog.models.activity_logging.activity_log import ActivityLog+from posthog.models.comment import Commentfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team import Teamfrom posthog.models.user import Userfrom posthog.models.utils import generate_random_token_personal, hash_key_value+from products.conversations.backend.models import (+ EMAIL_THREAD_COMMENT_SCOPE,+ EmailThread,+ EmailThreadAccountLink,+ EmailThreadMessage,+ EmailThreadMessageDirection,+ EmailThreadParticipant,+ EmailThreadParticipantKind,+)from products.conversations.backend.models.ticket import Ticketfrom products.customer_analytics.backend.logic import relationships as relationships_logicfrom products.customer_analytics.backend.models import (@@ -2769,6 +2780,124 @@ class TestAccountSupportTicketViewSet(APIBaseTest):self.assertEqual(status.HTTP_403_FORBIDDEN, self.client.get(self.endpoint).status_code)+class TestAccountEmailThreadViewSet(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.account = Account.objects.unscoped().create(team=self.team, name="Acme Corp", external_id="acme-1")+ first_message_at = timezone.now() - timedelta(hours=1)+ last_message_at = timezone.now()+ self.thread = EmailThread.objects.for_team(self.team.id).create(+ team=self.team,+ canonical_thread_key="<[email protected]>",+ subject="Renewal planning",+ first_message_at=first_message_at,+ last_message_at=last_message_at,+ message_count=2,+ preview="Latest reply",+ )+ EmailThreadAccountLink.objects.for_team(self.team.id).create(+ team=self.team,+ thread=self.thread,+ account_id=str(self.account.id),+ account_external_id=self.account.external_id,+ match_source="email_domain",+ )+ EmailThreadParticipant.objects.for_team(self.team.id).create(+ team=self.team,+ thread=self.thread,+ email="[email protected]",+ display_name="Customer",+ kind=EmailThreadParticipantKind.CUSTOMER,+ )+ for index, sent_at in enumerate([last_message_at, first_message_at], start=1):+ comment = Comment.objects.create(+ team=self.team,+ scope=EMAIL_THREAD_COMMENT_SCOPE,+ item_id=str(self.thread.id),+ content=f"Message {index}",+ )+ EmailThreadMessage.objects.for_team(self.team.id).create(+ team=self.team,+ thread=self.thread,+ comment=comment,+ message_id=f"<message-{index}@example.com>",+ sent_at=sent_at,+ sender_email="[email protected]",+ sender_name="Customer",+ to_recipients=[{"name": "CSM", "email": "[email protected]"}],+ cc_recipients=[],+ direction=EmailThreadMessageDirection.INBOUND,+ source_type="mailgun",+ source_id=f"message-{index}",+ )+ self.endpoint = f"/api/environments/{self.team.id}/accounts/{self.account.id}/email_threads/"++ def test_list_keeps_messages_out_and_detail_paginates_by_source_time(self):+ list_response = self.client.get(self.endpoint)++ self.assertEqual(status.HTTP_200_OK, list_response.status_code, list_response.json())+ payload = list_response.json()+ self.assertEqual(payload["count"], 1)+ summary = payload["results"][0]+ self.assertEqual(summary["subject"], "Renewal planning")+ self.assertEqual(summary["message_count"], 2)+ self.assertNotIn("messages", summary)++ detail_response = self.client.get(f"{self.endpoint}{self.thread.id}/?limit=1&offset=0")++ self.assertEqual(status.HTTP_200_OK, detail_response.status_code, detail_response.json())+ self.assertEqual(detail_response.json()["count"], 2)+ self.assertEqual(+ [message["content"] for message in detail_response.json()["results"]],+ ["Message 2"],+ )++ second_page_response = self.client.get(f"{self.endpoint}{self.thread.id}/?limit=1&offset=1")+ self.assertEqual(status.HTTP_200_OK, second_page_response.status_code, second_page_response.json())+ self.assertEqual(+ [message["content"] for message in second_page_response.json()["results"]],+ ["Message 1"],+ )++ with patch(+ "products.customer_analytics.backend.presentation.views.views.AccountEmailThreadMessagePagination.max_limit",+ 1,+ ):+ capped_response = self.client.get(f"{self.endpoint}{self.thread.id}/?limit=10000")+ self.assertEqual(status.HTTP_200_OK, capped_response.status_code, capped_response.json())+ self.assertEqual(capped_response.json()["count"], 2)+ self.assertEqual(len(capped_response.json()["results"]), 1)++ self.assertEqual(status.HTTP_404_NOT_FOUND, self.client.get(f"{self.endpoint}not-a-uuid/").status_code)++ def test_user_without_ticket_access_cannot_read_email_summaries_or_bodies(self):+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ self.organization.save()+ viewer = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ membership = OrganizationMembership.objects.get(user=viewer, organization=self.organization)+ AccessControl.objects.create(+ team=self.team,+ resource="customer_analytics",+ resource_id=None,+ access_level="viewer",+ organization_member=membership,+ )+ AccessControl.objects.create(+ team=self.team,+ resource="ticket",+ resource_id=None,+ access_level="none",+ organization_member=membership,+ )+ self.client.force_login(viewer)++ self.assertEqual(status.HTTP_403_FORBIDDEN, self.client.get(self.endpoint).status_code)+ self.assertEqual(status.HTTP_403_FORBIDDEN, self.client.get(f"{self.endpoint}{self.thread.id}/").status_code)++class TestCalendarSyncViewSet(APIBaseTest):def _become_admin(self):self.organization_membership.level = OrganizationMembership.Level.ADMINdiff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex 76ce58edf6be..eaeb56eebb2b 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -25,7 +25,7 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_TABLE_DATA_NODE_KEY, acc│ AccountsOverviewTilesButton + AccountsColumnConfigurator on the right├── AccountsOverviewTiles metric tiles across the filtered set└── AccountsTable the DataTable; keyed row renderers; controlled row expansion- └── AccountNotebooksExpansion expanded row: sidebar (Useful links + active-relationships summary) + LemonTabs(Notes/Users/Relationships/Usage/Spend/Opportunities/Summaries/Support tickets/Meetings/Event stream)+ └── AccountNotebooksExpansion expanded row: sidebar (Useful links + active-relationships summary) + LemonTabs(Notes/Users/Relationships/Usage/Spend/Opportunities/Summaries/Support tickets/Email threads/Meetings/Event stream)├── (notes) paginated/searchable/sortable LemonTable + "New note" button (accountNotebooksLogic, keyed by accountId)├── (users) AccountRelatedUsersExpansion (accountRelatedUsersLogic, keyed by externalId)├── (relationships) AccountRelationshipsExpansion (accountRelationshipsLogic, keyed by accountId — full assignment timeline, paginated; assign/end controls + definition filter, current assignments sorted on top)@@ -34,6 +34,7 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_TABLE_DATA_NODE_KEY, acc└── (opportunities) AccountOpportunitiesExpansion (accountOpportunitiesLogic, keyed by accountId — DWH Salesforce opportunities)└── (summaries) AccountSummariesExpansion (accountSummariesLogic, keyed by accountId — periodic AI summaries of the account's Slack channel, plus the cadence opt-in)└── (support_tickets) AccountSupportTicketsExpansion (accountSupportTicketsLogic, keyed by accountId — conversations support tickets, via the accounts/:id/support_tickets endpoint)+ └── (email_threads) AccountEmailThreadsExpansion (accountEmailThreadsLogic, keyed by accountId — matched Conversations email threads, with paginated summaries and message detail loaded on expansion)└── (meetings) AccountMeetingsExpansion (accountMeetingsLogic, keyed by accountId — synced Google Calendar meetings via the accounts/:id/meetings endpoint, plus the matching editor; flag-gated tab, CUSTOMER_ANALYTICS_CSP)└── (event_stream) AccountEventStreamToggle (`../EventStream/`) flag-gated tab (CUSTOMER_ANALYTICS_CSP); membership toggle for the Slack event stream```@@ -54,6 +55,7 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_TABLE_DATA_NODE_KEY, acc| `accountOpportunitiesLogic` | Salesforce opportunities behind the Opportunities tab (keyed by `accountId`): fetches the account's `sfdc_id`, then queries the data-warehouse `salesforce.opportunity` table via HogQL. Degrades to an empty state (not an error) when the table is absent — it's production-only. || `accountSummariesLogic` | The Summaries tab (keyed by `accountId`): fetches the account (for its linked `slack_channel_id` and `slack_summary_cadence`) plus the first page of the `accountsSummariesList` endpoint, navigates server pages via `loadSummariesPage` (5 per page, `page` reducer; each page replaces the last), holds per-summary collapse state (`expandedSummaryIds` / `toggleSummaryExpanded`), and owns the cadence opt-in (`setCadence` PATCHes the account through `accountsPartialUpdate`, guarded by a `cadenceSaving` flag). Turning the cadence on with no summaries yet starts `generatingFirstSummary` polling (`startFirstSummaryPolling` / `stopFirstSummaryPolling`, two `cache.disposables` keys) so the backfill the backend kicks off appears without a refresh; the poll deadline lives in a module-level map keyed by account id, because this logic unmounts whenever its row collapses while the backfill keeps running. Distinguishes not-loaded / no-channel-linked / generating / loaded-empty / load-failed; captures unexpected failures. || `accountSupportTicketsLogic` | Conversations support tickets behind the Support tickets tab (keyed by `accountId`): fetches the account's tickets from the generated `accountsSupportTicketsList` endpoint (backed by the customer-analytics facade → conversations facade → `Ticket`s matched on `organization_id = external_id`). Distinguishes not-loaded / loaded-empty / load-failed; captures unexpected failures. |+| `accountEmailThreadsLogic` | Matched email communication behind the Email threads tab (keyed by `accountId`): fetches server-paginated summaries from `accountsEmailThreadsList`, keeps one row expanded, and fetches paginated ordered messages through `accountsEmailThreadMessagesList`. The current message page is cached while the row remains expanded; list and detail failures leave explicit retry guidance instead of an infinite skeleton. || `accountMeetingsLogic` | The Meetings tab (keyed by `accountId`): fetches synced calendar meetings from the generated `accountsMeetingsList` endpoint (customer-analytics facade `get_account_meetings` over the `Meeting` model, populated by the Google Calendar Temporal sync). Distinguishes not-loaded / loaded-empty / load-failed; captures unexpected failures. Also owns the project-admin-gated "Edit matching" editor: `email_domains` / `known_emails` drafts, normalization (trim, lowercase, strip a leading `@`, dedupe), and `saveMatching` — merges them into the account's `properties` via `accountsPartialUpdate` (guarded by `savingMatching`) and propagates the updated account through `accountLinksLogic.loadAccountSuccess` (it connects to that logic for the account instead of fetching its own copy). || `accountLinksLogic` | The "Useful links" sidebar for one account (keyed by `accountId`). |@@ -108,9 +110,9 @@ Sort safety: removing the sorted column drops the sort (`clearSortIfColumnRemove## The expanded row-`AccountsTable.useExpandable()` makes expansion **controlled** by `accountsExpansionLogic`: `isRowExpanded` reads `expandedAccountIds`, `onRowExpand`/`onRowCollapse` dispatch `toggleAccountExpanded`. The body is `AccountNotebooksExpansion`, a `LemonTabs` over `notes` / `users` / `relationships` / `usage` / `spend` / `opportunities` / `summaries` / `support_tickets` / `event_stream` (`AccountExpansionTab`; the `event_stream` tab is gated by the `CUSTOMER_ANALYTICS_CSP` flag) plus the sidebar (Useful links + an active-relationships summary, `ActiveRelationships`, hidden when nothing is assigned). Active tab comes from `activeTabFor(accountId)` (defaults to `notes`).+`AccountsTable.useExpandable()` makes expansion **controlled** by `accountsExpansionLogic`: `isRowExpanded` reads `expandedAccountIds`, `onRowExpand`/`onRowCollapse` dispatch `toggleAccountExpanded`. The body is `AccountNotebooksExpansion`, a `LemonTabs` over `notes` / `users` / `relationships` / `usage` / `spend` / `opportunities` / `summaries` / `support_tickets` / `email_threads` / `meetings` / `event_stream` (`AccountExpansionTab`; the `event_stream` tab is gated by the `CUSTOMER_ANALYTICS_CSP` flag) plus the sidebar (Useful links + an active-relationships summary, `ActiveRelationships`, hidden when nothing is assigned). Active tab comes from `activeTabFor(accountId)` (defaults to `notes`).-**Tab data is cached for the row's expanded lifetime, not refetched per tab switch.** `LemonTabs` only renders the active tab's content (keyed by `activeKey`), so a tab's logic would normally unmount the moment you switch away and refetch on return. To avoid that, `AccountNotebooksExpansion` holds a mount reference to each per-tab logic via `useMountedLogic` — `accountRelatedUsersLogic({ externalId })`, `accountRelationshipsLogic({ accountId })`, `accountBillingLogic` for both `kind: 'usage'` and `kind: 'spend'`, `accountOpportunitiesLogic({ accountId })`, `accountSummariesLogic({ accountId })`, `accountSupportTicketsLogic({ accountId })`, and `accountMeetingsLogic({ accountId })`. Since `AccountNotebooksExpansion` stays mounted for as long as the row is expanded (it's the `expandedRowRender` body), those keyed instances survive tab switches and only tear down when the row collapses. The `useMountedLogic` props must stay identical to the `useValues` props in the tab components (`AccountRelatedUsersExpansion`, `AccountRelationshipsExpansion`, `AccountBillingExpansion`, `AccountOpportunitiesExpansion`, `AccountSummariesExpansion`, `AccountSupportTicketsExpansion`, `AccountMeetingsExpansion`) so both resolve to the same keyed instance. `accountNotebooksLogic` and `accountLinksLogic` already mount at this level (Notes content and the always-rendered sidebar), so they need no explicit mount reference. Data is loaded once on mount and not auto-refreshed while the row stays open — acceptable since this data needn't be live.+**Tab data is cached for the row's expanded lifetime, not refetched per tab switch.** `LemonTabs` only renders the active tab's content (keyed by `activeKey`), so a tab's logic would normally unmount the moment you switch away and refetch on return. To avoid that, `AccountNotebooksExpansion` holds a mount reference to each per-tab logic via `useMountedLogic` — `accountRelatedUsersLogic({ externalId })`, `accountRelationshipsLogic({ accountId })`, `accountBillingLogic` for both `kind: 'usage'` and `kind: 'spend'`, `accountOpportunitiesLogic({ accountId })`, `accountSummariesLogic({ accountId })`, `accountSupportTicketsLogic({ accountId })`, `accountEmailThreadsLogic({ accountId })`, and `accountMeetingsLogic({ accountId })`. Since `AccountNotebooksExpansion` stays mounted for as long as the row is expanded (it's the `expandedRowRender` body), those keyed instances survive tab switches and only tear down when the row collapses. The `useMountedLogic` props must stay identical to the `useValues` props in the tab components (`AccountRelatedUsersExpansion`, `AccountRelationshipsExpansion`, `AccountBillingExpansion`, `AccountOpportunitiesExpansion`, `AccountSummariesExpansion`, `AccountSupportTicketsExpansion`, `AccountEmailThreadsExpansion`, `AccountMeetingsExpansion`) so both resolve to the same keyed instance. `accountNotebooksLogic` and `accountLinksLogic` already mount at this level (Notes content and the always-rendered sidebar), so they need no explicit mount reference. Data is loaded once on mount and not auto-refreshed while the row stays open — acceptable since this data needn't be live.The Users tab reads its loaded data straight off `accountRelatedUsersLogic`, so the root mount above keeps it cached. The **Usage/Spend** tabs are different: `accountBillingLogic` only holds the saved-insight _metadata_ — the actual insight **results** live in the `dataNodeLogic`/`dataVisualizationLogic` mounted inside the tab body, which the root mount does **not** keep alive. So the tab body attaches those data logics to the (root-mounted) `accountBillingLogic` via `useAttachedLogic` — `AccountBillingChart` does this for the chart it renders, and the fallback `<Query>` path does it via `attachTo={accountBillingLogic-instance}` — so they outlive the tab body unmounting on tab switch and only detach when the row collapses. Without that attachment, usage/spend refetch on every return to the tab even with the metadata logic mounted. (The Opportunities tab loads its data in `accountOpportunitiesLogic` directly, not via an embedded query, so the root `useMountedLogic` above is enough — it needs no attachment.)@@ -143,6 +145,8 @@ An account with no `external_id` simply returns an empty list (the backend shortEach ticket row links to the ticket in the conversations UI via the `deep_link` the backend builds (`{SITE_URL}/project/<team>/support/tickets/<ticket_number>`), firing `SupportTicketClicked`.Like Opportunities, it loads directly in the logic (no embedded query), so the root `useMountedLogic` is enough — no `useAttachedLogic` needed.+The Email threads tab lists matched customer communication from Conversations. `accountEmailThreadsLogic` fetches paginated summaries that include subject, preview, customer participants, owner, message count, and latest activity. Expanding one row fetches messages in server-bounded pages and renders them in source-timestamp order. The list endpoint never includes message bodies. Both list and detail endpoints require account viewer access plus ticket viewer access because subjects, previews, addresses, and bodies are customer communication. The logic reports unexpected failures without including any email content in analytics or exception metadata.+The Meetings tab (flag-gated, `CUSTOMER_ANALYTICS_CSP`) lists the account's synced Google Calendar meetings from the `accounts/:id/meetings` endpoint — rows are written by the calendar-sync Temporal workflow (`backend/logic/calendar_sync.py`) from calendars connected in Customer analytics settings, and attach to an account via known emails → person resolution → email domains.`accountMeetingsLogic` owns three states like the Support tickets tab (skeleton on first load / load-failed / "no meetings yet"), plus **server-side pagination and search** (like the Users tab: `page` + `searchTerm` feed the endpoint's `limit`/`offset`/`search` params; search debounces, resets to page 1, and fires `MeetingsSearched`), the **attendee cell** state (first 3 attendees shown, "+N more"/"show less" toggles `expandedAttendeeMeetingIds`; attendees with a resolved `person_id` — populated by the sync via the same HogQL person-email lookup the account matching uses — get a leading `ProfilePicture` (xs, gravatar-by-email) and link to their person page, firing `MeetingAttendeeClicked`; each attendee carries a minimal RSVP glyph after the name — green check accepted, red x declined, muted "?" tentative, nothing for needs_action), and the project-admin-gated **"Edit matching" inline panel**: two `LemonInputSelect` chip inputs editing the account's `email_domains` and `known_emails` properties (normalized, merged into `properties` via `accountsPartialUpdate`, propagated through `accountLinksLogic.loadAccountSuccess`).The matching editor is deliberately an inline panel above the table, not a dropdown — the `LemonInputSelect` suggestion popover opens below the inputs and would cover Save/Cancel inside a small overlay, so the buttons sit beside the inputs instead.@@ -233,6 +237,19 @@ The tool is registered for the page regardless of agent mode. The Customer analy- `products/customer_analytics/backend/max_tools/` — `OpenAccountTool` and other account Max tools.- `ee/hogai/core/agent_modes/presets/customer_analytics.py` — the Customer analytics agent mode (gated by the `customer-analytics-csp` flag).+## Devbox setup for account tabs++Use a full devbox stack when checking account tabs against real product routing and permissions.++1. Check out the feature branch on the devbox and wait for the app stack.+2. Run `python manage.py sync_feature_flags`. This creates local flags from `frontend/src/lib/constants.tsx`, including `customer-analytics-roadmap`; `sync_feature_flags_from_api` alone does not create that local-only gate.+3. Configure group analytics at index 0 before seeding. The standard demo workspace already maps `project` to index 0; verify with `get_group_types_for_project` when using another workspace.+4. Run `python manage.py seed_customer_analytics_accounts --team-id <team_id>`. It creates accounts from index-0 groups, configures Customer Analytics for that group type, and adds sample relationships and notes.+5. Restart the backend after syncing flags so local flag evaluation reloads them.+6. Open `/project/<team_id>/customer_analytics/accounts` and confirm the seeded group appears as an account.++The seed command does not create communication data. For the Email threads tab, capture a message through the Mailgun flow or add an invented local thread linked to one seeded account.+## Conventions- **kea, not hooks** — business logic lives in the logics above; components are thin views. The one DOM concession is the `data-account-id` anchor for scroll. Resources needing cleanup (the scroll poll) go through `cache.disposables`, never a bare `setTimeout` + `beforeUnmount`.@@ -275,7 +292,7 @@ We track user actions on the Accounts list with `posthog.capture()`. Conventions| `customer analytics accounts note created` | `accountNotebooksLogic` `createNoteSuccess` listener | `notebook_short_id` || `customer analytics accounts notes searched` | `accountNotebooksLogic` `setSearchTerm` listener (post-debounce) | `has_query`, `query_length` (no raw text) || `customer analytics accounts notes sorted` | `accountNotebooksLogic` `setSorting` listener | `column` (`created_at` \| `created_by` \| null), `direction` (`asc` \| `desc` \| `cleared`) |-| `customer analytics account tab viewed` | `accountsExpansionLogic` `setActiveTab` listener (genuine tab clicks only; programmatic `openAccountTab` navigation does not fire it) | `tab` (`notes` \| `users` \| `relationships` \| `usage` \| `spend` \| `opportunities` \| `summaries` \| `support_tickets` \| `meetings` \| `event_stream`) |+| `customer analytics account tab viewed` | `accountsExpansionLogic` `setActiveTab` listener (genuine tab clicks only; programmatic `openAccountTab` navigation does not fire it) | `tab` (`notes` \| `users` \| `relationships` \| `usage` \| `spend` \| `opportunities` \| `summaries` \| `support_tickets` \| `email_threads` \| `meetings` \| `event_stream`) || `customer analytics account usage series toggled` | `accountBillingLogic` `toggleHiddenSeriesKey` listener (dispatched by the `AccountBillingSeriesToggle` chips) | `kind` (`usage` \| `spend`), `is_hidden` (the post-click state), `series_count` (no series label / no PII) || `customer analytics account usage series bulk toggled` | `accountBillingLogic` `setAllSeriesHidden` listener (dispatched by the Select all / Clear all buttons in `AccountBillingSeriesToggle`) | `kind` (`usage` \| `spend`), `is_hidden` (`true` when hiding all, `false` when showing all), `series_count` (no series label / no PII) || `customer analytics account related user clicked` | `AccountRelatedUsersExpansion.tsx` user `<Link>` `onClick` | _(none — customer end-user PII kept out)_ |diff --git a/products/customer_analytics/frontend/components/Accounts/AccountEmailThreadsExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountEmailThreadsExpansion.tsxnew file mode 100644index 000000000000..8dbf3689cef9--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/AccountEmailThreadsExpansion.tsx@@ -0,0 +1,224 @@+import { useActions, useValues } from 'kea'++import { LemonCard, LemonSkeleton, LemonTable, LemonTableColumns, LemonTag, Tooltip } from '@posthog/lemon-ui'++import { BigLeaguesHog } from 'lib/components/hedgehogs'+import { TZLabel } from 'lib/components/TZLabel'+import { PaginationControl } from 'lib/lemon-ui/PaginationControl'++import type {+ AccountEmailThreadApi,+ AccountEmailThreadMessageApi,+ AccountEmailThreadParticipantApi,+ PaginatedAccountEmailThreadMessageListApi,+} from 'products/customer_analytics/frontend/generated/api.schemas'++import { accountEmailThreadsLogic, MESSAGE_PAGE_SIZE, NOT_LOADED, PAGE_SIZE } from './accountEmailThreadsLogic'++const COLLAPSED_PARTICIPANT_COUNT = 3++function EmailThreadsEmptyState({ title, detail }: { title: string; detail: string }): JSX.Element {+ return (+ <div className="flex flex-col items-center justify-center gap-2 p-8 text-center">+ <BigLeaguesHog className="w-24 h-24" />+ <h4 className="mb-0">{title}</h4>+ <p className="text-secondary max-w-sm mb-0">{detail}</p>+ </div>+ )+}++function participantLabel(participant: AccountEmailThreadParticipantApi): string {+ return participant.display_name || participant.email+}++function ParticipantList({ participants }: { participants: readonly AccountEmailThreadParticipantApi[] }): JSX.Element {+ const customerParticipants = participants.filter((participant) => participant.kind === 'customer')+ const shown = customerParticipants.slice(0, COLLAPSED_PARTICIPANT_COUNT)+ const hiddenCount = customerParticipants.length - shown.length++ if (shown.length === 0) {+ return <span className="text-muted">No customer participants</span>+ }++ return (+ <span>+ {shown.map((participant, index) => (+ <span key={participant.email} title={participant.email}>+ {participantLabel(participant)}+ {index < shown.length - 1 ? ', ' : ''}+ </span>+ ))}+ {hiddenCount > 0 ? `, +${hiddenCount} more` : null}+ </span>+ )+}++function recipientSummary(message: AccountEmailThreadMessageApi): string {+ const recipients = [...message.to_recipients, ...message.cc_recipients]+ return recipients.map((recipient) => recipient.name || recipient.email).join(', ')+}++function EmailMessage({ message }: { message: AccountEmailThreadMessageApi }): JSX.Element {+ const sender = message.sender.name || message.sender.email+ const recipients = recipientSummary(message)+ return (+ <LemonCard hoverEffect={false} className="p-3 flex flex-col gap-2">+ <div className="flex flex-wrap items-start justify-between gap-2">+ <div className="flex flex-col min-w-0">+ <span className="font-semibold truncate" title={message.sender.email}>+ {sender}+ </span>+ {recipients ? (+ <span className="text-xs text-secondary truncate" title={recipients}>+ To: {recipients}+ </span>+ ) : null}+ </div>+ <div className="flex items-center gap-2 shrink-0">+ {message.direction === 'inbound' && !message.sender_authenticated ? (+ <Tooltip title="PostHog couldn't verify this sender's domain. Check the sender before sharing account details.">+ <LemonTag type="warning">Unverified sender</LemonTag>+ </Tooltip>+ ) : null}+ <LemonTag type={message.direction === 'outbound' ? 'primary' : 'default'}>+ {message.direction === 'outbound' ? 'Outgoing' : 'Incoming'}+ </LemonTag>+ <TZLabel time={message.sent_at} />+ </div>+ </div>+ <div className="whitespace-pre-wrap break-words text-sm">{message.content}</div>+ </LemonCard>+ )+}++function ThreadDetail({ accountId, threadId }: { accountId: string; threadId: string }): JSX.Element {+ const logic = accountEmailThreadsLogic({ accountId })+ const { threadDetails, threadDetailsLoading, threadDetailErrors, threadDetailPages } = useValues(logic)+ const { setThreadDetailPage } = useActions(logic)+ const detail: PaginatedAccountEmailThreadMessageListApi | undefined = threadDetails[threadId]+ const page = threadDetailPages[threadId] ?? 1++ if (threadDetailsLoading[threadId] || (!detail && !threadDetailErrors[threadId])) {+ return <LemonSkeleton className="h-40 w-full" />+ }+ if (threadDetailErrors[threadId]) {+ return (+ <EmailThreadsEmptyState+ title="Couldn't load this email thread"+ detail="Collapse the thread and open it again. If it still doesn't load, refresh the page."+ />+ )+ }+ if (!detail) {+ return <></>+ }+ return (+ <div className="flex flex-col gap-2 py-2" data-attr="account-email-thread-detail">+ {detail.results.map((message) => (+ <EmailMessage key={message.id} message={message} />+ ))}+ <PaginationControl+ pagination={{ controlled: true, pageSize: MESSAGE_PAGE_SIZE }}+ currentPage={page}+ setCurrentPage={(newPage) => setThreadDetailPage(threadId, newPage)}+ pageCount={Math.max(1, Math.ceil(detail.count / MESSAGE_PAGE_SIZE))}+ dataSourcePage={detail.results}+ entryCount={detail.count}+ currentStartIndex={(page - 1) * MESSAGE_PAGE_SIZE}+ currentEndIndex={(page - 1) * MESSAGE_PAGE_SIZE + detail.results.length}+ nouns={['message', 'messages']}+ />+ </div>+ )+}++export function AccountEmailThreadsExpansion({ accountId }: { accountId: string }): JSX.Element {+ const logic = accountEmailThreadsLogic({ accountId })+ const { threadsResult, threadsResultLoading, page, expandedThreadId } = useValues(logic)+ const { setPage, openThread, closeThread } = useActions(logic)++ if (threadsResult === NOT_LOADED || threadsResultLoading) {+ return <LemonSkeleton className="h-64 w-full" />+ }++ const { threads, count, loadFailed } = threadsResult+ if (loadFailed) {+ return (+ <EmailThreadsEmptyState+ title="Couldn't load email threads"+ detail="Refresh the page to try loading this account's email threads again."+ />+ )+ }+ if (count === 0) {+ return (+ <EmailThreadsEmptyState+ title="No email threads yet"+ detail="Forwarded customer email that matches this account will show up here."+ />+ )+ }++ const columns: LemonTableColumns<AccountEmailThreadApi> = [+ {+ title: 'Thread',+ key: 'subject',+ render: (_, thread) => (+ <div className="flex flex-col gap-1 py-1 max-w-xl">+ <span className="font-medium line-clamp-1">{thread.subject || 'No subject'}</span>+ {thread.preview ? <span className="text-xs text-muted line-clamp-1">{thread.preview}</span> : null}+ </div>+ ),+ },+ {+ title: 'Participants',+ key: 'participants',+ render: (_, thread) => <ParticipantList participants={thread.participants} />,+ },+ {+ title: 'Messages',+ key: 'message_count',+ align: 'right',+ render: (_, thread) => thread.message_count,+ },+ {+ title: 'Last activity',+ key: 'last_message_at',+ width: 150,+ render: (_, thread) =>+ thread.last_message_at ? (+ <TZLabel time={thread.last_message_at} />+ ) : (+ <span className="text-muted">Not available</span>+ ),+ },+ ]++ return (+ <LemonTable<AccountEmailThreadApi>+ data-attr="account-email-threads-table"+ size="small"+ embedded+ dataSource={threads ?? []}+ columns={columns}+ rowKey="id"+ tableLayout="fixed"+ pagination={{+ controlled: true,+ pageSize: PAGE_SIZE,+ currentPage: page,+ entryCount: count,+ onForward: () => setPage(page + 1),+ onBackward: () => setPage(page - 1),+ }}+ expandable={{+ expandedRowRender: (thread) => <ThreadDetail accountId={accountId} threadId={thread.id} />,+ isRowExpanded: (thread) => thread.id === expandedThreadId,+ onRowExpand: (thread) => openThread(thread.id),+ onRowCollapse: (thread) => closeThread(thread.id),+ rowExpandable: () => true,+ }}+ emptyState="No email threads on this page."+ />+ )+}diff --git a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsxindex c6afda8950d6..b3282cb7b0b3 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx@@ -37,6 +37,8 @@ import type { AccountNotebookApi } from 'products/customer_analytics/frontend/geimport { AccountEventStreamToggle } from '../EventStream/AccountEventStreamToggle'import { AccountBillingExpansion } from './AccountBillingExpansion'import { accountBillingLogic } from './accountBillingLogic'+import { AccountEmailThreadsExpansion } from './AccountEmailThreadsExpansion'+import { accountEmailThreadsLogic } from './accountEmailThreadsLogic'import { accountLinksLogic } from './accountLinksLogic'import { AccountMeetingsExpansion } from './AccountMeetingsExpansion'import { accountMeetingsLogic } from './accountMeetingsLogic'@@ -180,6 +182,7 @@ export function AccountNotebooksExpansion({useMountedLogic(accountOpportunitiesLogic({ accountId }))useMountedLogic(accountSummariesLogic({ accountId }))useMountedLogic(accountSupportTicketsLogic({ accountId }))+ useMountedLogic(accountEmailThreadsLogic({ accountId }))useMountedLogic(accountMeetingsLogic({ accountId }))const { setSearchTerm, setSorting, createNote } = useActions(logic)const { featureFlags } = useValues(featureFlagLogic)@@ -357,6 +360,11 @@ export function AccountNotebooksExpansion({label: 'Support tickets',content: <AccountSupportTicketsExpansion accountId={accountId} />,},+ {+ key: 'email_threads',+ label: 'Email threads',+ content: <AccountEmailThreadsExpansion accountId={accountId} />,+ },// Flag-gated here (not just inside the component) so the tab label hides too.!!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP] && {key: 'meetings' as const,diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsxindex 84d80314c676..dbdbebf1461f 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx@@ -9,9 +9,13 @@ import { urls } from 'scenes/urls'import { mswDecorator } from '~/mocks/browser'import type { MockResolverInfo } from '~/mocks/utils'+import type { PaginatedAccountEmailThreadListApi } from 'products/customer_analytics/frontend/generated/api.schemas'+const QUERY_ENDPOINT = '/api/environments/:team_id/query/:kind/'const ACCOUNT_RETRIEVE_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/'const ACCOUNT_NOTEBOOKS_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/notebooks/'+const ACCOUNT_EMAIL_THREADS_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/email_threads/'+const ACCOUNT_EMAIL_THREAD_DETAIL_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/email_threads/:thread_id/'const ACCOUNT_RELATIONSHIPS_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/relationships/'const RELATIONSHIP_DEFINITIONS_ENDPOINT = 'api/projects/:team_id/account_relationship_definitions/'const ORGANIZATION_MEMBERS_ENDPOINT = 'api/projects/:team_id/organization_members/'@@ -120,9 +124,15 @@ const ACCOUNT_WITHOUT_LINKS = {}const EMPTY_INSIGHTS = { count: 0, next: null, previous: null, results: [] }+const EMPTY_EMAIL_THREADS: PaginatedAccountEmailThreadListApi = {+ count: 0,+ next: null,+ previous: null,+ results: [],+}// Every fetch the expansion fires must be mocked (even if empty), because AccountNotebooksExpansion-// eagerly mounts the related-users, relationships, and usage/spend billing logics up front. An+// eagerly mounts the related-users, relationships, email-thread, and usage/spend billing logics up front. An// unhandled fetch passes through msw to the static storybook server and errors out, and the failure// re-render can collapse the expansion — making [data-attr="account-expansion"] disappear so the// post-play waitForSelector times out. The related-users failure also pops an error toast, which the@@ -131,6 +141,7 @@ const EXPANDED_ROW_FETCH_MOCKS = {[INSIGHTS_ENDPOINT]: EMPTY_INSIGHTS,[ORGANIZATION_MEMBERS_ENDPOINT]: { count: 0, next: null, previous: null, results: [] },[ACCOUNT_RELATIONSHIPS_ENDPOINT]: [],+ [ACCOUNT_EMAIL_THREADS_ENDPOINT]: EMPTY_EMAIL_THREADS,}// Billing tab stories share the same account + notebooks mocks; they differ only in the insight and query responses.@@ -153,11 +164,18 @@ function billingTabDecorators(]}-const EXPANDED_ROW_DECORATORS_BASE = [- mswDecorator({- get: EXPANDED_ROW_FETCH_MOCKS,- }),-]+function expandedRowDecorators(+ emailThreads: PaginatedAccountEmailThreadListApi = EMPTY_EMAIL_THREADS+): ReturnType<typeof mswDecorator>[] {+ return [+ mswDecorator({+ get: {+ ...EXPANDED_ROW_FETCH_MOCKS,+ [ACCOUNT_EMAIL_THREADS_ENDPOINT]: emailThreads,+ },+ }),+ ]+}// Expands the first row and asserts the expansion actually rendered. The click can race the table's// render cycle and be swallowed, so verify and re-click instead of trusting a single click — a lost@@ -299,7 +317,7 @@ export const RowExpandedEmpty: Story = {render: () => <App />,parameters: { testOptions: EXPANDED_ROW_TEST_OPTIONS },decorators: [- ...EXPANDED_ROW_DECORATORS_BASE,+ ...expandedRowDecorators(),mswDecorator({get: {[ACCOUNT_RETRIEVE_ENDPOINT]: ACCOUNT_WITH_LINKS,@@ -321,7 +339,7 @@ export const RowExpandedWithNote: Story = {render: () => <App />,parameters: { testOptions: EXPANDED_ROW_TEST_OPTIONS },decorators: [- ...EXPANDED_ROW_DECORATORS_BASE,+ ...expandedRowDecorators(),mswDecorator({get: {[ACCOUNT_RETRIEVE_ENDPOINT]: ACCOUNT_WITH_LINKS,@@ -369,11 +387,101 @@ export const RowExpandedWithNote: Story = {},}+export const RowExpandedEmailThreads: Story = {+ render: () => <App />,+ parameters: {+ testOptions: {+ ...EXPANDED_ROW_TEST_OPTIONS,+ waitForSelector: ['[data-attr="accounts-refresh"]', '[data-attr="account-email-thread-detail"]'],+ },+ },+ decorators: [+ ...expandedRowDecorators({+ count: 1,+ next: null,+ previous: null,+ results: [+ {+ id: '11111111-1111-1111-1111-111111111111',+ subject: 'Renewal planning',+ preview: 'I shared the revised timeline with the team.',+ first_message_at: '2026-05-20T09:00:00Z',+ last_message_at: '2026-05-20T11:30:00Z',+ message_count: 2,+ participants: [+ {+ email: '[email protected]',+ display_name: 'Example buyer',+ kind: 'customer',+ },+ ],+ },+ ],+ }),+ mswDecorator({+ get: {+ [ACCOUNT_RETRIEVE_ENDPOINT]: ACCOUNT_WITH_LINKS,+ [ACCOUNT_NOTEBOOKS_ENDPOINT]: { count: 0, next: null, previous: null, results: [] },+ [ACCOUNT_EMAIL_THREAD_DETAIL_ENDPOINT]: {+ count: 2,+ next: null,+ previous: null,+ results: [+ {+ id: '22222222-2222-2222-2222-222222222222',+ sent_at: '2026-05-20T09:00:00Z',+ sender: { name: 'Example buyer', email: '[email protected]' },+ to_recipients: [{ name: 'Alice Anderson', email: '[email protected]' }],+ cc_recipients: [],+ sender_authenticated: false,+ direction: 'inbound',+ content: 'Could you send the updated renewal timeline?',+ },+ {+ id: '33333333-3333-3333-3333-333333333333',+ sent_at: '2026-05-20T11:30:00Z',+ sender: { name: 'Alice Anderson', email: '[email protected]' },+ to_recipients: [{ name: 'Example buyer', email: '[email protected]' }],+ cc_recipients: [],+ sender_authenticated: true,+ direction: 'outbound',+ content: 'I shared the revised timeline with the team.',+ },+ ],+ },+ },+ post: {+ [QUERY_ENDPOINT]: mockAccountsTableQuery(SINGLE_ROW),+ },+ }),+ ],+ play: async ({ canvasElement }) => {+ await expandFirstRow(canvasElement)+ const canvas = within(canvasElement)+ await userEvent.click(await canvas.findByText('Email threads', {}, { timeout: 15000 }))+ await waitFor(+ () => {+ if (!canvasElement.querySelector('[data-attr="account-email-threads-table"]')) {+ throw new Error('Email threads table did not render')+ }+ },+ { timeout: 15000 }+ )+ const table = canvasElement.querySelector('[data-attr="account-email-threads-table"]') as HTMLElement+ await userEvent.click(await within(table).findByTitle('Show more'))+ await waitFor(() => {+ if (!canvasElement.querySelector('[data-attr="account-email-thread-detail"]')) {+ throw new Error('Email thread detail did not render')+ }+ })+ },+}+export const RowExpandedLinksDisabled: Story = {render: () => <App />,parameters: { testOptions: EXPANDED_ROW_TEST_OPTIONS },decorators: [- ...EXPANDED_ROW_DECORATORS_BASE,+ ...expandedRowDecorators(),mswDecorator({get: {[ACCOUNT_RETRIEVE_ENDPOINT]: ACCOUNT_WITHOUT_LINKS,diff --git a/products/customer_analytics/frontend/components/Accounts/accountEmailThreadsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountEmailThreadsLogic.test.tsnew file mode 100644index 000000000000..ee76ac5526fd--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/accountEmailThreadsLogic.test.ts@@ -0,0 +1,115 @@+import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'++import { initKeaTests } from '~/test/init'++import {+ accountsEmailThreadMessagesList,+ accountsEmailThreadsList,+} from 'products/customer_analytics/frontend/generated/api'+import type {+ AccountEmailThreadApi,+ PaginatedAccountEmailThreadMessageListApi,+} from 'products/customer_analytics/frontend/generated/api.schemas'++import { accountEmailThreadsLogic, MESSAGE_PAGE_SIZE, PAGE_SIZE } from './accountEmailThreadsLogic'++jest.mock('products/customer_analytics/frontend/generated/api', () => ({+ ...jest.requireActual('products/customer_analytics/frontend/generated/api'),+ accountsEmailThreadMessagesList: jest.fn(),+ accountsEmailThreadsList: jest.fn(),+}))++const mockList = accountsEmailThreadsList as jest.MockedFunction<typeof accountsEmailThreadsList>+const mockMessageList = accountsEmailThreadMessagesList as jest.MockedFunction<typeof accountsEmailThreadMessagesList>++const thread = {+ id: '11111111-1111-1111-1111-111111111111',+ subject: 'Account review',+ preview: 'Latest message',+ first_message_at: '2026-08-01T10:00:00Z',+ last_message_at: '2026-08-01T11:00:00Z',+ message_count: 2,+ participants: [],+} as AccountEmailThreadApi++const detail = {+ count: 1,+ next: null,+ previous: null,+ results: [+ {+ id: '22222222-2222-2222-2222-222222222222',+ sent_at: '2026-08-01T10:00:00Z',+ sender: { name: 'Customer', email: '[email protected]' },+ to_recipients: [],+ cc_recipients: [],+ sender_authenticated: true,+ direction: 'inbound',+ content: 'Message body',+ },+ ],+} as PaginatedAccountEmailThreadMessageListApi++describe('accountEmailThreadsLogic', () => {+ let logic: ReturnType<typeof accountEmailThreadsLogic.build>++ beforeEach(() => {+ initKeaTests()+ jest.resetAllMocks()+ jest.spyOn(posthog, 'captureException').mockReturnValue(undefined as any)+ mockList.mockResolvedValue({ count: 1, next: null, previous: null, results: [thread] })+ })++ afterEach(() => {+ logic?.unmount()+ })++ const mount = async (): Promise<void> => {+ logic = accountEmailThreadsLogic({ accountId: 'acc-1' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ }++ it('paginates summaries and loads message detail only when a thread opens', async () => {+ mockMessageList.mockResolvedValue(detail)+ await mount()++ expect(mockMessageList).not.toHaveBeenCalled()+ await expectLogic(logic, () => logic.actions.openThread(thread.id)).toFinishAllListeners()+ expect(logic.values.threadDetails[thread.id]).toEqual(detail)+ expect(mockMessageList).toHaveBeenCalledTimes(1)+ expect(mockMessageList).toHaveBeenLastCalledWith(expect.any(String), 'acc-1', thread.id, {+ limit: MESSAGE_PAGE_SIZE,+ offset: 0,+ })++ await expectLogic(logic, () => logic.actions.setThreadDetailPage(thread.id, 2)).toFinishAllListeners()+ expect(mockMessageList).toHaveBeenCalledTimes(2)+ expect(mockMessageList).toHaveBeenLastCalledWith(expect.any(String), 'acc-1', thread.id, {+ limit: MESSAGE_PAGE_SIZE,+ offset: MESSAGE_PAGE_SIZE,+ })++ logic.actions.closeThread(thread.id)+ await expectLogic(logic, () => logic.actions.openThread(thread.id)).toFinishAllListeners()+ expect(mockMessageList).toHaveBeenCalledTimes(2)++ await expectLogic(logic, () => logic.actions.setPage(2)).toFinishAllListeners()+ expect(mockList).toHaveBeenLastCalledWith(expect.any(String), 'acc-1', {+ limit: PAGE_SIZE,+ offset: PAGE_SIZE,+ })+ })++ it('records a detail error instead of leaving the expanded row loading', async () => {+ mockMessageList.mockRejectedValue(new Error('network'))+ await mount()++ await expectLogic(logic, () => logic.actions.openThread(thread.id)).toFinishAllListeners()++ expect(logic.values.threadDetailsLoading[thread.id]).toBe(false)+ expect(logic.values.threadDetailErrors[thread.id]).toBe(true)+ expect(posthog.captureException).toHaveBeenCalledTimes(1)+ })+})diff --git a/products/customer_analytics/frontend/components/Accounts/accountEmailThreadsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountEmailThreadsLogic.tsnew file mode 100644index 000000000000..6780ca8dc740--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/accountEmailThreadsLogic.ts@@ -0,0 +1,228 @@+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers } from 'kea'+import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'++import { teamLogic } from 'scenes/teamLogic'++import {+ accountsEmailThreadMessagesList,+ accountsEmailThreadsList,+} from 'products/customer_analytics/frontend/generated/api'+import type {+ AccountEmailThreadApi,+ PaginatedAccountEmailThreadMessageListApi,+} from 'products/customer_analytics/frontend/generated/api.schemas'++export const PAGE_SIZE = 10+export const MESSAGE_PAGE_SIZE = 50++export interface AccountEmailThreadsLogicProps {+ accountId: string+}++export interface AccountEmailThreadsResult {+ threads: AccountEmailThreadApi[] | null+ count: number+ loadFailed?: boolean+}++export const NOT_LOADED: AccountEmailThreadsResult = { threads: null, count: 0 }++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface accountEmailThreadsLogicValues {+ currentTeamId: number | null // teamLogic+ expandedThreadId: string | null+ page: number+ threadDetailErrors: Record<string, boolean>+ threadDetailPages: Record<string, number>+ threadDetails: Record<string, PaginatedAccountEmailThreadMessageListApi>+ threadDetailsLoading: Record<string, boolean>+ threadsResult: AccountEmailThreadsResult+ threadsResultLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface accountEmailThreadsLogicActions {+ closeThread: (threadId: string) => {+ threadId: string+ }+ loadThreadDetail: (threadId: string) => {+ threadId: string+ }+ loadThreadDetailFailure: (threadId: string) => {+ threadId: string+ }+ loadThreadDetailSuccess: (+ threadId: string,+ detail: PaginatedAccountEmailThreadMessageListApi+ ) => {+ detail: PaginatedAccountEmailThreadMessageListApi+ threadId: string+ }+ loadThreads: (_?: any) => any+ loadThreadsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadThreadsSuccess: (+ threadsResult: AccountEmailThreadsResult,+ payload?: any+ ) => {+ threadsResult: AccountEmailThreadsResult+ payload?: any+ }+ openThread: (threadId: string) => {+ threadId: string+ }+ setPage: (page: number) => {+ page: number+ }+ setThreadDetailPage: (+ threadId: string,+ page: number+ ) => {+ page: number+ threadId: string+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface accountEmailThreadsLogicMeta {+ key: string+}++export type accountEmailThreadsLogicType = MakeLogicType<+ accountEmailThreadsLogicValues,+ accountEmailThreadsLogicActions,+ AccountEmailThreadsLogicProps,+ accountEmailThreadsLogicMeta+>++export const accountEmailThreadsLogic = kea<accountEmailThreadsLogicType>([+ path((key) => ['scenes', 'customerAnalytics', 'accounts', 'accountEmailThreadsLogic', key]),+ props({} as AccountEmailThreadsLogicProps),+ key((props) => props.accountId),+ connect(() => ({+ values: [teamLogic, ['currentTeamId']],+ })),+ actions({+ setPage: (page: number) => ({ page }),+ openThread: (threadId: string) => ({ threadId }),+ closeThread: (threadId: string) => ({ threadId }),+ loadThreadDetail: (threadId: string) => ({ threadId }),+ loadThreadDetailSuccess: (threadId: string, detail: PaginatedAccountEmailThreadMessageListApi) => ({+ threadId,+ detail,+ }),+ loadThreadDetailFailure: (threadId: string) => ({ threadId }),+ setThreadDetailPage: (threadId: string, page: number) => ({ threadId, page }),+ }),+ loaders(({ props, values }) => ({+ threadsResult: [+ NOT_LOADED,+ {+ loadThreads: async (_ = null, breakpoint): Promise<AccountEmailThreadsResult> => {+ let response: Awaited<ReturnType<typeof accountsEmailThreadsList>>+ try {+ response = await accountsEmailThreadsList(String(values.currentTeamId), props.accountId, {+ limit: PAGE_SIZE,+ offset: (values.page - 1) * PAGE_SIZE,+ })+ } catch (error) {+ posthog.captureException(error as Error, {+ scope: 'accountEmailThreadsLogic.loadThreads',+ })+ return { threads: null, count: 0, loadFailed: true }+ }+ // Abort if a newer page load started while this request was in flight, so a slow+ // earlier page cannot resolve last and overwrite the page the user is now on.+ breakpoint()+ return { threads: [...response.results], count: response.count }+ },+ },+ ],+ })),+ reducers({+ page: [+ 1,+ {+ setPage: (_, { page }) => page,+ },+ ],+ expandedThreadId: [+ null as string | null,+ {+ openThread: (_, { threadId }) => threadId,+ closeThread: (state, { threadId }) => (state === threadId ? null : state),+ setPage: () => null,+ },+ ],+ threadDetails: [+ {} as Record<string, PaginatedAccountEmailThreadMessageListApi>,+ {+ loadThreadDetailSuccess: (state, { threadId, detail }) => ({ ...state, [threadId]: detail }),+ },+ ],+ threadDetailPages: [+ {} as Record<string, number>,+ {+ openThread: (state, { threadId }) => (state[threadId] ? state : { ...state, [threadId]: 1 }),+ setThreadDetailPage: (state, { threadId, page }) => ({ ...state, [threadId]: page }),+ },+ ],+ threadDetailsLoading: [+ {} as Record<string, boolean>,+ {+ loadThreadDetail: (state, { threadId }) => ({ ...state, [threadId]: true }),+ loadThreadDetailSuccess: (state, { threadId }) => ({ ...state, [threadId]: false }),+ loadThreadDetailFailure: (state, { threadId }) => ({ ...state, [threadId]: false }),+ },+ ],+ threadDetailErrors: [+ {} as Record<string, boolean>,+ {+ loadThreadDetail: (state, { threadId }) => ({ ...state, [threadId]: false }),+ loadThreadDetailSuccess: (state, { threadId }) => ({ ...state, [threadId]: false }),+ loadThreadDetailFailure: (state, { threadId }) => ({ ...state, [threadId]: true }),+ },+ ],+ }),+ listeners(({ actions, values, props }) => ({+ setPage: () => actions.loadThreads(),+ openThread: ({ threadId }) => {+ if (!values.threadDetails[threadId] && !values.threadDetailsLoading[threadId]) {+ actions.loadThreadDetail(threadId)+ }+ },+ setThreadDetailPage: ({ threadId }) => actions.loadThreadDetail(threadId),+ loadThreadDetail: async ({ threadId }, breakpoint) => {+ let detail: PaginatedAccountEmailThreadMessageListApi+ try {+ const page = values.threadDetailPages[threadId] ?? 1+ detail = await accountsEmailThreadMessagesList(+ String(values.currentTeamId),+ props.accountId,+ threadId,+ {+ limit: MESSAGE_PAGE_SIZE,+ offset: (page - 1) * MESSAGE_PAGE_SIZE,+ }+ )+ } catch (error) {+ posthog.captureException(error as Error, {+ scope: 'accountEmailThreadsLogic.loadThreadDetail',+ })+ actions.loadThreadDetailFailure(threadId)+ return+ }+ breakpoint()+ actions.loadThreadDetailSuccess(threadId, detail)+ },+ })),+ afterMount(({ actions }) => {+ actions.loadThreads()+ }),+])diff --git a/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.tsindex 804899831cca..bcfa2aa225d5 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts@@ -12,6 +12,7 @@ export type AccountExpansionTab =| 'opportunities'| 'summaries'| 'support_tickets'+ | 'email_threads'| 'meetings'| 'event_stream'@@ -24,6 +25,7 @@ export const ACCOUNT_EXPANSION_TABS: AccountExpansionTab[] = ['opportunities','summaries','support_tickets',+ 'email_threads','meetings','event_stream',]diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex 85d781795a08..f09755263f28 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -461,6 +461,112 @@ export interface PatchedAccountApi {readonly updated_at?: string | null}+/**+ * * `internal` - Internal+ * * `customer` - Customer+ */+export type EmailThreadParticipantKindEnumApi =+ (typeof EmailThreadParticipantKindEnumApi)[keyof typeof EmailThreadParticipantKindEnumApi]++export const EmailThreadParticipantKindEnumApi = {+ Internal: 'internal',+ Customer: 'customer',+} as const++export interface AccountEmailThreadParticipantApi {+ /** Email address of the thread participant. */+ readonly email: string+ /** Display name from the captured email headers. */+ readonly display_name: string+ /** Whether the participant belongs to the PostHog organization or the customer.+ *+ * * `internal` - Internal+ * * `customer` - Customer */+ readonly kind: EmailThreadParticipantKindEnumApi+}++export interface AccountEmailThreadApi {+ /** UUID of the captured email thread. */+ readonly id: string+ /** Email thread subject. */+ readonly subject: string+ /** Plain-text preview of the latest captured message. */+ readonly preview: string+ /**+ * Source timestamp of the first captured message.+ * @nullable+ */+ readonly first_message_at: string | null+ /**+ * Source timestamp of the latest captured message.+ * @nullable+ */+ readonly last_message_at: string | null+ /** Number of captured messages in the thread. */+ readonly message_count: number+ /** Participants included in the email thread. */+ readonly participants: readonly AccountEmailThreadParticipantApi[]+}++export interface PaginatedAccountEmailThreadListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: AccountEmailThreadApi[]+}++export interface AccountEmailThreadAddressApi {+ /** Name from the email header. */+ readonly name: string+ /** Email address from the email header. */+ readonly email: string+}++/**+ * * `inbound` - Inbound+ * * `outbound` - Outbound+ */+export type EmailThreadMessageDirectionEnumApi =+ (typeof EmailThreadMessageDirectionEnumApi)[keyof typeof EmailThreadMessageDirectionEnumApi]++export const EmailThreadMessageDirectionEnumApi = {+ Inbound: 'inbound',+ Outbound: 'outbound',+} as const++export interface AccountEmailThreadMessageApi {+ /** UUID of the captured email message. */+ readonly id: string+ /** Timestamp from the source email. */+ readonly sent_at: string+ /** Sender from the email From header. */+ readonly sender: AccountEmailThreadAddressApi+ /** Recipients from the email To header. */+ readonly to_recipients: readonly AccountEmailThreadAddressApi[]+ /** Recipients from the email Cc header. */+ readonly cc_recipients: readonly AccountEmailThreadAddressApi[]+ /** Whether Mailgun authentication verified the sender domain. */+ readonly sender_authenticated: boolean+ /** Whether PostHog received or sent the message.+ *+ * * `inbound` - Inbound+ * * `outbound` - Outbound */+ readonly direction: EmailThreadMessageDirectionEnumApi+ /** Plain-text email content. */+ readonly content: string+}++export interface PaginatedAccountEmailThreadMessageListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: AccountEmailThreadMessageApi[]+}+/*** One attendee of a synced calendar meeting (read-only).*/@@ -1997,6 +2103,28 @@ export type AccountsRelationshipsListParams = {include_history?: boolean}+export type AccountsEmailThreadsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}++export type AccountsEmailThreadMessagesListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}+export type AccountsMeetingsListParams = {/*** Number of results to return per page.diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.tsindex de36ea8d48f2..b148ec6b3f9b 100644--- a/products/customer_analytics/frontend/generated/api.ts+++ b/products/customer_analytics/frontend/generated/api.ts@@ -16,6 +16,8 @@ import type {AccountRelationshipDefinitionApi,AccountRelationshipDefinitionsListParams,AccountRelationshipWriteApi,+ AccountsEmailThreadMessagesListParams,+ AccountsEmailThreadsListParams,AccountsListParams,AccountsMeetingsListParams,AccountsNotebooksListParams,@@ -59,6 +61,8 @@ import type {GroupUsageMetricApi,GroupsTypesMetricsListParams,PaginatedAccountChannelSummaryListApi,+ PaginatedAccountEmailThreadListApi,+ PaginatedAccountEmailThreadMessageListApi,PaginatedAccountListApi,PaginatedAccountNoteListApi,PaginatedAccountNotebookListApi,@@ -563,6 +567,75 @@ export const accountsDestroy = async (projectId: string, id: string, options?: R})}+export const getAccountsEmailThreadsListUrl = (+ projectId: string,+ id: string,+ params?: AccountsEmailThreadsListParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/accounts/${id}/email_threads/?${stringifiedParams}`+ : `/api/projects/${projectId}/accounts/${id}/email_threads/`+}++export const accountsEmailThreadsList = async (+ projectId: string,+ id: string,+ params?: AccountsEmailThreadsListParams,+ options?: RequestInit+): Promise<PaginatedAccountEmailThreadListApi> => {+ return apiMutator<PaginatedAccountEmailThreadListApi>(getAccountsEmailThreadsListUrl(projectId, id, params), {+ ...options,+ method: 'GET',+ })+}++export const getAccountsEmailThreadMessagesListUrl = (+ projectId: string,+ id: string,+ threadId: string,+ params?: AccountsEmailThreadMessagesListParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/accounts/${id}/email_threads/${threadId}/?${stringifiedParams}`+ : `/api/projects/${projectId}/accounts/${id}/email_threads/${threadId}/`+}++export const accountsEmailThreadMessagesList = async (+ projectId: string,+ id: string,+ threadId: string,+ params?: AccountsEmailThreadMessagesListParams,+ options?: RequestInit+): Promise<PaginatedAccountEmailThreadMessageListApi> => {+ return apiMutator<PaginatedAccountEmailThreadMessageListApi>(+ getAccountsEmailThreadMessagesListUrl(projectId, id, threadId, params),+ {+ ...options,+ method: 'GET',+ }+ )+}+export const getAccountsMeetingsListUrl = (projectId: string, id: string, params?: AccountsMeetingsListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yamlindex 9e30f36ad543..b4a6855b2635 100644--- a/products/customer_analytics/mcp/tools.yaml+++ b/products/customer_analytics/mcp/tools.yaml@@ -178,6 +178,12 @@ tools:description: |Permanently delete a Customer Analytics account by id.feature_flag: customer-analytics-csp+ accounts-email-thread-messages-list:+ operation: accounts_email_thread_messages_list+ enabled: false+ accounts-email-threads-list:+ operation: accounts_email_threads_list+ enabled: falseaccounts-list:operation: accounts_listenabled: truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex a9917ae6e6d5..cf715962b29d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -329,6 +329,94 @@ export namespace Schemas {value?: (string | number | boolean)[] | string | number | boolean | null;}+ /**+ * * `internal` - Internal+ * * `customer` - Customer+ */+ export type EmailThreadParticipantKindEnum = typeof EmailThreadParticipantKindEnum[keyof typeof EmailThreadParticipantKindEnum];+++ export const EmailThreadParticipantKindEnum = {+ Internal: 'internal',+ Customer: 'customer',+ } as const;++ export interface AccountEmailThreadParticipant {+ /** Email address of the thread participant. */+ readonly email: string;+ /** Display name from the captured email headers. */+ readonly display_name: string;+ /** Whether the participant belongs to the PostHog organization or the customer.+ *+ * * `internal` - Internal+ * * `customer` - Customer */+ readonly kind: EmailThreadParticipantKindEnum;+ }++ export interface AccountEmailThread {+ /** UUID of the captured email thread. */+ readonly id: string;+ /** Email thread subject. */+ readonly subject: string;+ /** Plain-text preview of the latest captured message. */+ readonly preview: string;+ /**+ * Source timestamp of the first captured message.+ * @nullable+ */+ readonly first_message_at: string | null;+ /**+ * Source timestamp of the latest captured message.+ * @nullable+ */+ readonly last_message_at: string | null;+ /** Number of captured messages in the thread. */+ readonly message_count: number;+ /** Participants included in the email thread. */+ readonly participants: readonly AccountEmailThreadParticipant[];+ }++ export interface AccountEmailThreadAddress {+ /** Name from the email header. */+ readonly name: string;+ /** Email address from the email header. */+ readonly email: string;+ }++ /**+ * * `inbound` - Inbound+ * * `outbound` - Outbound+ */+ export type EmailThreadMessageDirectionEnum = typeof EmailThreadMessageDirectionEnum[keyof typeof EmailThreadMessageDirectionEnum];+++ export const EmailThreadMessageDirectionEnum = {+ Inbound: 'inbound',+ Outbound: 'outbound',+ } as const;++ export interface AccountEmailThreadMessage {+ /** UUID of the captured email message. */+ readonly id: string;+ /** Timestamp from the source email. */+ readonly sent_at: string;+ /** Sender from the email From header. */+ readonly sender: AccountEmailThreadAddress;+ /** Recipients from the email To header. */+ readonly to_recipients: readonly AccountEmailThreadAddress[];+ /** Recipients from the email Cc header. */+ readonly cc_recipients: readonly AccountEmailThreadAddress[];+ /** Whether Mailgun authentication verified the sender domain. */+ readonly sender_authenticated: boolean;+ /** Whether PostHog received or sent the message.+ *+ * * `inbound` - Inbound+ * * `outbound` - Outbound */+ readonly direction: EmailThreadMessageDirectionEnum;+ /** Plain-text email content. */+ readonly content: string;+ }+/*** * `engineering` - Engineering* * `data` - Data@@ -48229,6 +48317,24 @@ export namespace Schemas {results: AccountChannelSummary[];}+ export interface PaginatedAccountEmailThreadList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: AccountEmailThread[];+ }++ export interface PaginatedAccountEmailThreadMessageList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: AccountEmailThreadMessage[];+ }+export interface PaginatedAccountList {count: number;/** @nullable */@@ -82156,6 +82262,28 @@ export namespace Schemas {include_history?: boolean;};+ export type AccountsEmailThreadsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };++ export type AccountsEmailThreadMessagesListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };+export type AccountsMeetingsListParams = {/*** Number of results to return per page.