: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): unify account conversations (#86702)
Arthur Moreira de Deusf4ce2881e03a
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 9e78ff650720..f7f2ba0da322 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5788,10 +5788,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-apCszpwMzOkbxEc8eK4Fvp4KJHaM9Dk+ scenes-app-customer-analytics-accounts--row-expanded-conversations--dark:+ hash: v1.k794b7964.eb11e3e57318a64f00f2787930b0166cb4d0097e5331dda546d334957ab1cebd.zetLxjVqgzk7MOztZFxtX1iPBWQErA0Q-611MnOLSaA+ scenes-app-customer-analytics-accounts--row-expanded-conversations--light:+ hash: v1.k794b7964.e091729fb045a322490cbdb642b777c3f80f0b26db64eef74b35c63716d45a9d.Krd-pMnQ6xCttmsjdME-65PxLEt2-KnBPnVF_2rNNIoscenes-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/frontend/src/lib/lemon-ui/LemonTable/LemonTable.test.tsx b/frontend/src/lib/lemon-ui/LemonTable/LemonTable.test.tsxindex e7a91d521ae3..8029461b5b64 100644--- a/frontend/src/lib/lemon-ui/LemonTable/LemonTable.test.tsx+++ b/frontend/src/lib/lemon-ui/LemonTable/LemonTable.test.tsx@@ -53,6 +53,46 @@ describe('LemonTable', () => {expect(renderedOrder()).toEqual(expectedOrder)})+ it('keeps headers, expanded rows, and empty states aligned when the row expansion toggle is hidden', () => {+ const { rerender } = render(+ <LemonTable+ rowKey="id"+ dataSource={DATA}+ columns={COLUMNS}+ expandable={{+ expandedRowRender: () => <div>Expanded</div>,+ isRowExpanded: () => true,+ showRowExpansionToggle: false,+ noIndent: true,+ }}+ />+ )++ const headerCells = document.querySelectorAll('thead tr:last-child th')+ const firstRowCells = document.querySelectorAll('tbody tr:first-child > td')+ const expansionCells = document.querySelectorAll('tbody tr.LemonTable__expansion > td')++ expect(headerCells).toHaveLength(1)+ expect(firstRowCells).toHaveLength(1)+ expect(firstRowCells[0]).toHaveTextContent('alpha')+ expect(expansionCells).toHaveLength(3)+ expect(expansionCells[0]).toHaveAttribute('colspan', '1')++ rerender(+ <LemonTable+ rowKey="id"+ dataSource={[]}+ columns={COLUMNS}+ expandable={{+ expandedRowRender: () => <div>Expanded</div>,+ showRowExpansionToggle: false,+ }}+ />+ )++ expect(document.querySelector('tbody tr.LemonTable__empty-state > td')).toHaveAttribute('colspan', '1')+ })+it('keeps group headers aligned when the sticky first group has a single column', () => {// The sticky-first-group header is rendered as a title cell plus a filler cell. With one child// the filler's colSpan would be 0, which the DOM clamps to 1, adding a phantom column thatdiff --git a/frontend/src/lib/lemon-ui/LemonTable/LemonTable.tsx b/frontend/src/lib/lemon-ui/LemonTable/LemonTable.tsxindex 69abd6c92093..6204904c2c27 100644--- a/frontend/src/lib/lemon-ui/LemonTable/LemonTable.tsx+++ b/frontend/src/lib/lemon-ui/LemonTable/LemonTable.tsx@@ -460,7 +460,11 @@ export function LemonTable<T extends Record<string, any>, K extends BulkSelectio</tr>)}<tr>- {!!expandable && <th className="LemonTable__toggle" /> /* Expand/collapse */}+ {+ isRowExpansionToggleShown && (+ <th className="LemonTable__toggle" />+ ) /* Expand/collapse */+ }{columnGroups.flatMap((columnGroup, columnGroupIndex) =>columnGroup.children.filter((column) => !column.isHidden)@@ -736,9 +740,7 @@ export function LemonTable<T extends Record<string, any>, K extends BulkSelectio))) : (<tr className="LemonTable__empty-state">- <td colSpan={columns.length + Number(!!expandable)}>- {emptyState || `No ${nouns[1]}`}- </td>+ <td colSpan={headerLoaderColSpan}>{emptyState || `No ${nouns[1]}`}</td></tr>)}</tbody>diff --git a/frontend/src/lib/lemon-ui/LemonTable/TableRow.tsx b/frontend/src/lib/lemon-ui/LemonTable/TableRow.tsxindex 79644eef378f..753b13bf8d74 100644--- a/frontend/src/lib/lemon-ui/LemonTable/TableRow.tsx+++ b/frontend/src/lib/lemon-ui/LemonTable/TableRow.tsx@@ -55,6 +55,12 @@ function TableRowRaw<T extends Record<string, any>>({const isRowExpansionToggleShownLocal = !!expandable && rowExpandable >= 0const isRowExpansionToggleShown = expandable?.showRowExpansionToggle ?? isRowExpansionToggleShownLocal+ const visibleDataColumnCount = columnGroups.reduce(+ (count, columnGroup) => count + columnGroup.children.filter((column) => !column.isHidden).length,+ 0+ )+ const expansionColSpan =+ visibleDataColumnCount + Number(isRowExpansionToggleShown && !!expandable?.noIndent) + Number(!!rowActions)const expandedRowClassNameDetermined =expandable &&@@ -171,15 +177,8 @@ function TableRowRaw<T extends Record<string, any>>({{expandable && !!rowExpandable && isRowExpanded && (<tr className={clsx('LemonTable__expansion', expandedRowClassNameDetermined)}>- {!expandable.noIndent && <td />}- <td- colSpan={- columnGroups.reduce((acc, columnGroup) => acc + columnGroup.children.length, 0) +- Number(!!expandable.noIndent)- }- >- {expandable.expandedRowRender(record, recordIndex)}- </td>+ {isRowExpansionToggleShown && !expandable.noIndent && <td />}+ <td colSpan={expansionColSpan}>{expandable.expandedRowRender(record, recordIndex)}</td></tr>)}</>diff --git a/products/conversations/backend/facade/api.py b/products/conversations/backend/facade/api.pyindex 2d4221532c94..04b18dd9e24a 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, QuerySet+from django.db.models import F, OuterRef, Prefetch, Q, QuerySet, Subqueryimport structlogfrom slack_sdk.errors import SlackApiError@@ -28,11 +28,14 @@ from products.conversations.backend.channel_summary_ids import build_channel_sumfrom products.conversations.backend.facade.types import (AccountEmailThreadMessage as AccountEmailThreadMessage,AccountEmailThreadSummary as AccountEmailThreadSummary,+ ConversationMessageSender as ConversationMessageSender,+ ConversationMessageSummary as ConversationMessageSummary,EmailThreadAccountLinkInput as EmailThreadAccountLinkInput,EmailThreadAddress as EmailThreadAddress,EmailThreadForAccountMatching as EmailThreadForAccountMatching,EmailThreadParticipantSummary as EmailThreadParticipantSummary,SupportChannel as SupportChannel,+ SupportTicketMessage as SupportTicketMessage,TicketSummary as TicketSummary,)from products.conversations.backend.models import (@@ -55,8 +58,20 @@ from products.conversations.backend.support_slack_channels import (logger = structlog.get_logger(__name__)+class _TicketAccessControl(Protocol):+ def filter_queryset_by_access_level(self, queryset: QuerySet[Ticket]) -> QuerySet[Ticket]: ...++class _EmailThreadWithFacadePrefetch(Protocol):facade_participants: list[EmailThreadParticipant]+ facade_first_message_direction: str | None+ facade_first_message_sender_email: str | None+ facade_first_message_sender_name: str | None+ facade_first_message_sent_at: datetime | None+ facade_last_message_direction: str | None+ facade_last_message_sender_email: str | None+ facade_last_message_sender_name: str | None+ facade_last_message_sent_at: datetime | Noneclass GoogleAccountEmailSyncError(Exception):@@ -248,7 +263,85 @@ def trigger_immediate_channel_summary(return True-def list_account_tickets(team_id: int, organization_id: str, *, limit: int = 50) -> list[TicketSummary]:+def _get_first_string(context: dict[str, Any], keys: tuple[str, ...]) -> str | None:+ for key in keys:+ value = context.get(key)+ if isinstance(value, str) and value:+ return value+ return None+++def _support_ticket_last_message(ticket: Ticket, comment: Comment | None) -> ConversationMessageSummary | None:+ if comment is None:+ return None++ context = comment.item_context if isinstance(comment.item_context, dict) else {}+ author_type = context.get("author_type")+ is_outbound = bool(comment.created_by_id and author_type != "customer") or author_type in {+ "AI",+ "human",+ "support",+ }+ context_name = _get_first_string(+ context,+ (+ "author_name",+ "author_email",+ "slack_author_name",+ "teams_author_name",+ "teams_author_email",+ "email_from_name",+ "slack_author_email",+ "email_from",+ ),+ )+ context_email = _get_first_string(+ context,+ ("author_email", "slack_author_email", "teams_author_email", "email_from"),+ )+ sender_name: str | None+ sender_email: str | None++ if is_outbound:+ if comment.created_by is not None:+ sender_name = comment.created_by.get_full_name() or comment.created_by.email+ sender_email = comment.created_by.email+ else:+ sender_name = context_name or context_email or ("AI" if author_type == "AI" else "Support")+ sender_email = context_email+ sender = ConversationMessageSender(+ name=sender_name or sender_email or "Support",+ email=sender_email,+ person_id=None,+ distinct_id=None,+ )+ else:+ traits = ticket.anonymous_traits or {}+ trait_email = traits.get("email") if isinstance(traits.get("email"), str) else None+ trait_name = traits.get("name") if isinstance(traits.get("name"), str) else None+ sender_email = context_email or trait_email+ sender_name = context_name or trait_name+ sender = ConversationMessageSender(+ name=sender_name or sender_email or "Customer",+ email=sender_email,+ person_id=None,+ distinct_id=ticket.distinct_id,+ )++ return ConversationMessageSummary(+ sender=sender,+ sent_at=comment.created_at,+ direction="outbound" if is_outbound else "inbound",+ )+++def list_account_tickets(+ team_id: int,+ organization_id: str,+ user_access_control: _TicketAccessControl,+ *,+ limit: int = 50,+) -> list[TicketSummary]:"""Support tickets whose resolved customer org matches ``organization_id``, newest activity first.``organization_id`` is the customer's group key (a customer-analytics account's@@ -256,9 +349,24 @@ def list_account_tickets(team_id: int, organization_id: str, *, limit: int = 50)"""if not organization_id:return []- tickets = Ticket.objects.filter(team_id=team_id, organization_id=organization_id).order_by(- F("last_message_at").desc(nulls_last=True)- )[:limit]+ tickets = list(+ user_access_control.filter_queryset_by_access_level(+ Ticket.objects.filter(team_id=team_id, organization_id=organization_id)+ ).order_by(F("last_message_at").desc(nulls_last=True))[:limit]+ )+ latest_comments = {+ comment.item_id: comment+ for comment in Comment.objects.filter(+ team_id=team_id,+ scope="conversations_ticket",+ item_id__in=[str(ticket.id) for ticket in tickets],+ deleted=False,+ )+ .filter(~Q(item_context__is_private=True) | Q(item_context__is_private__isnull=True))+ .select_related("created_by")+ .order_by("item_id", "-created_at", "-id")+ .distinct("item_id")+ }return [TicketSummary(id=str(ticket.id),@@ -266,12 +374,63 @@ def list_account_tickets(team_id: int, organization_id: str, *, limit: int = 50)status=ticket.status,last_message_at=ticket.last_message_at,last_message_text=ticket.last_message_text,+ last_message=_support_ticket_last_message(ticket, latest_comments.get(str(ticket.id))),deep_link=f"{settings.SITE_URL}/project/{team_id}/support/tickets/{ticket.ticket_number}",+ created_at=ticket.created_at,+ started_by=(ticket.anonymous_traits or {}).get("name")+ or (ticket.anonymous_traits or {}).get("email")+ or "Customer",+ distinct_id=ticket.distinct_id,)for ticket in tickets]+def list_account_ticket_messages(+ team_id: int,+ organization_id: str,+ ticket_id: str,+ user_access_control: _TicketAccessControl,+ *,+ offset: int = 0,+ limit: int = 50,+) -> tuple[list[SupportTicketMessage], int] | None:+ ticket = user_access_control.filter_queryset_by_access_level(+ Ticket.objects.filter(team_id=team_id, organization_id=organization_id, id=ticket_id)+ ).first()+ if ticket is None:+ return None++ comments = (+ Comment.objects.filter(+ team_id=team_id,+ scope="conversations_ticket",+ item_id=str(ticket.id),+ deleted=False,+ )+ .select_related("created_by")+ .order_by("created_at", "id")+ )+ count = comments.count()+ messages = []+ for comment in comments[offset : offset + limit]:+ summary = _support_ticket_last_message(ticket, comment)+ if summary is None:+ continue+ context = comment.item_context if isinstance(comment.item_context, dict) else {}+ messages.append(+ SupportTicketMessage(+ id=str(comment.id),+ content=comment.content or "",+ author_name=summary.sender.name,+ direction=summary.direction,+ is_private=context.get("is_private") is True,+ created_at=comment.created_at,+ )+ )+ return messages, count++def resolve_group_keys_by_email(team_id: int,emails: list[str],@@ -350,21 +509,62 @@ def _email_thread_participant_summary(email=participant.email,display_name=participant.display_name,kind=participant.kind,+ person_id=str(participant.person_id) if participant.person_id else None,+ )+++def _email_message_summary(+ sender_email: str | None,+ sender_name: str | None,+ sent_at: datetime | None,+ direction: str | None,+ participant_by_email: dict[str, EmailThreadParticipantSummary],+) -> ConversationMessageSummary | None:+ if not sender_email or not sent_at or not direction:+ return None+ participant = participant_by_email.get(sender_email.lower())+ return ConversationMessageSummary(+ sender=ConversationMessageSender(+ name=sender_name or sender_email,+ email=sender_email,+ person_id=participant.person_id if participant else None,+ distinct_id=None,+ ),+ sent_at=sent_at,+ direction=direction,)def _account_email_thread_summary(thread: EmailThread) -> AccountEmailThreadSummary:prefetched_thread = cast(_EmailThreadWithFacadePrefetch, thread)+ participants = [+ _email_thread_participant_summary(participant) for participant in prefetched_thread.facade_participants+ ]+ participant_by_email = {participant.email.lower(): participant for participant in participants}+ first_message = _email_message_summary(+ prefetched_thread.facade_first_message_sender_email,+ prefetched_thread.facade_first_message_sender_name,+ prefetched_thread.facade_first_message_sent_at,+ prefetched_thread.facade_first_message_direction,+ participant_by_email,+ )+ last_message = _email_message_summary(+ prefetched_thread.facade_last_message_sender_email,+ prefetched_thread.facade_last_message_sender_name,+ prefetched_thread.facade_last_message_sent_at,+ prefetched_thread.facade_last_message_direction,+ participant_by_email,+ )return AccountEmailThreadSummary(id=str(thread.id),subject=thread.subject,preview=thread.preview,first_message_at=thread.first_message_at,+ first_message=first_message,last_message_at=thread.last_message_at,+ last_message=last_message,message_count=thread.message_count,- participants=[- _email_thread_participant_summary(participant) for participant in prefetched_thread.facade_participants- ],+ participants=participants,)@@ -376,9 +576,25 @@ def list_account_email_threads(limit: int = 50,) -> tuple[list[AccountEmailThreadSummary], int]:participants: QuerySet[EmailThreadParticipant] = EmailThreadParticipant.objects.for_team(team_id).order_by("email")+ first_message = (+ EmailThreadMessage.objects.for_team(team_id).filter(thread_id=OuterRef("pk")).order_by("sent_at", "id")+ )+ latest_message = (+ EmailThreadMessage.objects.for_team(team_id).filter(thread_id=OuterRef("pk")).order_by("-sent_at", "-id")+ )threads = (EmailThread.objects.for_team(team_id).filter(account_links__team_id=team_id, account_links__account_id=account_id)+ .annotate(+ facade_first_message_direction=Subquery(first_message.values("direction")[:1]),+ facade_first_message_sender_email=Subquery(first_message.values("sender_email")[:1]),+ facade_first_message_sender_name=Subquery(first_message.values("sender_name")[:1]),+ facade_first_message_sent_at=Subquery(first_message.values("sent_at")[:1]),+ facade_last_message_direction=Subquery(latest_message.values("direction")[:1]),+ facade_last_message_sender_email=Subquery(latest_message.values("sender_email")[:1]),+ facade_last_message_sender_name=Subquery(latest_message.values("sender_name")[:1]),+ facade_last_message_sent_at=Subquery(latest_message.values("sent_at")[:1]),+ ).prefetch_related(Prefetch("participants", queryset=participants, to_attr="facade_participants")).order_by(F("last_message_at").desc(nulls_last=True), "-id"))diff --git a/products/conversations/backend/facade/types.py b/products/conversations/backend/facade/types.pyindex 7a17fa288c80..8d7d3f5de54e 100644--- a/products/conversations/backend/facade/types.py+++ b/products/conversations/backend/facade/types.py@@ -21,6 +21,31 @@ class SupportChannel:is_member: bool+@dataclass(frozen=True)+class ConversationMessageSender:+ name: str+ email: str | None+ person_id: str | None+ distinct_id: str | None+++@dataclass(frozen=True)+class ConversationMessageSummary:+ sender: ConversationMessageSender+ sent_at: datetime+ direction: str+++@dataclass(frozen=True)+class SupportTicketMessage:+ id: str+ content: str+ author_name: str+ direction: str+ is_private: bool+ created_at: datetime++@dataclass(frozen=True)class TicketSummary:"""A support ticket, reduced to what an account's tickets list renders."""@@ -30,7 +55,11 @@ class TicketSummary:status: strlast_message_at: datetime | Nonelast_message_text: str | None+ last_message: ConversationMessageSummary | Nonedeep_link: str+ created_at: datetime+ started_by: str+ distinct_id: str@dataclass(frozen=True)@@ -51,6 +80,7 @@ class EmailThreadParticipantSummary:email: strdisplay_name: strkind: str+ person_id: str | None@dataclass(frozen=True)@@ -59,7 +89,9 @@ class AccountEmailThreadSummary:subject: strpreview: strfirst_message_at: datetime | None+ first_message: ConversationMessageSummary | Nonelast_message_at: datetime | None+ last_message: ConversationMessageSummary | Nonemessage_count: intparticipants: list[EmailThreadParticipantSummary]diff --git a/products/conversations/backend/tests/test_email_thread_account_links.py b/products/conversations/backend/tests/test_email_thread_account_links.pyindex ddc0c96bcc58..71118fe26af0 100644--- a/products/conversations/backend/tests/test_email_thread_account_links.py+++ b/products/conversations/backend/tests/test_email_thread_account_links.py@@ -1,3 +1,5 @@+from datetime import timedelta+from posthog.test.base import BaseTestfrom django.utils import timezone@@ -93,14 +95,48 @@ class TestEmailThreadAccountLinks(BaseTest):],)+ reply_sent_at = self.message.sent_at + timedelta(minutes=1)+ reply_comment = Comment.objects.create(+ team=self.team,+ scope=EMAIL_THREAD_COMMENT_SCOPE,+ item_id=str(self.thread.id),+ content="Reply update",+ )+ EmailThreadMessage.objects.for_team(self.team.id).create(+ team=self.team,+ thread=self.thread,+ comment=reply_comment,+ message_id="<[email protected]>",+ in_reply_to=self.message.message_id,+ references=[self.message.message_id],+ sent_at=reply_sent_at,+ sender_email="[email protected]",+ sender_name="CSM",+ to_recipients=[{"name": "Customer", "email": "[email protected]"}],+ cc_recipients=[],+ sender_authenticated=True,+ direction=EmailThreadMessageDirection.OUTBOUND,+ source_type="mailgun",+ source_id="<[email protected]>",+ )+ self.thread.last_message_at = reply_sent_at+ self.thread.message_count = 2+ self.thread.preview = "Reply update"+ self.thread.save(update_fields=["last_message_at", "message_count", "preview", "updated_at"])+summaries, count = list_account_email_threads(self.team.id, "account-1")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 summaries[0].last_message is not None+ assert summaries[0].last_message.sender.name == "CSM"+ assert summaries[0].last_message.sender.email == "[email protected]"+ assert summaries[0].last_message.sent_at == reply_sent_at+ assert summaries[0].last_message.direction == "outbound"assert message_page is not Nonemessages, message_count = message_page- assert message_count == 1+ assert message_count == 2assert messages[0].content == "Latest update"assert messages[0].sender_authenticated is Trueassert messages[0].to_recipients[0].email == "[email protected]"diff --git a/products/conversations/backend/tests/test_facade.py b/products/conversations/backend/tests/test_facade.pyindex bbc254757023..bd7e6959b6b1 100644--- a/products/conversations/backend/tests/test_facade.py+++ b/products/conversations/backend/tests/test_facade.py@@ -9,10 +9,12 @@ from parameterized import parameterizedfrom slack_sdk.errors import SlackApiErrorfrom posthog.models import Team+from posthog.models.comment import Commentfrom products.conversations.backend.channel_summary_ids import build_channel_summary_workflow_idfrom products.conversations.backend.facade.api import (SupportMessageSendError,+ list_account_ticket_messages,list_account_tickets,post_support_message,trigger_immediate_channel_summary,@@ -91,6 +93,11 @@ class TestPostSupportMessage(BaseTest):class TestListAccountTickets(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.access_control = MagicMock()+ self.access_control.filter_queryset_by_access_level.side_effect = lambda queryset: queryset+def _create_ticket(self, *, team: Team, organization_id: str | None, number: int, last_message_at=None) -> Ticket:return Ticket.objects.create(team=team,@@ -107,11 +114,149 @@ class TestListAccountTickets(BaseTest):self._create_ticket(team=self.team, organization_id="acct-2", number=2)self._create_ticket(team=other_team, organization_id="acct-1", number=1)- result = list_account_tickets(self.team.pk, "acct-1")+ result = list_account_tickets(self.team.pk, "acct-1", self.access_control)assert [t.id for t in result] == [str(mine.id)]assert result[0].deep_link.endswith(f"/project/{self.team.pk}/support/tickets/1")+ def test_returns_latest_public_message_sender(self):+ ticket = self._create_ticket(+ team=self.team,+ organization_id="acct-1",+ number=1,+ last_message_at=timezone.now(),+ )+ ticket.anonymous_traits = {"name": "Example customer", "email": "[email protected]"}+ ticket.save(update_fields=["anonymous_traits"])+ Comment.objects.create(+ team=self.team,+ created_by=self.user,+ scope="conversations_ticket",+ item_id=str(ticket.id),+ content="Support reply",+ item_context={"author_type": "support", "is_private": False},+ )+ Comment.objects.create(+ team=self.team,+ scope="conversations_ticket",+ item_id=str(ticket.id),+ content="Customer reply",+ item_context={"author_type": "customer", "is_private": False},+ )+ Comment.objects.create(+ team=self.team,+ created_by=self.user,+ scope="conversations_ticket",+ item_id=str(ticket.id),+ content="Private note",+ item_context={"author_type": "support", "is_private": True},+ )++ result = list_account_tickets(self.team.pk, "acct-1", self.access_control)++ assert result[0].last_message is not None+ assert result[0].last_message.sender.name == "Example customer"+ assert result[0].last_message.sender.email == "[email protected]"+ assert result[0].last_message.sender.distinct_id == ticket.distinct_id+ assert result[0].last_message.direction == "inbound"++ message_page = list_account_ticket_messages(self.team.pk, "acct-1", str(ticket.id), self.access_control)+ assert message_page is not None+ messages, count = message_page+ assert count == 3+ assert [message.content for message in messages] == ["Support reply", "Customer reply", "Private note"]+ assert [message.direction for message in messages] == ["outbound", "inbound", "outbound"]+ assert messages[-1].is_private is True++ def test_returns_imported_support_sender_without_a_posthog_user(self):+ ticket = self._create_ticket(+ team=self.team,+ organization_id="acct-1",+ number=1,+ last_message_at=timezone.now(),+ )+ Comment.objects.create(+ team=self.team,+ scope="conversations_ticket",+ item_id=str(ticket.id),+ content="Imported support reply",+ item_context={+ "author_type": "support",+ "author_name": "Imported agent",+ "author_email": "[email protected]",+ "is_private": False,+ },+ )++ result = list_account_tickets(self.team.pk, "acct-1", self.access_control)++ assert result[0].last_message is not None+ assert result[0].last_message.sender.name == "Imported agent"+ assert result[0].last_message.sender.email == "[email protected]"+ assert result[0].last_message.direction == "outbound"++ @parameterized.expand(+ [+ (+ "slack",+ {+ "author_type": "customer",+ "slack_author_name": "Slack responder",+ "slack_author_email": "[email protected]",+ },+ "Slack responder",+ "[email protected]",+ ),+ (+ "teams",+ {+ "author_type": "customer",+ "teams_author_name": "Teams responder",+ "teams_author_email": "[email protected]",+ },+ "Teams responder",+ "[email protected]",+ ),+ (+ "email",+ {"author_type": "customer", "email_from_name": "Email responder", "email_from": "[email protected]"},+ "Email responder",+ "[email protected]",+ ),+ ]+ )+ def test_returns_channel_specific_inbound_sender(+ self,+ _name: str,+ item_context: dict[str, str],+ expected_name: str,+ expected_email: str,+ ) -> None:+ ticket = self._create_ticket(+ team=self.team,+ organization_id="acct-1",+ number=1,+ last_message_at=timezone.now(),+ )+ ticket.anonymous_traits = {"name": "Thread starter", "email": "[email protected]"}+ ticket.save(update_fields=["anonymous_traits"])+ Comment.objects.create(+ team=self.team,+ scope="conversations_ticket",+ item_id=str(ticket.id),+ content="Channel reply",+ item_context=item_context,+ )++ tickets = list_account_tickets(self.team.pk, "acct-1", self.access_control)+ message_page = list_account_ticket_messages(self.team.pk, "acct-1", str(ticket.id), self.access_control)++ assert tickets[0].last_message is not None+ assert tickets[0].last_message.sender.name == expected_name+ assert tickets[0].last_message.sender.email == expected_email+ assert message_page is not None+ assert message_page[0][0].author_name == expected_name+def test_orders_by_last_message_activity_with_nulls_last(self):older = timezone.now() - timedelta(hours=1)newer = timezone.now()@@ -119,14 +264,14 @@ class TestListAccountTickets(BaseTest):self._create_ticket(team=self.team, organization_id="acct-1", number=2, last_message_at=newer)self._create_ticket(team=self.team, organization_id="acct-1", number=3, last_message_at=None)- result = list_account_tickets(self.team.pk, "acct-1")+ result = list_account_tickets(self.team.pk, "acct-1", self.access_control)assert [t.ticket_number for t in result] == [2, 1, 3]def test_empty_organization_id_matches_nothing(self):self._create_ticket(team=self.team, organization_id="acct-1", number=1)- assert list_account_tickets(self.team.pk, "") == []+ assert list_account_tickets(self.team.pk, "", self.access_control) == []ACCOUNT_ID = "e1f4a5b6-0000-4000-8000-000000000001"diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 45223d64be6b..aa55def0b967 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -76,13 +76,17 @@ from posthog.models.team import Teamfrom products.conversations.backend.facade.api import (AccountEmailThreadMessage as AccountEmailThreadMessage,AccountEmailThreadSummary as AccountEmailThreadSummary,+ ConversationMessageSender as ConversationMessageSender,+ ConversationMessageSummary as ConversationMessageSummary,EmailThreadAddress as EmailThreadAddress,EmailThreadParticipantSummary as EmailThreadParticipantSummary,SupportSlackChannelsUnavailable,SupportSlackNotConfigured,+ SupportTicketMessage as SupportTicketMessage,TicketSummary as TicketSummary,list_account_email_thread_messages,list_account_email_threads,+ list_account_ticket_messages,list_account_tickets,trigger_immediate_channel_summary,)@@ -3876,7 +3880,33 @@ def get_account_support_tickets(account = _resolve_account(team_id, account_id=account_id)if account is None or not account.external_id:return []- return list_account_tickets(team_id, account.external_id, limit=limit)+ return list_account_tickets(team_id, account.external_id, user_access_control, limit=limit)+++def get_account_support_ticket_messages(+ team_id: int,+ account_id: str,+ ticket_id: str,+ user_access_control: "UserAccessControl",+ *,+ offset: int = 0,+ limit: int = 50,+) -> tuple[list[SupportTicketMessage], 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()+ account = _resolve_account(team_id, account_id=account_id)+ if account is None or not account.external_id:+ return None+ return list_account_ticket_messages(+ team_id,+ account.external_id,+ ticket_id,+ user_access_control,+ offset=offset,+ limit=limit,+ )def get_account_email_threads(diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.pyindex f26677b5df2f..5f4f3d885b38 100644--- a/products/customer_analytics/backend/presentation/views/serializers.py+++ b/products/customer_analytics/backend/presentation/views/serializers.py@@ -31,8 +31,11 @@ from posthog.models import OrganizationMembershipfrom products.customer_analytics.backend.facade.api import (AccountEmailThreadMessage,AccountEmailThreadSummary,+ ConversationMessageSender,+ ConversationMessageSummary,EmailThreadAddress,EmailThreadParticipantSummary,+ SupportTicketMessage,TicketSummary,)from products.customer_analytics.backend.facade.constants import (@@ -977,6 +980,66 @@ class AccountChannelSummarySerializer(DataclassSerializer):]+class ConversationMessageSenderSerializer(DataclassSerializer):+ name = serializers.CharField(read_only=True, help_text="Display name of the message sender.")+ email = serializers.EmailField(+ read_only=True,+ allow_null=True,+ help_text="Email address of the message sender, when available.",+ )+ person_id = serializers.UUIDField(+ read_only=True,+ allow_null=True,+ help_text="UUID of the matched PostHog person, when available.",+ )+ distinct_id = serializers.CharField(+ read_only=True,+ allow_null=True,+ help_text="Distinct ID of the sender, when available.",+ )++ class Meta:+ dataclass = ConversationMessageSender+ ref_name = "ConversationMessageSender"+ fields = ["name", "email", "person_id", "distinct_id"]+++class ConversationMessageSummarySerializer(DataclassSerializer):+ sender = ConversationMessageSenderSerializer(read_only=True, help_text="Sender of the message.")+ sent_at = serializers.DateTimeField(read_only=True, help_text="Timestamp from the message source.")+ direction = serializers.ChoiceField(+ read_only=True,+ choices=[("inbound", "Inbound"), ("outbound", "Outbound")],+ help_text="Whether PostHog received or sent the message.",+ )++ class Meta:+ dataclass = ConversationMessageSummary+ ref_name = "ConversationMessageSummary"+ fields = ["sender", "sent_at", "direction"]+++class SupportTicketMessageSerializer(DataclassSerializer):+ id = serializers.UUIDField(read_only=True, help_text="UUID of the support ticket message.")+ content = serializers.CharField(read_only=True, allow_blank=True, help_text="Plain-text message content.")+ author_name = serializers.CharField(read_only=True, help_text="Display name of the message author.")+ direction = serializers.ChoiceField(+ read_only=True,+ choices=[("inbound", "Inbound"), ("outbound", "Outbound")],+ help_text="Whether PostHog received or sent the message.",+ )+ is_private = serializers.BooleanField(+ read_only=True,+ help_text="Whether the message is an internal note hidden from the customer.",+ )+ created_at = serializers.DateTimeField(read_only=True, help_text="When the message was created.")++ class Meta:+ dataclass = SupportTicketMessage+ ref_name = "AccountSupportTicketMessage"+ fields = ["id", "content", "author_name", "direction", "is_private", "created_at"]++class SupportTicketSerializer(DataclassSerializer):"""A support ticket linked to an account, sourced from the conversations product (read-only)."""@@ -989,12 +1052,31 @@ class SupportTicketSerializer(DataclassSerializer):last_message_text = serializers.CharField(read_only=True, allow_null=True, help_text="Truncated preview of the most recent message.")+ last_message = ConversationMessageSummarySerializer(+ read_only=True,+ allow_null=True,+ help_text="Sender, timestamp, and direction of the latest public message, when available.",+ )deep_link = serializers.CharField(read_only=True, help_text="Absolute URL to open this ticket in the app.")+ created_at = serializers.DateTimeField(read_only=True, help_text="When the ticket conversation started.")+ started_by = serializers.CharField(read_only=True, help_text="Display name of the customer who started the ticket.")+ distinct_id = serializers.CharField(read_only=True, help_text="Distinct ID of the customer who started the ticket.")class Meta:dataclass = TicketSummaryref_name = "SupportTicket"- fields = ["id", "ticket_number", "status", "last_message_at", "last_message_text", "deep_link"]+ fields = [+ "id",+ "ticket_number",+ "status",+ "last_message_at",+ "last_message_text",+ "last_message",+ "deep_link",+ "created_at",+ "started_by",+ "distinct_id",+ ]class EmailThreadParticipantSerializer(DataclassSerializer):@@ -1009,11 +1091,16 @@ class EmailThreadParticipantSerializer(DataclassSerializer):choices=[("internal", "Internal"), ("customer", "Customer")],help_text="Whether the participant belongs to the PostHog organization or the customer.",)+ person_id = serializers.UUIDField(+ read_only=True,+ allow_null=True,+ help_text="UUID of the matched PostHog person for a customer participant, when available.",+ )class Meta:dataclass = EmailThreadParticipantSummaryref_name = "AccountEmailThreadParticipant"- fields = ["email", "display_name", "kind"]+ fields = ["email", "display_name", "kind", "person_id"]class AccountEmailThreadSerializer(DataclassSerializer):@@ -1029,11 +1116,21 @@ class AccountEmailThreadSerializer(DataclassSerializer):allow_null=True,help_text="Source timestamp of the first captured message.",)+ first_message = ConversationMessageSummarySerializer(+ read_only=True,+ allow_null=True,+ help_text="Sender, timestamp, and direction of the first captured message, when available.",+ )last_message_at = serializers.DateTimeField(read_only=True,allow_null=True,help_text="Source timestamp of the latest captured message.",)+ last_message = ConversationMessageSummarySerializer(+ read_only=True,+ allow_null=True,+ help_text="Sender, timestamp, and direction of the latest captured message, when available.",+ )message_count = serializers.IntegerField(read_only=True,help_text="Number of captured messages in the thread.",@@ -1052,7 +1149,9 @@ class AccountEmailThreadSerializer(DataclassSerializer):"subject","preview","first_message_at",+ "first_message","last_message_at",+ "last_message","message_count","participants",]diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.pyindex 24080d3f88d8..7dd429646dd3 100644--- a/products/customer_analytics/backend/presentation/views/views.py+++ b/products/customer_analytics/backend/presentation/views/views.py@@ -90,6 +90,7 @@ from products.customer_analytics.backend.presentation.views.serializers import (FeatureRequestUpdateSerializer,FeatureRequestVersionSerializer,MeetingSerializer,+ SupportTicketMessageSerializer,SupportTicketSerializer,)@@ -1437,6 +1438,50 @@ class AccountViewSet(return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)return Response(SupportTicketSerializer(instance=tickets, many=True).data)+ @extend_schema(+ operation_id="accounts_support_ticket_messages_list",+ parameters=[_ACCOUNT_ID_PARAM],+ responses={200: SupportTicketMessageSerializer(many=True)},+ )+ @action(+ methods=["GET"],+ detail=True,+ url_path=r"support_tickets/(?P<ticket_id>[^/.]+)",+ url_name="support-ticket-detail",+ pagination_class=AccountEmailThreadMessagePagination,+ )+ def support_ticket(self, request: Request, ticket_id: str, *args, **kwargs) -> Response:+ try:+ parsed_ticket_id = str(UUID(ticket_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_support_ticket_messages(+ self.team_id,+ self.kwargs["pk"],+ parsed_ticket_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 = SupportTicketMessageSerializer(instance=messages, many=True)+ return paginator.get_paginated_response(serializer.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:@@ -1542,7 +1587,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 in {"support_tickets", "email_threads", "email_thread"}:+ if view.action in {"support_tickets", "support_ticket", "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 871e9321ba55..6c71c276659e 100644--- a/products/customer_analytics/backend/test/test_views.py+++ b/products/customer_analytics/backend/test/test_views.py@@ -2747,13 +2747,21 @@ class TestAccountSupportTicketViewSet(APIBaseTest):self.endpoint = f"/api/environments/{self.team.id}/accounts/{self.account.id}/support_tickets/"def test_list_returns_tickets_for_the_accounts_org(self):- Ticket.objects.create(+ ticket = Ticket.objects.create(team=self.team,ticket_number=7,widget_session_id="s7",distinct_id="d7",organization_id="acme-1",status="open",+ anonymous_traits={"name": "Example customer", "email": "[email protected]"},+ )+ Comment.objects.create(+ team=self.team,+ scope="conversations_ticket",+ item_id=str(ticket.id),+ content="Latest question",+ item_context={"author_type": "customer", "is_private": False},)Ticket.objects.create(team=self.team, ticket_number=8, widget_session_id="s8", distinct_id="d8", organization_id="other-org"@@ -2765,8 +2773,16 @@ class TestAccountSupportTicketViewSet(APIBaseTest):data = response.json()self.assertEqual([t["ticket_number"] for t in data], [7])self.assertEqual(data[0]["status"], "open")+ self.assertEqual(data[0]["last_message"]["sender"]["name"], "Example customer")+ self.assertEqual(data[0]["last_message"]["direction"], "inbound")self.assertTrue(data[0]["deep_link"].endswith(f"/project/{self.team.id}/support/tickets/7"))+ detail_response = self.client.get(f"{self.endpoint}{ticket.id}/")+ self.assertEqual(status.HTTP_200_OK, detail_response.status_code, detail_response.json())+ self.assertEqual(detail_response.json()["count"], 1)+ self.assertEqual(detail_response.json()["results"][0]["content"], "Latest question")+ self.assertEqual(detail_response.json()["results"][0]["direction"], "inbound")+def test_list_is_empty_when_account_has_no_external_id(self):unlinked = Account.objects.unscoped().create(team=self.team, name="Unlinked", external_id=None)@@ -2775,6 +2791,72 @@ class TestAccountSupportTicketViewSet(APIBaseTest):self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())self.assertEqual(response.json(), [])+ def test_ticket_object_denial_hides_list_metadata_and_message_bodies(self):+ allowed_ticket = Ticket.objects.create(+ team=self.team,+ ticket_number=9,+ widget_session_id="s9",+ distinct_id="d9",+ organization_id="acme-1",+ )+ denied_ticket = Ticket.objects.create(+ team=self.team,+ ticket_number=10,+ widget_session_id="s10",+ distinct_id="d10",+ organization_id="acme-1",+ )+ for ticket in (allowed_ticket, denied_ticket):+ Comment.objects.create(+ team=self.team,+ scope="conversations_ticket",+ item_id=str(ticket.id),+ content=f"Message for {ticket.ticket_number}",+ item_context={"author_type": "customer", "is_private": False},+ )+ 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="viewer",+ organization_member=membership,+ )+ AccessControl.objects.create(+ team=self.team,+ resource="ticket",+ resource_id=str(denied_ticket.id),+ access_level="none",+ organization_member=membership,+ )+ self.client.force_login(viewer)++ list_response = self.client.get(self.endpoint)++ self.assertEqual(status.HTTP_200_OK, list_response.status_code, list_response.json())+ self.assertEqual([ticket["id"] for ticket in list_response.json()], [str(allowed_ticket.id)])+ self.assertEqual(+ status.HTTP_404_NOT_FOUND,+ self.client.get(f"{self.endpoint}{denied_ticket.id}/").status_code,+ )+ self.assertEqual(+ status.HTTP_200_OK,+ self.client.get(f"{self.endpoint}{allowed_ticket.id}/").status_code,+ )+def test_account_viewer_denied_tickets_cannot_read_them(self):Ticket.objects.create(team=self.team,@@ -2838,6 +2920,13 @@ class TestAccountEmailThreadViewSet(APIBaseTest):display_name="Customer",kind=EmailThreadParticipantKind.CUSTOMER,)+ EmailThreadParticipant.objects.for_team(self.team.id).create(+ team=self.team,+ thread=self.thread,+ email="[email protected]",+ display_name="Account manager",+ kind=EmailThreadParticipantKind.INTERNAL,+ )for index, sent_at in enumerate([last_message_at, first_message_at], start=1):comment = Comment.objects.create(team=self.team,@@ -2870,6 +2959,9 @@ class TestAccountEmailThreadViewSet(APIBaseTest):summary = payload["results"][0]self.assertEqual(summary["subject"], "Renewal planning")self.assertEqual(summary["message_count"], 2)+ self.assertEqual(summary["first_message"]["sender"]["name"], "Customer")+ self.assertEqual(summary["last_message"]["sender"]["name"], "Customer")+ self.assertEqual(summary["last_message"]["direction"], "inbound")self.assertNotIn("messages", summary)detail_response = self.client.get(f"{self.endpoint}{self.thread.id}/?limit=1&offset=0")diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex 55f59520ac36..e9ed2a096546 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/Feature requests/Usage/Spend/Opportunities/Summaries/Support tickets/Email threads/Meetings/Event stream)+ └── AccountNotebooksExpansion expanded row: sidebar (Useful links + active-relationships summary) + LemonTabs(Notes/Users/Relationships/Feature requests/Usage/Spend/Opportunities/Conversations/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)@@ -33,9 +33,7 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_TABLE_DATA_NODE_KEY, acc├── (usage) AccountBillingExpansion kind="usage" (accountBillingLogic — a saved billing-usage insight)├── (spend) AccountBillingExpansion kind="spend" (accountBillingLogic — saved billing-spend insights)└── (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)+ └── (conversations) AccountConversationsExpansion (accountConversationsLogic, keyed by accountId — combines email threads, accessible Support tickets, and Slack summaries; one failed source leaves the other sources usable; email and Slack counts expose a Load older conversations action; expansions paginate email messages, show the Support thread, and keep Slack message links collapsed by default)└── (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```@@ -57,7 +55,8 @@ 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. |+| `accountEmailThreadsLogic` | Matched email communication used by the Conversations 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. |+| `accountConversationsLogic` | The unified Conversations timeline (keyed by `accountId`): loads email, Support, and Slack independently so one denied or failed source does not blank successful sources; merges them newest-first; owns search, source filters, expansion state, Support message loading, and collapsed Slack message links. It preserves email and Slack response counts and loads older source pages on demand instead of silently limiting search to the first 50 rows. || `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`). |@@ -115,9 +114,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` / `feature_requests` / `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`). Pagination inside these tabs keeps its page state out of the URL so changing pages does not rerun deep-link restoration and replace the active tab.+`AccountsTable.useExpandable()` makes expansion **controlled** by `accountsExpansionLogic`: `isRowExpanded` reads `expandedAccountIds`, `onRowExpand`/`onRowCollapse` dispatch `toggleAccountExpanded`. The body is `AccountNotebooksExpansion`, a `LemonTabs` over `notes` / `users` / `relationships` / `feature_requests` / `usage` / `spend` / `opportunities` / `conversations` / `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`). Pagination inside these tabs keeps its page state out of the URL so changing pages does not rerun deep-link restoration and replace the active tab.-**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 flag-gated Feature requests tab loads when opened instead of mounting its logic while the flag is off.+**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 })`, `accountConversationsLogic({ 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 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 flag-gated Feature requests tab loads when opened instead of mounting its logic while the flag is off.The Users tab reads its loaded data straight off `accountRelatedUsersLogic`, so the root mount above keeps it cached. The **Usage/Spend** tabs are different: their insight results live in `dataNodeLogic`/`dataVisualizationLogic`. After each `accountBillingLogic` loads its saved-insight metadata, it mounts those result logics immediately. Because the expanded-row root mounts both billing kinds, all Usage and Spend queries start when the account expands instead of waiting for a tab click. The result logics stay mounted until the row collapses. Changing the date range replaces each insight's preload and aborts work under the previous query key. The tab body reuses the same keyed logics and attaches them to `accountBillingLogic` via `useAttachedLogic` — `AccountBillingChart` does this directly, and the fallback `<Query>` path uses `attachTo={accountBillingLogic-instance}` plus matching insight context. This prevents duplicate loads and keeps results across tab switches. (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.)@@ -150,7 +149,7 @@ 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 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. Clicking the subject or a participant toggles the thread; the table does not render a separate expansion control. 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`).diff --git a/products/customer_analytics/frontend/components/Accounts/AccountConversationsExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountConversationsExpansion.tsxnew file mode 100644index 000000000000..3136a9216c14--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/AccountConversationsExpansion.tsx@@ -0,0 +1,664 @@+import { useActions, useValues } from 'kea'++import { IconChevronDown, IconLock, IconSupport } from '@posthog/icons'+import {+ LemonBanner,+ LemonButton,+ LemonCard,+ LemonCheckbox,+ LemonDropdown,+ LemonInput,+ LemonMenu,+ LemonMenuItems,+ LemonSkeleton,+ LemonTable,+ LemonTableColumns,+ Link,+ ProfilePicture,+ Tooltip,+} from '@posthog/lemon-ui'++import { BigLeaguesHog } from 'lib/components/hedgehogs'+import { TZLabel } from 'lib/components/TZLabel'+import { IconSlack } from 'lib/lemon-ui/icons'+import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'+import { PaginationControl } from 'lib/lemon-ui/PaginationControl'+import { urls } from 'scenes/urls'++import gmailIcon from 'public/services/gmail.png'++import type {+ AccountEmailThreadMessageApi,+ AccountSupportTicketMessageApi,+ ConversationMessageSummaryApi,+} from 'products/customer_analytics/frontend/generated/api.schemas'++import {+ AccountConversation,+ accountConversationsLogic,+ ConversationSource,+ NOT_LOADED,+} from './accountConversationsLogic'+import { accountEmailThreadsLogic, MESSAGE_PAGE_SIZE } from './accountEmailThreadsLogic'+import { periodLabel } from './AccountSummariesExpansion'+import { AccountSummaryCadencePicker } from './AccountSummaryCadencePicker'++const SOURCE_OPTIONS: { key: ConversationSource; label: string }[] = [+ { key: 'email', label: 'Gmail' },+ { key: 'support', label: 'Support' },+ { key: 'slack', label: 'Slack' },+]+const VISIBLE_PARTICIPANT_COUNT = 3++function EmptyState({ 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 SourceIcon({ source }: { source: ConversationSource }): JSX.Element {+ const label = SOURCE_OPTIONS.find((option) => option.key === source)?.label ?? source+ return (+ <Tooltip title={label}>+ <span className="inline-flex shrink-0 text-lg" aria-label={label}>+ {source === 'email' ? (+ <img src={gmailIcon} alt="" className="size-4 object-contain" />+ ) : source === 'support' ? (+ <IconSupport />+ ) : (+ <IconSlack />+ )}+ </span>+ </Tooltip>+ )+}++function SourceFilter({+ sources,+ onChange,+}: {+ sources: ConversationSource[]+ onChange: (sources: ConversationSource[]) => void+}): JSX.Element {+ const allSelected = sources.length === SOURCE_OPTIONS.length+ const label = allSelected+ ? 'All sources'+ : sources.length === 1+ ? (SOURCE_OPTIONS.find((option) => option.key === sources[0])?.label ?? sources[0])+ : `${sources.length} sources`+ const items: LemonMenuItems = [+ {+ title: 'Sources',+ items: SOURCE_OPTIONS.map((option) => ({+ icon: <LemonCheckbox checked={sources.includes(option.key)} className="pointer-events-none" />,+ label: option.label,+ onClick: () =>+ onChange(+ sources.includes(option.key)+ ? sources.filter((source) => source !== option.key)+ : SOURCE_OPTIONS.map(({ key }) => key).filter(+ (source) => sources.includes(source) || source === option.key+ )+ ),+ })),+ },+ ]++ return (+ <LemonMenu items={items} closeOnClickInside={false} placement="bottom-start">+ <LemonButton+ type="secondary"+ size="small"+ sideIcon={<IconChevronDown />}+ className="shrink-0"+ aria-label={allSelected ? 'All sources selected' : `${sources.length} sources selected`}+ data-attr="account-conversations-source-filter"+ >+ {label}+ </LemonButton>+ </LemonMenu>+ )+}++function ActivityTimestamp({ time }: { time: string }): JSX.Element {+ return (+ <span className="self-start text-xs text-muted">+ <TZLabel time={time} />+ </span>+ )+}++interface ConversationParticipant {+ key: string+ name: string+ email?: string+ personId?: string | null+}++function ParticipantList({ participants }: { participants: ConversationParticipant[] }): JSX.Element {+ const visibleParticipants = participants.slice(0, VISIBLE_PARTICIPANT_COUNT)+ const hiddenParticipants = participants.slice(VISIBLE_PARTICIPANT_COUNT)++ return (+ <span className="flex flex-wrap items-center gap-2">+ {visibleParticipants.map((participant) => (+ <Person+ key={participant.key}+ name={participant.name}+ email={participant.email}+ personId={participant.personId}+ />+ ))}+ {hiddenParticipants.length > 0 && (+ <LemonDropdown+ closeOnClickInside={false}+ placement="bottom-start"+ overlay={+ <div className="flex max-h-80 min-w-56 flex-col gap-2 overflow-y-auto p-3">+ {participants.map((participant) => (+ <Person+ key={participant.key}+ name={participant.name}+ email={participant.email}+ personId={participant.personId}+ />+ ))}+ </div>+ }+ >+ <LemonButton+ type="tertiary"+ size="xsmall"+ noPadding+ className="text-muted"+ data-attr="account-conversations-participant-overflow"+ >+ +{hiddenParticipants.length} more+ </LemonButton>+ </LemonDropdown>+ )}+ </span>+ )+}++function Person({ name, email, personId }: { name: string; email?: string; personId?: string | null }): JSX.Element {+ const content = (+ <span className="inline-flex items-center gap-1.5 min-w-0">+ <ProfilePicture user={{ email: email ?? name }} size="xs" />+ <span className="truncate">{name}</span>+ </span>+ )+ return personId ? <Link to={urls.personByUUID(personId)}>{content}</Link> : content+}++function LatestMessageActivity({ message }: { message: ConversationMessageSummaryApi }): JSX.Element {+ const person = (+ <Person+ name={message.sender.name || message.sender.email || 'Unknown sender'}+ email={message.sender.email ?? undefined}+ personId={message.sender.person_id}+ />+ )+ const sender = message.sender.distinct_id ? (+ <Link to={urls.personByDistinctId(message.sender.distinct_id)}>{person}</Link>+ ) : (+ person+ )++ return (+ <span className="flex min-w-0 flex-col gap-0.5">+ {sender}+ <span className="flex self-start items-center gap-1 text-xs text-muted">+ <span>{message.direction === 'inbound' ? 'Inbound' : 'Outbound'}</span>+ <span>·</span>+ <ActivityTimestamp time={message.sent_at} />+ </span>+ </span>+ )+}++function LatestActivity({ conversation }: { conversation: AccountConversation }): JSX.Element {+ if (conversation.source === 'slack') {+ return (+ <span className="flex flex-col gap-0.5">+ <span>Summary generated</span>+ <ActivityTimestamp time={conversation.summary.generated_at} />+ </span>+ )+ }++ const lastMessage =+ conversation.source === 'email' ? conversation.email.last_message : conversation.ticket.last_message+ if (lastMessage) {+ return <LatestMessageActivity message={lastMessage} />+ }+ return conversation.occurredAt ? (+ <ActivityTimestamp time={conversation.occurredAt} />+ ) : (+ <span className="text-muted">—</span>+ )+}++function EmailMessage({ message }: { message: AccountEmailThreadMessageApi }): JSX.Element {+ const outgoing = message.direction === 'outbound'+ return (+ <div className={`flex ${outgoing ? 'justify-end' : 'justify-start'}`}>+ <LemonCard+ hoverEffect={false}+ className={`p-3 flex flex-col gap-1 max-w-3xl ${outgoing ? 'bg-surface-primary' : 'bg-surface-secondary'}`}+ >+ <div className="flex items-center justify-between gap-4">+ <Person name={message.sender.name || message.sender.email} email={message.sender.email} />+ <ActivityTimestamp time={message.sent_at} />+ </div>+ <div className="whitespace-pre-wrap break-words text-sm">{message.content}</div>+ </LemonCard>+ </div>+ )+}++function SupportMessage({ message }: { message: AccountSupportTicketMessageApi }): JSX.Element {+ const outgoing = message.direction === 'outbound'+ return (+ <div className={`flex ${outgoing ? 'justify-end' : 'justify-start'}`}>+ <LemonCard+ hoverEffect={false}+ className={`flex max-w-3xl flex-col gap-1 p-3 ${+ message.is_private+ ? 'bg-warning-highlight'+ : outgoing+ ? 'bg-surface-primary'+ : 'bg-surface-secondary'+ }`}+ >+ <div className="flex items-center justify-between gap-4">+ <span className="flex items-center gap-1.5">+ <span className="font-medium">{message.author_name}</span>+ {message.is_private && (+ <span className="flex items-center gap-1 text-xs text-warning-dark">+ <IconLock /> Private note+ </span>+ )}+ </span>+ <ActivityTimestamp time={message.created_at} />+ </div>+ <div className="whitespace-pre-wrap break-words text-sm">{message.content}</div>+ </LemonCard>+ </div>+ )+}++function ConversationDetail({+ accountId,+ conversation,+}: {+ accountId: string+ conversation: AccountConversation+}): JSX.Element {+ const emailLogic = accountEmailThreadsLogic({ accountId })+ const { threadDetails, threadDetailsLoading, threadDetailErrors, threadDetailPages } = useValues(emailLogic)+ const {+ expandedSummaryMessageIds,+ supportTicketMessages,+ supportTicketMessagesLoading,+ supportTicketMessageErrors,+ } = useValues(accountConversationsLogic({ accountId }))+ const { toggleSummaryMessages } = useActions(accountConversationsLogic({ accountId }))+ const { setThreadDetailPage } = useActions(emailLogic)++ if (conversation.source === 'slack') {+ return (+ <div className="flex flex-col gap-4 bg-surface-primary p-4">+ <LemonMarkdown lowKeyHeadings disableImages disableDocsRedirect>+ {conversation.summary.content}+ </LemonMarkdown>+ {conversation.summary.messages.length > 0 && (+ <div className="flex flex-col gap-2 border-t pt-3">+ <LemonButton+ type="tertiary"+ fullWidth+ noPadding+ className="justify-between"+ sideIcon={+ <IconChevronDown+ className={+ expandedSummaryMessageIds[conversation.summary.id] ? 'rotate-180' : undefined+ }+ />+ }+ aria-expanded={!!expandedSummaryMessageIds[conversation.summary.id]}+ onClick={() => toggleSummaryMessages(conversation.summary.id)}+ data-attr="account-summary-messages-toggle"+ >+ {conversation.summary.message_count}{' '}+ {conversation.summary.message_count === 1 ? 'message' : 'messages'} summarized+ </LemonButton>+ {expandedSummaryMessageIds[conversation.summary.id] && (+ <div className="flex flex-col gap-1">+ {conversation.summary.messages.map((message, index) => (+ <Link+ key={`${message.permalink}-${index}`}+ to={message.permalink}+ target="_blank"+ className="flex items-center justify-between gap-4 rounded px-2 py-1 hover:bg-surface-secondary"+ >+ <span className="font-medium">{message.author}</span>+ <ActivityTimestamp time={message.sent_at} />+ </Link>+ ))}+ </div>+ )}+ </div>+ )}+ </div>+ )+ }+ if (conversation.source === 'support') {+ const messages = supportTicketMessages[conversation.ticket.id]+ if (+ supportTicketMessagesLoading[conversation.ticket.id] ||+ (!messages && !supportTicketMessageErrors[conversation.ticket.id])+ ) {+ return <LemonSkeleton className="h-40 w-full" />+ }+ if (!messages || supportTicketMessageErrors[conversation.ticket.id]) {+ return <EmptyState title="Couldn't load this ticket" detail="Collapse it and try again." />+ }+ return (+ <div className="flex flex-col gap-3 bg-surface-primary p-4">+ <div className="flex justify-end">+ <LemonButton type="secondary" to={conversation.ticket.deep_link} targetBlank>+ Open in Support+ </LemonButton>+ </div>+ {messages.results.length > 0 ? (+ messages.results.map((message) => <SupportMessage key={message.id} message={message} />)+ ) : (+ <span className="text-sm text-muted">No messages in this ticket yet.</span>+ )}+ {messages.count > messages.results.length && (+ <span className="text-xs text-muted">+ Showing {messages.results.length} of {messages.count} messages.+ </span>+ )}+ </div>+ )+ }++ const detail = threadDetails[conversation.email.id]+ if (threadDetailsLoading[conversation.email.id] || (!detail && !threadDetailErrors[conversation.email.id])) {+ return <LemonSkeleton className="h-40 w-full" />+ }+ if (!detail || threadDetailErrors[conversation.email.id]) {+ return <EmptyState title="Couldn't load this conversation" detail="Collapse it and try again." />+ }+ const page = threadDetailPages[conversation.email.id] ?? 1+ return (+ <div className="flex flex-col gap-2 bg-surface-primary p-4" 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(conversation.email.id, 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>+ )+}++function conversationTitle(conversation: AccountConversation): string {+ if (conversation.source === 'email') {+ return conversation.email.subject || 'No subject'+ }+ if (conversation.source === 'support') {+ return `Ticket: #${conversation.ticket.ticket_number}`+ }+ return periodLabel(conversation.summary)+}++function conversationPreview(conversation: AccountConversation): string {+ if (conversation.source === 'email') {+ return conversation.email.preview+ }+ if (conversation.source === 'support') {+ return conversation.ticket.last_message_text ?? ''+ }+ return conversation.summary.content+ .replace(/[#*_`>[\]]/g, '')+ .replace(/\s+/g, ' ')+ .trim()+}++export function AccountConversationsExpansion({ accountId }: { accountId: string }): JSX.Element {+ const logic = accountConversationsLogic({ accountId })+ const emailLogic = accountEmailThreadsLogic({ accountId })+ const {+ conversationsResult,+ conversationsResultLoading,+ filteredConversations,+ searchTerm,+ sources,+ expandedConversationId,+ olderConversationCount,+ } = useValues(logic)+ const { setSearchTerm, setSources, openConversation, closeConversation, loadConversations, loadMoreConversations } =+ useActions(logic)+ const { openThread, closeThread } = useActions(emailLogic)++ if (+ conversationsResult === NOT_LOADED ||+ (conversationsResultLoading && conversationsResult.conversations === null)+ ) {+ return <LemonSkeleton className="h-64 w-full" />+ }+ const toolbar = (+ <div className="hide-scrollbar flex items-center gap-4 overflow-x-auto pb-1">+ <LemonInput+ type="search"+ value={searchTerm}+ onChange={setSearchTerm}+ placeholder="Search conversations"+ size="small"+ className="min-w-56 max-w-md flex-1"+ data-attr="account-conversations-search"+ />+ <SourceFilter sources={sources} onChange={setSources} />+ <div className="ml-auto flex shrink-0 items-center gap-2 whitespace-nowrap">+ <span className="text-sm text-muted">Slack summary cadence</span>+ <AccountSummaryCadencePicker accountId={accountId} />+ </div>+ </div>+ )+ const sourceFailureBanner = conversationsResult.failedSources.length > 0 && (+ <LemonBanner+ type={conversationsResult.loadFailed ? 'error' : 'warning'}+ action={{+ children: 'Retry',+ onClick: loadConversations,+ loading: conversationsResultLoading,+ }}+ >+ {conversationsResult.loadFailed+ ? "Conversation sources couldn't load."+ : "Some conversation sources aren't available. Showing the sources that loaded."}+ </LemonBanner>+ )+ if (conversationsResult.loadFailed) {+ return (+ <div className="flex flex-col gap-3">+ {toolbar}+ {sourceFailureBanner}+ <EmptyState title="Couldn't load conversations" detail="Retry to load this account's conversations." />+ </div>+ )+ }+ if (!conversationsResult.conversations?.length) {+ return (+ <div className="flex flex-col gap-3">+ {toolbar}+ {sourceFailureBanner}+ <EmptyState+ title="No conversations yet"+ detail="Email, Support, and Slack conversations will appear here."+ />+ </div>+ )+ }++ const toggleConversation = (conversation: AccountConversation): void => {+ if (expandedConversationId === conversation.id) {+ closeConversation(conversation.id)+ if (conversation.source === 'email') {+ closeThread(conversation.email.id)+ }+ } else {+ openConversation(conversation.id)+ if (conversation.source === 'email') {+ openThread(conversation.email.id)+ }+ }+ }++ const columns: LemonTableColumns<AccountConversation> = [+ {+ title: 'Conversation',+ key: 'conversation',+ align: 'left',+ render: (_, conversation) => (+ <LemonButton+ type="tertiary"+ noPadding+ fullWidth+ className="justify-start text-left"+ aria-expanded={expandedConversationId === conversation.id}+ onClick={() => toggleConversation(conversation)}+ >+ <span className="flex min-w-0 items-center gap-2 py-1">+ <SourceIcon source={conversation.source} />+ <span className="flex min-w-0 flex-col">+ <span className="font-medium truncate">{conversationTitle(conversation)}</span>+ <span className="text-xs text-muted line-clamp-2">{conversationPreview(conversation)}</span>+ </span>+ </span>+ </LemonButton>+ ),+ },+ {+ title: 'Started by',+ key: 'startedBy',+ align: 'left',+ render: (_, conversation) => {+ if (conversation.source === 'email') {+ const starter = conversation.email.first_message?.sender+ return starter ? (+ <Person+ name={starter.name || starter.email || 'Unknown sender'}+ email={starter.email ?? undefined}+ personId={starter.person_id}+ />+ ) : (+ <span className="text-muted">—</span>+ )+ }+ if (conversation.source === 'support') {+ return (+ <Link to={urls.personByDistinctId(conversation.ticket.distinct_id)}>+ <Person name={conversation.ticket.started_by} />+ </Link>+ )+ }+ const author = conversation.summary.messages[0]?.author+ return author ? <Person name={author} /> : <span className="text-muted">—</span>+ },+ },+ {+ title: 'Latest activity',+ key: 'latestActivity',+ align: 'left',+ width: 190,+ render: (_, conversation) => <LatestActivity conversation={conversation} />,+ },+ {+ title: 'Participants',+ key: 'participants',+ align: 'left',+ render: (_, conversation) => {+ if (conversation.source === 'email') {+ return (+ <ParticipantList+ participants={conversation.email.participants.map((participant) => ({+ key: participant.email,+ name: participant.display_name || participant.email,+ email: participant.email,+ personId: participant.kind === 'customer' ? participant.person_id : null,+ }))}+ />+ )+ }+ if (conversation.source === 'support') {+ return <Person name={conversation.ticket.started_by} />+ }+ const authors = [...new Set(conversation.summary.messages.map((message) => message.author))]+ return <ParticipantList participants={authors.map((author) => ({ key: author, name: author }))} />+ },+ },+ ]++ return (+ <div className="flex flex-col gap-3">+ {toolbar}+ {sourceFailureBanner}+ <LemonTable<AccountConversation>+ data-attr="account-conversations-table"+ size="small"+ embedded+ dataSource={filteredConversations}+ columns={columns}+ rowKey="id"+ tableLayout="fixed"+ pagination={{ pageSize: 10, useUrl: false }}+ expandable={{+ expandedRowRender: (conversation) => (+ <ConversationDetail accountId={accountId} conversation={conversation} />+ ),+ isRowExpanded: (conversation) => conversation.id === expandedConversationId,+ rowExpandable: () => true,+ showRowExpansionToggle: false,+ noIndent: true,+ }}+ emptyState={+ olderConversationCount > 0+ ? 'No loaded conversations match. Load older conversations to search more.'+ : 'No conversations match your search and filters.'+ }+ />+ {olderConversationCount > 0 && (+ <div className="flex items-center justify-end gap-3">+ <span className="text-xs text-muted">+ {olderConversationCount} older {olderConversationCount === 1 ? 'conversation' : 'conversations'}{' '}+ not loaded+ </span>+ <LemonButton+ type="secondary"+ size="small"+ loading={conversationsResultLoading}+ onClick={loadMoreConversations}+ >+ Load older conversations+ </LemonButton>+ </div>+ )}+ </div>+ )+}diff --git a/products/customer_analytics/frontend/components/Accounts/AccountEmailThreadsExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountEmailThreadsExpansion.tsxindex 906eae52583a..f3ff88ea5205 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountEmailThreadsExpansion.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountEmailThreadsExpansion.tsx@@ -1,6 +1,14 @@import { useActions, useValues } from 'kea'-import { LemonCard, LemonSkeleton, LemonTable, LemonTableColumns, LemonTag, Tooltip } from '@posthog/lemon-ui'+import {+ LemonButton,+ LemonCard,+ LemonSkeleton,+ LemonTable,+ LemonTableColumns,+ LemonTag,+ Tooltip,+} from '@posthog/lemon-ui'import { BigLeaguesHog } from 'lib/components/hedgehogs'import { TZLabel } from 'lib/components/TZLabel'@@ -137,6 +145,14 @@ export function AccountEmailThreadsExpansion({ accountId }: { accountId: stringconst { threadsResult, threadsResultLoading, page, expandedThreadId } = useValues(logic)const { setPage, openThread, closeThread } = useActions(logic)+ const toggleThread = (threadId: string): void => {+ if (threadId === expandedThreadId) {+ closeThread(threadId)+ } else {+ openThread(threadId)+ }+ }+if (threadsResult === NOT_LOADED || threadsResultLoading) {return <LemonSkeleton className="h-64 w-full" />}@@ -164,16 +180,38 @@ export function AccountEmailThreadsExpansion({ accountId }: { accountId: stringtitle: '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>+ <LemonButton+ type="tertiary"+ fullWidth+ noPadding+ className="justify-start text-left"+ aria-expanded={thread.id === expandedThreadId}+ onClick={() => toggleThread(thread.id)}+ >+ <div className="flex flex-col gap-1 py-1 max-w-xl min-w-0">+ <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>+ </LemonButton>),},{title: 'Participants',key: 'participants',- render: (_, thread) => <ParticipantList participants={thread.participants} />,+ render: (_, thread) => (+ <LemonButton+ type="tertiary"+ fullWidth+ noPadding+ className="justify-start text-left"+ aria-expanded={thread.id === expandedThreadId}+ onClick={() => toggleThread(thread.id)}+ >+ <ParticipantList participants={thread.participants} />+ </LemonButton>+ ),},{title: 'Messages',@@ -218,6 +256,7 @@ export function AccountEmailThreadsExpansion({ accountId }: { accountId: stringonRowExpand: (thread) => openThread(thread.id),onRowCollapse: (thread) => closeThread(thread.id),rowExpandable: () => true,+ showRowExpansionToggle: false,}}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 7bc53269f225..da140b6b604c 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx@@ -37,7 +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 { AccountConversationsExpansion } from './AccountConversationsExpansion'+import { accountConversationsLogic } from './accountConversationsLogic'import { accountEmailThreadsLogic } from './accountEmailThreadsLogic'import { AccountFeatureRequestsExpansion } from './AccountFeatureRequestsExpansion'import { accountLinksLogic } from './accountLinksLogic'@@ -51,10 +52,7 @@ import { accountRelatedUsersLogic } from './accountRelatedUsersLogic'import { AccountRelationshipsExpansion } from './AccountRelationshipsExpansion'import { accountRelationshipsLogic } from './accountRelationshipsLogic'import { accountsExpansionLogic } from './accountsExpansionLogic'-import { AccountSummariesExpansion } from './AccountSummariesExpansion'import { accountSummariesLogic } from './accountSummariesLogic'-import { AccountSupportTicketsExpansion } from './AccountSupportTicketsExpansion'-import { accountSupportTicketsLogic } from './accountSupportTicketsLogic'import { AccountsEvents } from './constants'import { EditAccountLinksButton } from './EditAccountLinksButton'@@ -182,7 +180,7 @@ export function AccountNotebooksExpansion({useMountedLogic(accountBillingLogic({ accountId, externalId, kind: 'spend' }))useMountedLogic(accountOpportunitiesLogic({ accountId }))useMountedLogic(accountSummariesLogic({ accountId }))- useMountedLogic(accountSupportTicketsLogic({ accountId }))+ useMountedLogic(accountConversationsLogic({ accountId }))useMountedLogic(accountEmailThreadsLogic({ accountId }))useMountedLogic(accountMeetingsLogic({ accountId }))const { setSearchTerm, setSorting, createNote } = useActions(logic)@@ -357,19 +355,9 @@ export function AccountNotebooksExpansion({content: <AccountOpportunitiesExpansion accountId={accountId} />,},{- key: 'summaries',- label: 'Summaries',- content: <AccountSummariesExpansion accountId={accountId} />,- },- {- key: 'support_tickets',- label: 'Support tickets',- content: <AccountSupportTicketsExpansion accountId={accountId} />,- },- {- key: 'email_threads',- label: 'Email threads',- content: <AccountEmailThreadsExpansion accountId={accountId} />,+ key: 'conversations',+ label: 'Conversations',+ content: <AccountConversationsExpansion accountId={accountId} />,},// Flag-gated here (not just inside the component) so the tab label hides too.!!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP] && {diff --git a/products/customer_analytics/frontend/components/Accounts/AccountSummariesExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountSummariesExpansion.tsxindex 52f59c32d81f..7e73eb27ffd0 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountSummariesExpansion.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountSummariesExpansion.tsx@@ -2,7 +2,7 @@ import clsx from 'clsx'import { useActions, useValues } from 'kea'import { ReactNode } from 'react'-import { LemonDropdown, LemonSelect, LemonSkeleton, LemonTag, Link, Spinner } from '@posthog/lemon-ui'+import { LemonDropdown, LemonSkeleton, LemonTag, Link, Spinner } from '@posthog/lemon-ui'import { BigLeaguesHog } from 'lib/components/hedgehogs'import { TZLabel } from 'lib/components/TZLabel'@@ -16,13 +16,7 @@ import {} from 'products/customer_analytics/frontend/generated/api.schemas'import { accountSummariesLogic, NOT_LOADED, SUMMARIES_PAGE_SIZE } from './accountSummariesLogic'--const CADENCE_OPTIONS: { value: SlackSummaryCadenceEnumApi | null; label: string }[] = [- { value: null, label: 'Off' },- { value: SlackSummaryCadenceEnumApi.Daily, label: 'Daily' },- { value: SlackSummaryCadenceEnumApi.Weekly, label: 'Weekly' },- { value: SlackSummaryCadenceEnumApi.Monthly, label: 'Monthly' },-]+import { AccountSummaryCadencePicker } from './AccountSummaryCadencePicker'function SummariesEmptyState({title,@@ -43,21 +37,6 @@ function SummariesEmptyState({)}-function CadencePicker({ accountId }: { accountId: string }): JSX.Element {- const { summariesResult, cadenceSaving } = useValues(accountSummariesLogic({ accountId }))- const { setCadence } = useActions(accountSummariesLogic({ accountId }))- return (- <LemonSelect<SlackSummaryCadenceEnumApi | null>- size="small"- value={summariesResult.cadence}- options={CADENCE_OPTIONS}- onChange={(value) => setCadence(value)}- disabledReason={cadenceSaving ? 'Saving…' : undefined}- data-attr="account-summary-cadence-picker"- />- )-}-function backfillDescription(cadence: SlackSummaryCadenceEnumApi | null): string {if (cadence === SlackSummaryCadenceEnumApi.Daily) {return 'Summarizing the last 7 days, one summary per day.'@@ -189,7 +168,7 @@ export function AccountSummariesExpansion({ accountId }: { accountId: string }):detail={`${backfillDescription(cadence)} This usually takes a minute.`}><Spinner className="text-xl" />- <CadencePicker accountId={accountId} />+ <AccountSummaryCadencePicker accountId={accountId} /></SummariesEmptyState>)}@@ -202,7 +181,7 @@ export function AccountSummariesExpansion({ accountId }: { accountId: string }):: "Get periodic AI summaries of this account's Slack channel, citing the original messages. Pick a cadence to turn them on."}>- <CadencePicker accountId={accountId} />+ <AccountSummaryCadencePicker accountId={accountId} /></SummariesEmptyState>)}@@ -220,7 +199,7 @@ export function AccountSummariesExpansion({ accountId }: { accountId: string }):</div><div className="flex items-center gap-2"><span className="text-muted text-sm">Cadence</span>- <CadencePicker accountId={accountId} />+ <AccountSummaryCadencePicker accountId={accountId} /></div></div>{summaries.map((summary) => (diff --git a/products/customer_analytics/frontend/components/Accounts/AccountSummaryCadencePicker.tsx b/products/customer_analytics/frontend/components/Accounts/AccountSummaryCadencePicker.tsxnew file mode 100644index 000000000000..2113e06383bf--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/AccountSummaryCadencePicker.tsx@@ -0,0 +1,31 @@+import { useActions, useValues } from 'kea'++import { LemonSelect } from '@posthog/lemon-ui'++import { SlackSummaryCadenceEnumApi } from 'products/customer_analytics/frontend/generated/api.schemas'++import { accountSummariesLogic } from './accountSummariesLogic'++const CADENCE_OPTIONS: { value: SlackSummaryCadenceEnumApi | null; label: string }[] = [+ { value: null, label: 'Off' },+ { value: SlackSummaryCadenceEnumApi.Daily, label: 'Daily' },+ { value: SlackSummaryCadenceEnumApi.Weekly, label: 'Weekly' },+ { value: SlackSummaryCadenceEnumApi.Monthly, label: 'Monthly' },+]++export function AccountSummaryCadencePicker({ accountId }: { accountId: string }): JSX.Element {+ const logic = accountSummariesLogic({ accountId })+ const { summariesResult, cadenceSaving } = useValues(logic)+ const { setCadence } = useActions(logic)++ return (+ <LemonSelect<SlackSummaryCadenceEnumApi | null>+ size="small"+ value={summariesResult.cadence}+ options={CADENCE_OPTIONS}+ onChange={setCadence}+ disabledReason={cadenceSaving ? 'Saving…' : undefined}+ data-attr="account-summary-cadence-picker"+ />+ )+}diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsxindex ffe4c2a63bdd..ab2ca1d65b4f 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx@@ -16,6 +16,8 @@ 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_SUMMARIES_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/summaries/'+const ACCOUNT_SUPPORT_TICKETS_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/support_tickets/'const ACCOUNT_RELATIONSHIPS_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/relationships/'const FEATURE_REQUESTS_ENDPOINT = 'api/projects/:team_id/feature_requests/'const RELATIONSHIP_DEFINITIONS_ENDPOINT = 'api/projects/:team_id/account_relationship_definitions/'@@ -170,6 +172,8 @@ const EXPANDED_ROW_FETCH_MOCKS = {[ORGANIZATION_MEMBERS_ENDPOINT]: { count: 0, next: null, previous: null, results: [] },[ACCOUNT_RELATIONSHIPS_ENDPOINT]: [],[ACCOUNT_EMAIL_THREADS_ENDPOINT]: EMPTY_EMAIL_THREADS,+ [ACCOUNT_SUMMARIES_ENDPOINT]: { count: 0, next: null, previous: null, results: [] },+ [ACCOUNT_SUPPORT_TICKETS_ENDPOINT]: [],}// Billing tab stories share the same account + notebooks mocks; they differ only in the insight and query responses.@@ -458,7 +462,7 @@ export const RowExpandedFeatureRequests: Story = {},}-export const RowExpandedEmailThreads: Story = {+export const RowExpandedConversations: Story = {render: () => <App />,parameters: {testOptions: {@@ -477,13 +481,34 @@ export const RowExpandedEmailThreads: Story = {subject: 'Renewal planning',preview: 'I shared the revised timeline with the team.',first_message_at: '2026-05-20T09:00:00Z',+ first_message: {+ sender: {+ name: 'Example buyer',+ email: '[email protected]',+ person_id: null,+ distinct_id: null,+ },+ sent_at: '2026-05-20T09:00:00Z',+ direction: 'inbound',+ },last_message_at: '2026-05-20T11:30:00Z',+ last_message: {+ sender: {+ name: 'Alice Anderson',+ email: '[email protected]',+ person_id: null,+ distinct_id: null,+ },+ sent_at: '2026-05-20T11:30:00Z',+ direction: 'outbound',+ },message_count: 2,participants: [{email: '[email protected]',display_name: 'Example buyer',kind: 'customer',+ person_id: null,},],},@@ -529,22 +554,37 @@ export const RowExpandedEmailThreads: Story = {play: async ({ canvasElement }) => {await expandFirstRow(canvasElement)const canvas = within(canvasElement)- await userEvent.click(await canvas.findByText('Email threads', {}, { timeout: 15000 }))+ await userEvent.click(await canvas.findByRole('tab', { name: 'Conversations' }, { timeout: 15000 }))await waitFor(() => {- if (!canvasElement.querySelector('[data-attr="account-email-threads-table"]')) {- throw new Error('Email threads table did not render')+ if (!canvasElement.querySelector('[data-attr="account-conversations-table"]')) {+ throw new Error('Conversations 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'))+ const table = canvasElement.querySelector('[data-attr="account-conversations-table"]') as HTMLElement+ if (within(table).queryByTitle('Show more')) {+ throw new Error('Conversation expansion toggle should not render')+ }+ await userEvent.click(await within(table).findByText('Renewal planning'))await waitFor(() => {if (!canvasElement.querySelector('[data-attr="account-email-thread-detail"]')) {throw new Error('Email thread detail did not render')}})+ await userEvent.click(await within(table).findByText('Renewal planning'))+ await waitFor(() => {+ if (canvasElement.querySelector('[data-attr="account-email-thread-detail"]')) {+ throw new Error('Email thread detail did not collapse')+ }+ })+ await userEvent.click(await within(table).findByText('Renewal planning'))+ await waitFor(() => {+ if (!canvasElement.querySelector('[data-attr="account-email-thread-detail"]')) {+ throw new Error('Email thread detail did not reopen')+ }+ })},}diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTable.test.ts b/products/customer_analytics/frontend/components/Accounts/AccountsTable.test.tsindex b8308a3549b6..1b630a9545b0 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsTable.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTable.test.ts@@ -50,7 +50,7 @@ describe('getCanonicalPropertyTab', () => {({ name, is_canonical: isCanonical }) as CustomPropertyDefinitionApiit('routes the last Slack message to the channel summaries', () => {- expect(getCanonicalPropertyTab(definition('Last Slack message at', true))).toBe('summaries')+ expect(getCanonicalPropertyTab(definition('Last Slack message at', true))).toBe('conversations')})it('does not link an ordinary property a user happened to name the same', () => {diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsxindex 7206a4485d8c..a7c276958a12 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx@@ -325,7 +325,7 @@ function CustomPropertyHistoryCell({}const CANONICAL_PROPERTY_TAB: Record<string, AccountExpansionTab> = {- 'Last Slack message at': 'summaries',+ 'Last Slack message at': 'conversations',}export function getCanonicalPropertyTab(definition: CustomPropertyDefinitionApi): AccountExpansionTab | undefined {diff --git a/products/customer_analytics/frontend/components/Accounts/accountConversationsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountConversationsLogic.test.tsnew file mode 100644index 000000000000..79ab30c76030--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/accountConversationsLogic.test.ts@@ -0,0 +1,234 @@+import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'++import { ApiError } from 'lib/api-error'++import { initKeaTests } from '~/test/init'++import {+ accountsEmailThreadsList,+ accountsSummariesList,+ accountsSupportTicketMessagesList,+ accountsSupportTicketsList,+} from 'products/customer_analytics/frontend/generated/api'++import { accountConversationsLogic } from './accountConversationsLogic'++jest.mock('products/customer_analytics/frontend/generated/api', () => ({+ ...jest.requireActual('products/customer_analytics/frontend/generated/api'),+ accountsEmailThreadsList: jest.fn(),+ accountsSummariesList: jest.fn(),+ accountsSupportTicketMessagesList: jest.fn(),+ accountsSupportTicketsList: jest.fn(),+}))++const mockEmailThreads = accountsEmailThreadsList as jest.MockedFunction<typeof accountsEmailThreadsList>+const mockSummaries = accountsSummariesList as jest.MockedFunction<typeof accountsSummariesList>+const mockSupportTicketMessages = accountsSupportTicketMessagesList as jest.MockedFunction<+ typeof accountsSupportTicketMessagesList+>+const mockSupportTickets = accountsSupportTicketsList as jest.MockedFunction<typeof accountsSupportTicketsList>++describe('accountConversationsLogic', () => {+ let logic: ReturnType<typeof accountConversationsLogic.build>++ beforeEach(() => {+ initKeaTests()+ jest.resetAllMocks()+ jest.spyOn(posthog, 'captureException').mockReturnValue(undefined as any)+ mockEmailThreads.mockResolvedValue({+ count: 1,+ next: null,+ previous: null,+ results: [+ {+ id: '11111111-1111-1111-1111-111111111111',+ subject: 'Renewal planning',+ preview: 'Latest email',+ first_message_at: '2026-08-01T09:00:00Z',+ first_message: {+ sender: {+ name: 'Example customer',+ email: '[email protected]',+ person_id: null,+ distinct_id: null,+ },+ sent_at: '2026-08-01T09:00:00Z',+ direction: 'inbound',+ },+ last_message_at: '2026-08-03T09:00:00Z',+ last_message: {+ sender: {+ name: 'Account manager',+ email: '[email protected]',+ person_id: null,+ distinct_id: null,+ },+ sent_at: '2026-08-03T09:00:00Z',+ direction: 'outbound',+ },+ message_count: 2,+ participants: [],+ },+ ],+ })+ mockSupportTickets.mockResolvedValue([+ {+ id: 'ticket-1',+ ticket_number: 42,+ status: 'open',+ last_message_at: '2026-08-02T09:00:00Z',+ last_message_text: 'Support preview',+ last_message: {+ sender: {+ name: 'Example customer',+ email: '[email protected]',+ person_id: null,+ distinct_id: '[email protected]',+ },+ sent_at: '2026-08-02T09:00:00Z',+ direction: 'inbound',+ },+ deep_link: '/support/tickets/42',+ created_at: '2026-08-01T09:00:00Z',+ started_by: 'Example customer',+ distinct_id: '[email protected]',+ },+ ])+ mockSupportTicketMessages.mockResolvedValue({+ count: 1,+ next: null,+ previous: null,+ results: [+ {+ id: '33333333-3333-3333-3333-333333333333',+ content: 'Support reply',+ author_name: 'Account manager',+ direction: 'outbound',+ is_private: false,+ created_at: '2026-08-02T10:00:00Z',+ },+ ],+ })+ mockSummaries.mockResolvedValue({+ count: 1,+ next: null,+ previous: null,+ results: [+ {+ id: '22222222-2222-2222-2222-222222222222',+ slack_channel_id: 'C012345',+ cadence: 'weekly',+ period_start: '2026-08-01T00:00:00Z',+ period_end: '2026-08-10T00:00:00Z',+ content: 'Slack summary',+ message_count: 2,+ messages: [+ {+ author: 'Example customer',+ sent_at: '2026-08-01T12:00:00Z',+ permalink: 'https://example.com/slack/1',+ },+ {+ author: 'Account manager',+ sent_at: '2026-08-02T12:00:00Z',+ permalink: 'https://example.com/slack/2',+ },+ ],+ generated_at: '2026-08-10T01:00:00Z',+ },+ ],+ })+ })++ afterEach(() => logic?.unmount())++ it('combines, sorts, searches, and filters conversations', async () => {+ logic = accountConversationsLogic({ accountId: 'account-1' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.filteredConversations.map((conversation) => conversation.source)).toEqual([+ 'slack',+ 'email',+ 'support',+ ])+ expect(+ logic.values.filteredConversations.find((conversation) => conversation.source === 'slack')?.occurredAt+ ).toBe('2026-08-10T01:00:00Z')++ logic.actions.setSearchTerm('support preview')+ expect(logic.values.filteredConversations.map((conversation) => conversation.source)).toEqual(['support'])++ logic.actions.setSearchTerm('Account manager')+ expect(logic.values.filteredConversations.map((conversation) => conversation.source)).toEqual(['slack'])++ logic.actions.setSearchTerm('')+ logic.actions.setSources(['email'])+ expect(logic.values.filteredConversations.map((conversation) => conversation.source)).toEqual(['email'])++ logic.actions.openConversation('support:ticket-1')+ await expectLogic(logic).toFinishAllListeners()+ expect(mockSupportTicketMessages).toHaveBeenCalledWith('997', 'account-1', 'ticket-1', {+ limit: 200,+ offset: 0,+ })+ expect(logic.values.supportTicketMessages['ticket-1'].results[0].content).toBe('Support reply')++ expect(logic.values.expandedSummaryMessageIds['22222222-2222-2222-2222-222222222222']).toBeUndefined()+ logic.actions.toggleSummaryMessages('22222222-2222-2222-2222-222222222222')+ expect(logic.values.expandedSummaryMessageIds['22222222-2222-2222-2222-222222222222']).toBe(true)+ })++ it('keeps available conversations and retries a forbidden source', async () => {+ const supportTickets = await mockSupportTickets('997', 'account-1')+ jest.clearAllMocks()+ mockSupportTickets.mockRejectedValueOnce(new ApiError('Forbidden', 403)).mockResolvedValueOnce(supportTickets)+ logic = accountConversationsLogic({ accountId: 'account-1' })+ logic.mount()++ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.conversationsResult.failedSources).toEqual(['support'])+ expect(logic.values.filteredConversations.map(({ source }) => source)).toEqual(['slack', 'email'])+ expect(logic.values.conversationsResult.loadFailed).toBeUndefined()+ expect(posthog.captureException).not.toHaveBeenCalled()++ await expectLogic(logic, () => logic.actions.loadConversations()).toFinishAllListeners()++ expect(logic.values.conversationsResult.failedSources).toEqual([])+ expect(logic.values.filteredConversations.map(({ source }) => source)).toEqual(['slack', 'email', 'support'])+ })++ it('loads older paginated conversations without replacing the current timeline', async () => {+ const firstPage = await mockSummaries('997', 'account-1', { limit: 50, offset: 0 })+ const olderSummary = {+ ...firstPage.results[0],+ id: '44444444-4444-4444-4444-444444444444',+ content: 'Older Slack summary',+ generated_at: '2026-07-10T01:00:00Z',+ }+ jest.clearAllMocks()+ mockSummaries+ .mockResolvedValueOnce({ ...firstPage, count: 2 })+ .mockRejectedValueOnce(new Error('network'))+ .mockResolvedValueOnce({ ...firstPage, count: 2, results: [olderSummary] })+ logic = accountConversationsLogic({ accountId: 'account-1' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.olderConversationCount).toBe(1)+ await expectLogic(logic, () => logic.actions.loadMoreConversations()).toFinishAllListeners()+ expect(logic.values.conversationsResult.failedSources).toEqual(['slack'])+ expect(logic.values.olderConversationCount).toBe(1)++ await expectLogic(logic, () => logic.actions.loadMoreConversations()).toFinishAllListeners()++ expect(mockSummaries).toHaveBeenLastCalledWith('997', 'account-1', { limit: 50, offset: 1 })+ expect(logic.values.conversationsResult.failedSources).toEqual([])+ expect(logic.values.olderConversationCount).toBe(0)+ expect(logic.values.conversationsResult.conversations?.map(({ id }) => id)).toContain(+ 'slack:44444444-4444-4444-4444-444444444444'+ )+ })+})diff --git a/products/customer_analytics/frontend/components/Accounts/accountConversationsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountConversationsLogic.tsnew file mode 100644index 000000000000..9829e2ccad27--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/accountConversationsLogic.ts@@ -0,0 +1,388 @@+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'++import { ApiError } from 'lib/api-error'+import { teamLogic } from 'scenes/teamLogic'++import {+ accountsEmailThreadsList,+ accountsSummariesList,+ accountsSupportTicketMessagesList,+ accountsSupportTicketsList,+} from 'products/customer_analytics/frontend/generated/api'+import type {+ AccountChannelSummaryApi,+ AccountEmailThreadApi,+ PaginatedAccountSupportTicketMessageListApi,+ SupportTicketApi,+} from 'products/customer_analytics/frontend/generated/api.schemas'++export type ConversationSource = 'email' | 'support' | 'slack'++export type AccountConversation =+ | { id: string; source: 'email'; occurredAt: string | null; email: AccountEmailThreadApi }+ | { id: string; source: 'support'; occurredAt: string | null; ticket: SupportTicketApi }+ | { id: string; source: 'slack'; occurredAt: string; summary: AccountChannelSummaryApi }++interface AccountConversationsResult {+ conversations: AccountConversation[] | null+ emailCount: number+ failedSources: ConversationSource[]+ loadFailed?: boolean+ summaryCount: number+}++export const NOT_LOADED: AccountConversationsResult = {+ conversations: null,+ emailCount: 0,+ failedSources: [],+ summaryCount: 0,+}+const LIST_LIMIT = 50++export interface AccountConversationsLogicProps {+ accountId: string+}++interface accountConversationsLogicValues {+ conversationsResult: AccountConversationsResult+ conversationsResultLoading: boolean+ currentTeamId: number | null+ expandedConversationId: string | null+ expandedSummaryMessageIds: Record<string, boolean>+ filteredConversations: AccountConversation[]+ olderConversationCount: number+ searchTerm: string+ sources: ConversationSource[]+ supportTicketMessageErrors: Record<string, boolean>+ supportTicketMessages: Record<string, PaginatedAccountSupportTicketMessageListApi>+ supportTicketMessagesLoading: Record<string, boolean>+}++interface accountConversationsLogicActions {+ closeConversation: (conversationId: string) => { conversationId: string }+ loadConversations: () => void+ loadConversationsFailure: (error: string, errorObject?: unknown) => { error: string; errorObject?: unknown }+ loadConversationsSuccess: (+ conversationsResult: AccountConversationsResult,+ payload?: unknown+ ) => { conversationsResult: AccountConversationsResult; payload?: unknown }+ loadMoreConversations: () => void+ loadMoreConversationsFailure: (error: string, errorObject?: unknown) => { error: string; errorObject?: unknown }+ loadMoreConversationsSuccess: (+ conversationsResult: AccountConversationsResult,+ payload?: unknown+ ) => { conversationsResult: AccountConversationsResult; payload?: unknown }+ loadSupportTicketMessages: (ticketId: string) => { ticketId: string }+ loadSupportTicketMessagesFailure: (ticketId: string) => { ticketId: string }+ loadSupportTicketMessagesSuccess: (+ ticketId: string,+ messages: PaginatedAccountSupportTicketMessageListApi+ ) => { ticketId: string; messages: PaginatedAccountSupportTicketMessageListApi }+ openConversation: (conversationId: string) => { conversationId: string }+ setSearchTerm: (searchTerm: string) => { searchTerm: string }+ setSources: (sources: ConversationSource[]) => { sources: ConversationSource[] }+ toggleSummaryMessages: (summaryId: string) => { summaryId: string }+}++interface accountConversationsLogicMeta {+ key: string+}++type accountConversationsLogicType = MakeLogicType<+ accountConversationsLogicValues,+ accountConversationsLogicActions,+ AccountConversationsLogicProps,+ accountConversationsLogicMeta+>++function createEmailConversations(emails: readonly AccountEmailThreadApi[]): AccountConversation[] {+ return emails.map(+ (email): AccountConversation => ({+ id: `email:${email.id}`,+ source: 'email',+ occurredAt: email.last_message?.sent_at ?? email.last_message_at,+ email,+ })+ )+}++function createSupportConversations(tickets: readonly SupportTicketApi[]): AccountConversation[] {+ return tickets.map(+ (ticket): AccountConversation => ({+ id: `support:${ticket.id}`,+ source: 'support',+ occurredAt: ticket.last_message?.sent_at ?? ticket.last_message_at,+ ticket,+ })+ )+}++function createSlackConversations(summaries: readonly AccountChannelSummaryApi[]): AccountConversation[] {+ return summaries.map(+ (summary): AccountConversation => ({+ id: `slack:${summary.id}`,+ source: 'slack',+ occurredAt: summary.generated_at,+ summary,+ })+ )+}++function sortConversations(conversations: AccountConversation[]): AccountConversation[] {+ return conversations.sort((left, right) => (right.occurredAt ?? '').localeCompare(left.occurredAt ?? ''))+}++function captureSourceFailure(source: ConversationSource, error: unknown): void {+ if (error instanceof ApiError && error.status === 403) {+ return+ }+ posthog.captureException(error instanceof Error ? error : new Error(`Failed to load ${source} conversations`), {+ scope: 'accountConversationsLogic.loadConversations',+ source,+ })+}++function searchableText(conversation: AccountConversation): string {+ if (conversation.source === 'email') {+ return `${conversation.email.subject} ${conversation.email.preview} ${conversation.email.participants+ .map((participant) => `${participant.display_name} ${participant.email}`)+ .join(' ')}`+ }+ if (conversation.source === 'support') {+ return `${conversation.ticket.ticket_number} ${conversation.ticket.last_message_text ?? ''} ${conversation.ticket.started_by}`+ }+ return `${conversation.summary.period_start} ${conversation.summary.period_end} ${conversation.summary.content} ${conversation.summary.messages.map(({ author }) => author).join(' ')}`+}++export const accountConversationsLogic = kea<accountConversationsLogicType>([+ path((key) => ['scenes', 'customerAnalytics', 'accounts', 'accountConversationsLogic', key]),+ props({} as AccountConversationsLogicProps),+ key((props) => props.accountId),+ connect(() => ({ values: [teamLogic, ['currentTeamId']] })),+ actions({+ setSearchTerm: (searchTerm: string) => ({ searchTerm }),+ setSources: (sources: ConversationSource[]) => ({ sources }),+ openConversation: (conversationId: string) => ({ conversationId }),+ closeConversation: (conversationId: string) => ({ conversationId }),+ loadSupportTicketMessages: (ticketId: string) => ({ ticketId }),+ loadSupportTicketMessagesSuccess: (+ ticketId: string,+ messages: PaginatedAccountSupportTicketMessageListApi+ ) => ({ ticketId, messages }),+ loadSupportTicketMessagesFailure: (ticketId: string) => ({ ticketId }),+ toggleSummaryMessages: (summaryId: string) => ({ summaryId }),+ }),+ loaders(({ props, values }) => ({+ conversationsResult: [+ NOT_LOADED,+ {+ loadConversations: async (): Promise<AccountConversationsResult> => {+ const [emailResult, supportResult, summaryResult] = await Promise.allSettled([+ accountsEmailThreadsList(String(values.currentTeamId), props.accountId, {+ limit: LIST_LIMIT,+ offset: 0,+ }),+ accountsSupportTicketsList(String(values.currentTeamId), props.accountId),+ accountsSummariesList(String(values.currentTeamId), props.accountId, {+ limit: LIST_LIMIT,+ offset: 0,+ }),+ ])+ const results = [+ ['email', emailResult],+ ['support', supportResult],+ ['slack', summaryResult],+ ] as const+ const failedSources = results+ .filter(([, result]) => result.status === 'rejected')+ .map(([source]) => source)+ for (const [source, result] of results) {+ if (result.status === 'rejected') {+ captureSourceFailure(source, result.reason)+ }+ }+ if (failedSources.length === results.length) {+ return {+ conversations: null,+ emailCount: 0,+ failedSources,+ loadFailed: true,+ summaryCount: 0,+ }+ }+ const conversations = sortConversations([+ ...(emailResult.status === 'fulfilled'+ ? createEmailConversations(emailResult.value.results)+ : []),+ ...(supportResult.status === 'fulfilled'+ ? createSupportConversations(supportResult.value)+ : []),+ ...(summaryResult.status === 'fulfilled'+ ? createSlackConversations(summaryResult.value.results)+ : []),+ ])+ return {+ conversations,+ emailCount: emailResult.status === 'fulfilled' ? emailResult.value.count : 0,+ failedSources,+ summaryCount: summaryResult.status === 'fulfilled' ? summaryResult.value.count : 0,+ }+ },+ loadMoreConversations: async (): Promise<AccountConversationsResult> => {+ const currentResult = values.conversationsResult+ if (!currentResult.conversations) {+ return currentResult+ }+ const loadedEmailCount = currentResult.conversations.filter(+ ({ source }) => source === 'email'+ ).length+ const loadedSummaryCount = currentResult.conversations.filter(+ ({ source }) => source === 'slack'+ ).length+ const [emailResult, summaryResult] = await Promise.allSettled([+ loadedEmailCount < currentResult.emailCount+ ? accountsEmailThreadsList(String(values.currentTeamId), props.accountId, {+ limit: LIST_LIMIT,+ offset: loadedEmailCount,+ })+ : Promise.resolve(null),+ loadedSummaryCount < currentResult.summaryCount+ ? accountsSummariesList(String(values.currentTeamId), props.accountId, {+ limit: LIST_LIMIT,+ offset: loadedSummaryCount,+ })+ : Promise.resolve(null),+ ])+ const conversations = [...currentResult.conversations]+ const failedSources = new Set(currentResult.failedSources)+ let emailCount = currentResult.emailCount+ let summaryCount = currentResult.summaryCount+ if (emailResult.status === 'fulfilled' && emailResult.value) {+ conversations.push(...createEmailConversations(emailResult.value.results))+ emailCount = emailResult.value.count+ failedSources.delete('email')+ } else if (emailResult.status === 'rejected') {+ failedSources.add('email')+ captureSourceFailure('email', emailResult.reason)+ }+ if (summaryResult.status === 'fulfilled' && summaryResult.value) {+ conversations.push(...createSlackConversations(summaryResult.value.results))+ summaryCount = summaryResult.value.count+ failedSources.delete('slack')+ } else if (summaryResult.status === 'rejected') {+ failedSources.add('slack')+ captureSourceFailure('slack', summaryResult.reason)+ }+ return {+ conversations: sortConversations([+ ...new Map(conversations.map((item) => [item.id, item])).values(),+ ]),+ emailCount,+ failedSources: [...failedSources],+ summaryCount,+ }+ },+ },+ ],+ })),+ reducers({+ searchTerm: ['', { setSearchTerm: (_, { searchTerm }) => searchTerm }],+ sources: [['email', 'support', 'slack'] as ConversationSource[], { setSources: (_, { sources }) => sources }],+ expandedConversationId: [+ null as string | null,+ {+ openConversation: (_, { conversationId }) => conversationId,+ closeConversation: (state, { conversationId }) => (state === conversationId ? null : state),+ },+ ],+ expandedSummaryMessageIds: [+ {} as Record<string, boolean>,+ {+ toggleSummaryMessages: (state, { summaryId }) => ({+ ...state,+ [summaryId]: !state[summaryId],+ }),+ },+ ],+ supportTicketMessages: [+ {} as Record<string, PaginatedAccountSupportTicketMessageListApi>,+ {+ loadSupportTicketMessagesSuccess: (state, { ticketId, messages }) => ({+ ...state,+ [ticketId]: messages,+ }),+ },+ ],+ supportTicketMessagesLoading: [+ {} as Record<string, boolean>,+ {+ loadSupportTicketMessages: (state, { ticketId }) => ({ ...state, [ticketId]: true }),+ loadSupportTicketMessagesSuccess: (state, { ticketId }) => ({ ...state, [ticketId]: false }),+ loadSupportTicketMessagesFailure: (state, { ticketId }) => ({ ...state, [ticketId]: false }),+ },+ ],+ supportTicketMessageErrors: [+ {} as Record<string, boolean>,+ {+ loadSupportTicketMessages: (state, { ticketId }) => ({ ...state, [ticketId]: false }),+ loadSupportTicketMessagesSuccess: (state, { ticketId }) => ({ ...state, [ticketId]: false }),+ loadSupportTicketMessagesFailure: (state, { ticketId }) => ({ ...state, [ticketId]: true }),+ },+ ],+ }),+ selectors({+ filteredConversations: [+ (selectors) => [selectors.conversationsResult, selectors.searchTerm, selectors.sources],+ (result, searchTerm, sources): AccountConversation[] => {+ const normalizedSearch = searchTerm.trim().toLowerCase()+ return (result.conversations ?? []).filter(+ (conversation: AccountConversation) =>+ sources.includes(conversation.source) &&+ (!normalizedSearch || searchableText(conversation).toLowerCase().includes(normalizedSearch))+ )+ },+ ],+ olderConversationCount: [+ (selectors) => [selectors.conversationsResult],+ (result: AccountConversationsResult): number => {+ const conversations: AccountConversation[] = result.conversations ?? []+ const loadedEmailCount = conversations.filter(({ source }) => source === 'email').length+ const loadedSummaryCount = conversations.filter(({ source }) => source === 'slack').length+ return (+ Math.max(0, result.emailCount - loadedEmailCount) ++ Math.max(0, result.summaryCount - loadedSummaryCount)+ )+ },+ ],+ }),+ listeners(({ actions, props, values }) => ({+ openConversation: ({ conversationId }) => {+ if (!conversationId.startsWith('support:')) {+ return+ }+ const ticketId = conversationId.slice('support:'.length)+ if (!values.supportTicketMessages[ticketId] && !values.supportTicketMessagesLoading[ticketId]) {+ actions.loadSupportTicketMessages(ticketId)+ }+ },+ loadSupportTicketMessages: async ({ ticketId }) => {+ try {+ const messages = await accountsSupportTicketMessagesList(+ String(values.currentTeamId),+ props.accountId,+ ticketId,+ { limit: 200, offset: 0 }+ )+ actions.loadSupportTicketMessagesSuccess(ticketId, messages)+ } catch (error) {+ posthog.captureException(error as Error, {+ scope: 'accountConversationsLogic.loadSupportTicketMessages',+ })+ actions.loadSupportTicketMessagesFailure(ticketId)+ }+ },+ })),+ afterMount(({ actions }) => actions.loadConversations()),+])diff --git a/products/customer_analytics/frontend/components/Accounts/accountEmailThreadsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountEmailThreadsLogic.test.tsindex ee76ac5526fd..529438146ab3 100644--- a/products/customer_analytics/frontend/components/Accounts/accountEmailThreadsLogic.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountEmailThreadsLogic.test.ts@@ -28,7 +28,27 @@ const thread = {subject: 'Account review',preview: 'Latest message',first_message_at: '2026-08-01T10:00:00Z',+ first_message: {+ sender: {+ name: 'Example customer',+ email: '[email protected]',+ person_id: null,+ distinct_id: null,+ },+ sent_at: '2026-08-01T10:00:00Z',+ direction: 'inbound',+ },last_message_at: '2026-08-01T11:00:00Z',+ last_message: {+ sender: {+ name: 'Account manager',+ email: '[email protected]',+ person_id: null,+ distinct_id: null,+ },+ sent_at: '2026-08-01T11:00:00Z',+ direction: 'outbound',+ },message_count: 2,participants: [],} as AccountEmailThreadApidiff --git a/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.tsindex af1cc827377c..dfcfb0456a5e 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts@@ -11,9 +11,7 @@ export type AccountExpansionTab =| 'usage'| 'spend'| 'opportunities'- | 'summaries'- | 'support_tickets'- | 'email_threads'+ | 'conversations'| 'meetings'| 'event_stream'@@ -25,9 +23,7 @@ export const ACCOUNT_EXPANSION_TABS: AccountExpansionTab[] = ['usage','spend','opportunities',- 'summaries',- 'support_tickets',- 'email_threads',+ 'conversations','meetings','event_stream',]diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex c587465e3ef4..d2289fedaae8 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -476,6 +476,50 @@ export interface PatchedAccountApi {readonly updated_at?: string | null}+export interface ConversationMessageSenderApi {+ /** Display name of the message sender. */+ readonly name: string+ /**+ * Email address of the message sender, when available.+ * @nullable+ */+ readonly email: string | null+ /**+ * UUID of the matched PostHog person, when available.+ * @nullable+ */+ readonly person_id: string | null+ /**+ * Distinct ID of the sender, when available.+ * @nullable+ */+ readonly distinct_id: string | null+}++/**+ * * `inbound` - Inbound+ * * `outbound` - Outbound+ */+export type EmailThreadMessageDirectionEnumApi =+ (typeof EmailThreadMessageDirectionEnumApi)[keyof typeof EmailThreadMessageDirectionEnumApi]++export const EmailThreadMessageDirectionEnumApi = {+ Inbound: 'inbound',+ Outbound: 'outbound',+} as const++export interface ConversationMessageSummaryApi {+ /** Sender of the message. */+ readonly sender: ConversationMessageSenderApi+ /** Timestamp from the message source. */+ readonly sent_at: string+ /** Whether PostHog received or sent the message.+ *+ * * `inbound` - Inbound+ * * `outbound` - Outbound */+ readonly direction: EmailThreadMessageDirectionEnumApi+}+/*** * `internal` - Internal* * `customer` - Customer@@ -498,6 +542,11 @@ export interface AccountEmailThreadParticipantApi {* * `internal` - Internal* * `customer` - Customer */readonly kind: EmailThreadParticipantKindEnumApi+ /**+ * UUID of the matched PostHog person for a customer participant, when available.+ * @nullable+ */+ readonly person_id: string | null}export interface AccountEmailThreadApi {@@ -512,11 +561,15 @@ export interface AccountEmailThreadApi {* @nullable*/readonly first_message_at: string | null+ /** Sender, timestamp, and direction of the first captured message, when available. */+ readonly first_message: ConversationMessageSummaryApi | null/*** Source timestamp of the latest captured message.* @nullable*/readonly last_message_at: string | null+ /** Sender, timestamp, and direction of the latest captured message, when available. */+ readonly last_message: ConversationMessageSummaryApi | null/** Number of captured messages in the thread. */readonly message_count: number/** Participants included in the email thread. */@@ -539,18 +592,6 @@ export interface AccountEmailThreadAddressApi {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@@ -702,8 +743,43 @@ export interface SupportTicketApi {* @nullable*/readonly last_message_text: string | null+ /** Sender, timestamp, and direction of the latest public message, when available. */+ readonly last_message: ConversationMessageSummaryApi | null/** Absolute URL to open this ticket in the app. */readonly deep_link: string+ /** When the ticket conversation started. */+ readonly created_at: string+ /** Display name of the customer who started the ticket. */+ readonly started_by: string+ /** Distinct ID of the customer who started the ticket. */+ readonly distinct_id: string+}++export interface AccountSupportTicketMessageApi {+ /** UUID of the support ticket message. */+ readonly id: string+ /** Plain-text message content. */+ readonly content: string+ /** Display name of the message author. */+ readonly author_name: string+ /** Whether PostHog received or sent the message.+ *+ * * `inbound` - Inbound+ * * `outbound` - Outbound */+ readonly direction: EmailThreadMessageDirectionEnumApi+ /** Whether the message is an internal note hidden from the customer. */+ readonly is_private: boolean+ /** When the message was created. */+ readonly created_at: string+}++export interface PaginatedAccountSupportTicketMessageListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: AccountSupportTicketMessageApi[]}/**@@ -2388,6 +2464,17 @@ export type AccountsSummariesListParams = {offset?: number}+export type AccountsSupportTicketMessagesListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}+export type AnnouncementsListParams = {/*** 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 c79a78c23c24..8d2c354183f6 100644--- a/products/customer_analytics/frontend/generated/api.ts+++ b/products/customer_analytics/frontend/generated/api.ts@@ -23,6 +23,7 @@ import type {AccountsNotebooksListParams,AccountsRelationshipsListParams,AccountsSummariesListParams,+ AccountsSupportTicketMessagesListParams,AnnouncementApi,AnnouncementChannelApi,AnnouncementsListParams,@@ -71,6 +72,7 @@ import type {PaginatedAccountNoteListApi,PaginatedAccountNotebookListApi,PaginatedAccountRelationshipDefinitionListApi,+ PaginatedAccountSupportTicketMessageListApi,PaginatedAnnouncementListApi,PaginatedCustomPropertyDefinitionListApi,PaginatedCustomPropertySourceListApi,@@ -711,6 +713,43 @@ export const accountsSupportTicketsList = async (})}+export const getAccountsSupportTicketMessagesListUrl = (+ projectId: string,+ id: string,+ ticketId: string,+ params?: AccountsSupportTicketMessagesListParams+) => {+ 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}/support_tickets/${ticketId}/?${stringifiedParams}`+ : `/api/projects/${projectId}/accounts/${id}/support_tickets/${ticketId}/`+}++export const accountsSupportTicketMessagesList = async (+ projectId: string,+ id: string,+ ticketId: string,+ params?: AccountsSupportTicketMessagesListParams,+ options?: RequestInit+): Promise<PaginatedAccountSupportTicketMessageListApi> => {+ return apiMutator<PaginatedAccountSupportTicketMessageListApi>(+ getAccountsSupportTicketMessagesListUrl(projectId, id, ticketId, params),+ {+ ...options,+ method: 'GET',+ }+ )+}+export const getAnnouncementsListUrl = (projectId: string, params?: AnnouncementsListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yamlindex c627573dc0c9..9189570c7367 100644--- a/products/customer_analytics/mcp/tools.yaml+++ b/products/customer_analytics/mcp/tools.yaml@@ -406,6 +406,9 @@ tools:covered, even if the account is later rebound to another channel. Returns an empty list when the account hasno bound channel, summaries are off (`slack_summary_cadence` is null), or nothing has been generated yet.feature_flag: customer-analytics-csp+ accounts-support-ticket-messages-list:+ operation: accounts_support_ticket_messages_list+ enabled: falseaccounts-support-tickets-list:operation: accounts_support_tickets_listenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 74b9a751d627..926d8d90e1af 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -334,6 +334,50 @@ export namespace Schemas {value?: (string | number | boolean)[] | string | number | boolean | null;}+ export interface ConversationMessageSender {+ /** Display name of the message sender. */+ readonly name: string;+ /**+ * Email address of the message sender, when available.+ * @nullable+ */+ readonly email: string | null;+ /**+ * UUID of the matched PostHog person, when available.+ * @nullable+ */+ readonly person_id: string | null;+ /**+ * Distinct ID of the sender, when available.+ * @nullable+ */+ readonly distinct_id: string | null;+ }++ /**+ * * `inbound` - Inbound+ * * `outbound` - Outbound+ */+ export type EmailThreadMessageDirectionEnum = typeof EmailThreadMessageDirectionEnum[keyof typeof EmailThreadMessageDirectionEnum];+++ export const EmailThreadMessageDirectionEnum = {+ Inbound: 'inbound',+ Outbound: 'outbound',+ } as const;++ export interface ConversationMessageSummary {+ /** Sender of the message. */+ readonly sender: ConversationMessageSender;+ /** Timestamp from the message source. */+ readonly sent_at: string;+ /** Whether PostHog received or sent the message.+ *+ * * `inbound` - Inbound+ * * `outbound` - Outbound */+ readonly direction: EmailThreadMessageDirectionEnum;+ }+/*** * `internal` - Internal* * `customer` - Customer@@ -356,6 +400,11 @@ export namespace Schemas {* * `internal` - Internal* * `customer` - Customer */readonly kind: EmailThreadParticipantKindEnum;+ /**+ * UUID of the matched PostHog person for a customer participant, when available.+ * @nullable+ */+ readonly person_id: string | null;}export interface AccountEmailThread {@@ -370,11 +419,15 @@ export namespace Schemas {* @nullable*/readonly first_message_at: string | null;+ /** Sender, timestamp, and direction of the first captured message, when available. */+ readonly first_message: ConversationMessageSummary | null;/*** Source timestamp of the latest captured message.* @nullable*/readonly last_message_at: string | null;+ /** Sender, timestamp, and direction of the latest captured message, when available. */+ readonly last_message: ConversationMessageSummary | null;/** Number of captured messages in the thread. */readonly message_count: number;/** Participants included in the email thread. */@@ -388,18 +441,6 @@ export namespace Schemas {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;@@ -575,6 +616,24 @@ export namespace Schemas {user: number;}+ export interface AccountSupportTicketMessage {+ /** UUID of the support ticket message. */+ readonly id: string;+ /** Plain-text message content. */+ readonly content: string;+ /** Display name of the message author. */+ readonly author_name: string;+ /** Whether PostHog received or sent the message.+ *+ * * `inbound` - Inbound+ * * `outbound` - Outbound */+ readonly direction: EmailThreadMessageDirectionEnum;+ /** Whether the message is an internal note hidden from the customer. */+ readonly is_private: boolean;+ /** When the message was created. */+ readonly created_at: string;+ }+export type BounceRatePageViewMode = typeof BounceRatePageViewMode[keyof typeof BounceRatePageViewMode];@@ -50741,6 +50800,15 @@ export namespace Schemas {results: AccountRelationshipDefinition[];}+ export interface PaginatedAccountSupportTicketMessageList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: AccountSupportTicketMessage[];+ }+export interface PaginatedActionList {count: number;/** @nullable */@@ -79002,8 +79070,16 @@ export namespace Schemas {* @nullable*/readonly last_message_text: string | null;+ /** Sender, timestamp, and direction of the latest public message, when available. */+ readonly last_message: ConversationMessageSummary | null;/** Absolute URL to open this ticket in the app. */readonly deep_link: string;+ /** When the ticket conversation started. */+ readonly created_at: string;+ /** Display name of the customer who started the ticket. */+ readonly started_by: string;+ /** Distinct ID of the customer who started the ticket. */+ readonly distinct_id: string;}/**@@ -85825,6 +85901,17 @@ export namespace Schemas {offset?: number;};+ export type AccountsSupportTicketMessagesListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };+export type ActionsListParams = {/*** Comma-separated list of creator user ids. Returns only actions created by these users.