: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(persons): emails tab on person profile (#66988)
Meikel Ratzd08afb3b9301
diff --git a/frontend/src/scenes/persons/PersonEmailsTab.tsx b/frontend/src/scenes/persons/PersonEmailsTab.tsxnew file mode 100644index 000000000000..135d740b237c--- /dev/null+++ b/frontend/src/scenes/persons/PersonEmailsTab.tsx@@ -0,0 +1,85 @@+import { useValues } from 'kea'+import { useState } from 'react'++import { HedgehogGreek } from '@posthog/brand/hoggies'+import { LemonTable, Link } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { urls } from 'scenes/urls'++import { EmailViewerModal } from 'products/workflows/frontend/Workflows/EmailViewerModal'+import { MessageAsset } from 'products/workflows/frontend/Workflows/messageAssetsApi'++import { personEmailsLogic } from './personEmailsLogic'++interface PersonEmailsTabProps {+ teamId: number+ personId: string+}++function EmptyEmails(): JSX.Element {+ return (+ <div className="flex flex-col bg-surface-primary rounded px-4 py-8 items-center text-center mx-auto">+ <HedgehogGreek width="100" height="100" className="mb-4" />+ <h2 className="text-xl leading-tight">No emails sent to this person</h2>+ <p className="text-sm text-balance text-tertiary">+ Once a workflow sends this person an email, it will show up here.+ </p>+ </div>+ )+}++export function PersonEmailsTab({ teamId, personId }: PersonEmailsTabProps): JSX.Element {+ const logic = personEmailsLogic({ teamId, personId })+ const { emails, emailsLoading } = useValues(logic)+ const [selected, setSelected] = useState<MessageAsset | null>(null)++ return (+ <>+ <LemonTable+ loading={emailsLoading}+ dataSource={emails}+ onRow={(asset: MessageAsset) => ({+ onClick: () => setSelected(asset),+ className: 'cursor-pointer',+ })}+ emptyState={<EmptyEmails />}+ columns={[+ {+ title: 'Subject',+ dataIndex: 'subject',+ key: 'subject',+ },+ {+ title: 'Workflow',+ key: 'function_id',+ render: (_, asset: MessageAsset) => (+ <Link+ to={`${urls.workflow(asset.function_id, 'workflow')}?assetInvocation=${encodeURIComponent(+ asset.invocation_id+ )}`}+ onClick={(e) => e.stopPropagation()}+ >+ {asset.function_name || asset.function_id}+ </Link>+ ),+ },+ {+ title: 'Sent',+ key: 'sent_at',+ render: (_, asset: MessageAsset) => <TZLabel time={asset.sent_at} />,+ },+ ]}+ />+ <EmailViewerModal+ workflowId={selected?.function_id ?? ''}+ invocationId={selected?.invocation_id ?? ''}+ actionId={selected?.action_id ?? ''}+ isOpen={!!selected}+ onClose={() => setSelected(null)}+ title={selected?.subject || 'Email'}+ description={selected ? `Sent to ${selected.recipient}` : undefined}+ />+ </>+ )+}diff --git a/frontend/src/scenes/persons/PersonScene.tsx b/frontend/src/scenes/persons/PersonScene.tsxindex 73bf52f225a7..be3dee0ef0b4 100644--- a/frontend/src/scenes/persons/PersonScene.tsx+++ b/frontend/src/scenes/persons/PersonScene.tsx@@ -10,6 +10,7 @@ import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'import { NotFound } from 'lib/components/NotFound'import { PropertiesTable } from 'lib/components/PropertiesTable'import { TZLabel } from 'lib/components/TZLabel'+import { FEATURE_FLAGS } from 'lib/constants'import { groupsAccessLogic } from 'lib/introductions/groupsAccessLogic'import { IconOpenInApp } from 'lib/lemon-ui/icons'import { LemonBanner } from 'lib/lemon-ui/LemonBanner'@@ -17,6 +18,7 @@ import { LemonTabs } from 'lib/lemon-ui/LemonTabs'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { SpinnerOverlay } from 'lib/lemon-ui/Spinner/Spinner'import { Tooltip } from 'lib/lemon-ui/Tooltip'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { copyToClipboard } from 'lib/utils/copyToClipboard'import { isMobile } from 'lib/utils/dom'import { pluralize } from 'lib/utils/strings'@@ -45,6 +47,7 @@ import { FeedbackButton } from 'products/customer_analytics/frontend/components/import { MergeSplitPerson } from './MergeSplitPerson'import { asDisplay, pickBestPersonDistinctId } from './person-utils'import { PersonCohorts } from './PersonCohorts'+import { PersonEmailsTab } from './PersonEmailsTab'import { PersonLogsTab } from './PersonLogsTab'import PersonProfileCanvas from './PersonProfileCanvas'import { PERSON_EVENTS_CONTEXT_KEY, PersonsLogicProps, personsLogic } from './personsLogic'@@ -207,6 +210,8 @@ export function PersonScene(): JSX.Element | null {const { currentTeam } = useValues(teamLogic)const { addProductIntentForCrossSell } = useActions(teamLogic)const { user } = useValues(userLogic)+ const { featureFlags } = useValues(featureFlagLogic)+ const emailAssetsUIEnabled = !!featureFlags[FEATURE_FLAGS.WORKFLOW_EMAIL_ASSETS_UI]const eventsQueryLogicKey = `${PERSON_EVENTS_CONTEXT_KEY}-${mountedPersonsLogic.key}`if (personError) {@@ -395,6 +400,13 @@ export function PersonScene(): JSX.Element | null {label: <span data-attr="persons-logs-tab">Logs</span>,content: <PersonLogsTab person={person} />,},+ emailAssetsUIEnabled && person.uuid+ ? {+ key: PersonsTabType.EMAILS,+ label: <span data-attr="persons-emails-tab">Emails</span>,+ content: <PersonEmailsTab teamId={currentTeam?.id ?? 0} personId={String(person.uuid)} />,+ }+ : false,{key: PersonsTabType.EXCEPTIONS,label: <span data-attr="persons-exceptions-tab">Exceptions</span>,diff --git a/frontend/src/scenes/persons/personEmailsLogic.ts b/frontend/src/scenes/persons/personEmailsLogic.tsnew file mode 100644index 000000000000..c188c64cc009--- /dev/null+++ b/frontend/src/scenes/persons/personEmailsLogic.ts@@ -0,0 +1,30 @@+import { kea, key, path, props } from 'kea'+import { lazyLoaders } from 'kea-loaders'++import { getPersonMessageAssets, MessageAsset } from 'products/workflows/frontend/Workflows/messageAssetsApi'++import type { personEmailsLogicType } from './personEmailsLogicType'++export interface PersonEmailsLogicProps {+ teamId: number+ personId: string+}++export const personEmailsLogic = kea<personEmailsLogicType>([+ path(['scenes', 'persons', 'personEmailsLogic']),+ props({} as PersonEmailsLogicProps),+ key((props) => `${props.teamId}-${props.personId}`),+ lazyLoaders(({ props }) => ({+ emails: [+ [] as MessageAsset[],+ {+ loadEmails: async () => {+ if (!props.personId) {+ return []+ }+ return await getPersonMessageAssets(props.teamId, props.personId)+ },+ },+ ],+ })),+])diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 81d304713af7..ae5d34af28be 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -1821,6 +1821,7 @@ export enum PersonsTabType {RELATED = 'related',HISTORY = 'history',FEATURE_FLAGS = 'featureFlags',+ EMAILS = 'emails',}export enum GroupsTabType {diff --git a/posthog/api/person.py b/posthog/api/person.pyindex d51c8375a014..dadcd53a8ef6 100644--- a/posthog/api/person.py+++ b/posthog/api/person.py@@ -1,6 +1,7 @@import jsonimport uuidimport builtins+import dataclassesfrom datetime import UTC, datetime, timedeltafrom typing import Any, List, Optional, TypeVar, Union, cast # noqa: UP035@@ -69,11 +70,23 @@ from posthog.queries.properties_timeline import PropertiesTimelinefrom posthog.rate_limit import ClickHouseBurstRateThrottle, PersonalApiKeyRateThrottle, UserOrEmailRateThrottlefrom posthog.renderers import SafeJSONRendererfrom posthog.tasks.split_person import split_person-from posthog.utils import format_query_params_absolute_url, is_anonymous_id, refresh_requested_by_client+from posthog.utils import (+ format_query_params_absolute_url,+ is_anonymous_id,+ refresh_requested_by_client,+ relative_date_parse_with_delta_mapping,+)from products.cohorts.backend.models.cohort import Cohortfrom products.cohorts.backend.models.util import get_all_cohort_ids_by_person_uuidfrom products.product_analytics.backend.api.insight import capture_legacy_api_call+from products.workflows.backend.api.message_assets import (+ MessageAssetSerializer,+ PersonMessageAssetsRequestSerializer,+ fetch_message_assets_for_person,+ workflow_email_assets_ui_enabled,+)+from products.workflows.backend.models.hog_flow.hog_flow import HogFlowlogger = structlog.get_logger(__name__)tracer = trace.get_tracer(__name__)@@ -1448,6 +1461,47 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):return response.Response(data=properties_timeline)+ @extend_schema(+ parameters=[PersonMessageAssetsRequestSerializer],+ responses=MessageAssetSerializer(many=True),+ )+ @action(methods=["GET"], detail=True, required_scopes=["person:read"], pagination_class=None, filter_backends=[])+ def emails(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:+ person = self.get_object()+ if not workflow_email_assets_ui_enabled(self.team, request.user):+ raise NotFound()+ param_serializer = PersonMessageAssetsRequestSerializer(data=request.query_params)+ param_serializer.is_valid(raise_exception=True)+ params = param_serializer.validated_data++ tag_queries(product=ProductKey.PERSONS, feature=Feature.QUERY)++ after_date, _, _ = relative_date_parse_with_delta_mapping(params["after"], self.team.timezone_info)+ before_date = None+ if params.get("before"):+ before_date, _, _ = relative_date_parse_with_delta_mapping(params["before"], self.team.timezone_info)++ data = fetch_message_assets_for_person(+ team_id=self.team_id,+ person_id=str(person.uuid),+ limit=params["limit"],+ offset=params["offset"],+ after=after_date,+ before=before_date,+ )+ # Single lookup for every workflow referenced by this page of rows so the tab shows+ # human-readable names instead of raw UUIDs. Deleted workflows drop out of the map+ # and the row's `function_name` stays empty — the frontend falls back to `function_id`.+ # HogFlow.id is a UUID column; ClickHouse function_id is a plain string, so coerce+ # both sides to string when building the lookup dict.+ function_ids = {row.function_id for row in data}+ name_by_id = {+ str(pk): (name or "")+ for pk, name in HogFlow.objects.filter(team_id=self.team_id, id__in=function_ids).values_list("id", "name")+ }+ enriched = [dataclasses.replace(row, function_name=name_by_id.get(row.function_id, "")) for row in data]+ return response.Response(MessageAssetSerializer(enriched, many=True).data)+@action(methods=["GET"], detail=False)def lifecycle(self, request: request.Request) -> response.Response:team = cast(User, request.user).teamdiff --git a/products/persons/frontend/generated/api.schemas.ts b/products/persons/frontend/generated/api.schemas.tsindex dc636671a50b..e262fc8aff35 100644--- a/products/persons/frontend/generated/api.schemas.ts+++ b/products/persons/frontend/generated/api.schemas.ts@@ -234,6 +234,33 @@ export interface PersonDeletePropertyRequestApi {$unset: string}+export interface MessageAssetApi {+ /** The workflow run this email was sent in. */+ invocation_id: string+ /** The email step (action node) within the workflow that sent this email. */+ action_id: string+ /** The workflow id that sent this email — used to navigate from a person's Emails tab back into the originating workflow. */+ function_id: string+ /** Human-readable workflow name for display. Empty when the workflow has been deleted; clients should fall back to function_id in that case. */+ function_name: string+ /** The batch run this email belongs to, for batch-triggered workflows. Empty for event-triggered runs. */+ parent_run_id: string+ /** Asset kind. Currently always 'email'. */+ kind: string+ /** The recipient's distinct_id. */+ distinct_id: string+ /** The recipient's person UUID, if resolved. */+ person_id: string+ /** The recipient email address. */+ recipient: string+ /** The email subject line. */+ subject: string+ /** Delivery status at capture time. Currently always 'sent'. */+ status: string+ /** When the email was sent. */+ sent_at: string+}+export interface PersonSplitRequestApi {/*** The distinct_id to **keep** on this person; every *other* distinct_id is moved to its own new single-id person. If omitted, the first distinct_id on the person is kept. The original person always retains its properties; to clear individual properties afterward, use the delete_property endpoint. To surgically *remove* one or more distinct_ids while leaving the merge intact, use `distinct_ids_to_split` instead — these parameters are inverses of each other and cannot be combined.@@ -458,6 +485,38 @@ export const PersonsDeletePropertyCreateFormat = {Json: 'json',} as const+export type PersonsEmailsListParams = {+ /**+ * Start of the time range, matched on sent time. Relative ('-30d', '-24h') or ISO 8601. Defaults to -30d (the retention window) — bounds the ClickHouse partition scan.+ * @minLength 1+ */+ after?: string+ /**+ * End of the time range, matched on sent time. Same format as 'after'. Defaults to now.+ * @minLength 1+ */+ before?: string+ format?: PersonsEmailsListFormat+ /**+ * Maximum number of emails to return (1-500, default 50).+ * @minimum 1+ * @maximum 500+ */+ limit?: number+ /**+ * Number of emails to skip, for pagination.+ * @minimum 0+ */+ offset?: number+}++export type PersonsEmailsListFormat = (typeof PersonsEmailsListFormat)[keyof typeof PersonsEmailsListFormat]++export const PersonsEmailsListFormat = {+ Csv: 'csv',+ Json: 'json',+} as const+export type PersonsPropertiesTimelineRetrieveParams = {format?: PersonsPropertiesTimelineRetrieveFormat}diff --git a/products/persons/frontend/generated/api.ts b/products/persons/frontend/generated/api.tsindex 81c7c955f53a..2ab0a4d3d246 100644--- a/products/persons/frontend/generated/api.ts+++ b/products/persons/frontend/generated/api.ts@@ -9,6 +9,7 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'* OpenAPI spec version: 1.0.0*/import type {+ MessageAssetApi,PaginatedAsyncDeletionStatusListApi,PaginatedPersonRecordListApi,PatchedPersonRecordApi,@@ -28,6 +29,7 @@ import type {PersonsCohortsRetrieveParams,PersonsDeletePropertyCreateParams,PersonsDeletionStatusListParams,+ PersonsEmailsListParams,PersonsFunnelCreateParams,PersonsFunnelRetrieveParams,PersonsLifecycleRetrieveParams,@@ -265,6 +267,37 @@ export const personsDeletePropertyCreate = async (})}+export const getPersonsEmailsListUrl = (projectId: string, id: number, params?: PersonsEmailsListParams) => {+ 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}/persons/${id}/emails/?${stringifiedParams}`+ : `/api/projects/${projectId}/persons/${id}/emails/`+}++/**+ * This endpoint is meant for reading and deleting persons. To create or update persons, we recommend using the [capture API](https://posthog.com/docs/api/capture), the `$set` and `$unset` [properties](https://posthog.com/docs/product-analytics/user-properties), or one of our SDKs.+ */+export const personsEmailsList = async (+ projectId: string,+ id: number,+ params?: PersonsEmailsListParams,+ options?: RequestInit+): Promise<MessageAssetApi[]> => {+ return apiMutator<MessageAssetApi[]>(getPersonsEmailsListUrl(projectId, id, params), {+ ...options,+ method: 'GET',+ })+}+export const getPersonsPropertiesTimelineRetrieveUrl = (projectId: string,id: number,diff --git a/products/persons/mcp/tools.yaml b/products/persons/mcp/tools.yamlindex a28f2f721969..549fc59f8c76 100644--- a/products/persons/mcp/tools.yaml+++ b/products/persons/mcp/tools.yaml@@ -55,6 +55,9 @@ tools:persons-deletion-status-list:operation: persons_deletion_status_listenabled: false+ persons-emails-list:+ operation: persons_emails_list+ enabled: falsepersons-funnel-create:operation: persons_funnel_createenabled: falsediff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex 2d9e81ac16f0..2be7a6c3abc3 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -1,6 +1,7 @@import reimport jsonimport uuid as uuid_mod+import dataclassesfrom datetime import timedeltafrom typing import Optional, cast@@ -1632,7 +1633,8 @@ class HogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMixin, vieafter=after_date,before=before_date,)- return Response(MessageAssetSerializer(data, many=True).data)+ enriched = [dataclasses.replace(row, function_name=obj.name or "") for row in data]+ return Response(MessageAssetSerializer(enriched, many=True).data)@extend_schema(operation_id="hog_flows_asset_content_retrieve",diff --git a/products/workflows/backend/api/message_assets.py b/products/workflows/backend/api/message_assets.pyindex 5a1b154743f4..844bc6cb9e44 100644--- a/products/workflows/backend/api/message_assets.py+++ b/products/workflows/backend/api/message_assets.py@@ -40,6 +40,7 @@ def workflow_email_assets_ui_enabled(team: "Team", user: "AbstractBaseUser | Ano_COLLAPSED_AGGREGATES = """invocation_id,action_id,+ argMax(function_id, version) AS latest_function_id,argMax(parent_run_id, version) AS latest_parent_run_id,argMax(kind, version) AS latest_kind,argMax(distinct_id, version) AS latest_distinct_id,@@ -54,6 +55,7 @@ _COLLAPSED_AGGREGATES = """_OUTER_COLUMNS = """invocation_id,action_id,+ latest_function_id,latest_parent_run_id,latest_kind,latest_distinct_id,@@ -69,6 +71,7 @@ _OUTER_COLUMNS = """class MessageAsset:invocation_id: straction_id: str+ function_id: strparent_run_id: strkind: strdistinct_id: str@@ -77,6 +80,9 @@ class MessageAsset:subject: strstatus: strsent_at: datetime+ # Human-readable workflow name; enriched by the endpoint before serialization.+ # Left blank when the workflow no longer exists so the frontend falls back to function_id.+ function_name: str = ""class MessageAssetSerializer(serializers.Serializer):@@ -84,6 +90,15 @@ class MessageAssetSerializer(serializers.Serializer):action_id = serializers.CharField(help_text="The email step (action node) within the workflow that sent this email.")+ function_id = serializers.CharField(+ help_text="The workflow id that sent this email — used to navigate from a person's "+ "Emails tab back into the originating workflow."+ )+ function_name = serializers.CharField(+ help_text="Human-readable workflow name for display. Empty when the workflow has been deleted; "+ "clients should fall back to function_id in that case.",+ allow_blank=True,+ )parent_run_id = serializers.CharField(help_text="The batch run this email belongs to, for batch-triggered workflows. Empty for event-triggered runs.")@@ -156,18 +171,45 @@ class MessageAssetContentRequestSerializer(serializers.Serializer):)+class PersonMessageAssetsRequestSerializer(serializers.Serializer):+ after = serializers.CharField(+ required=False,+ default="-30d",+ help_text="Start of the time range, matched on sent time. Relative ('-30d', '-24h') or ISO 8601. "+ "Defaults to -30d (the retention window) — bounds the ClickHouse partition scan.",+ )+ before = serializers.CharField(+ required=False,+ help_text="End of the time range, matched on sent time. Same format as 'after'. Defaults to now.",+ )+ limit = serializers.IntegerField(+ required=False,+ default=50,+ max_value=500,+ min_value=1,+ help_text="Maximum number of emails to return (1-500, default 50).",+ )+ offset = serializers.IntegerField(+ required=False,+ default=0,+ min_value=0,+ help_text="Number of emails to skip, for pagination.",+ )++def _build_asset(row: tuple) -> MessageAsset:return MessageAsset(invocation_id=row[0],action_id=row[1],- parent_run_id=row[2],- kind=row[3],- distinct_id=row[4],- person_id=row[5],- recipient=row[6],- subject=row[7],- status=row[8],- sent_at=row[9],+ function_id=row[2],+ parent_run_id=row[3],+ kind=row[4],+ distinct_id=row[5],+ person_id=row[6],+ recipient=row[7],+ subject=row[8],+ status=row[9],+ sent_at=row[10],)@@ -239,6 +281,51 @@ def fetch_message_assets(return [_build_asset(row) for row in results]+def fetch_message_assets_for_person(+ team_id: int,+ person_id: str,+ limit: int,+ offset: int = 0,+ after: Optional[datetime] = None,+ before: Optional[datetime] = None,+) -> list[MessageAsset]:+ where = [+ "team_id = %(team_id)s",+ "person_id = %(person_id)s",+ # Standalone hog_function email destinations aren't surfaced anywhere yet,+ # so this endpoint only returns workflow-step rows.+ "function_kind = 'hog_flow'",+ ]+ kwargs: dict[str, Any] = {+ "team_id": team_id,+ "person_id": person_id,+ "limit": limit,+ "offset": offset,+ }+ if after:+ where.append("sent_at >= toDateTime64(%(after)s, 6)")+ kwargs["after"] = after.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S")+ if before:+ where.append("sent_at <= toDateTime64(%(before)s, 6)")+ kwargs["before"] = before.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S")++ query = f"""+ SELECT {_OUTER_COLUMNS}+ FROM (+ SELECT {_COLLAPSED_AGGREGATES}+ FROM message_assets+ WHERE {" AND ".join(where)}+ GROUP BY invocation_id, action_id+ )+ WHERE latest_is_deleted = 0+ ORDER BY latest_sent_at DESC+ LIMIT %(limit)s OFFSET %(offset)s+ """++ results = cast(list, sync_execute(query, kwargs))+ return [_build_asset(row) for row in results]++def fetch_message_asset_html(team_id: int,function_kind: str,diff --git a/products/workflows/backend/api/test/test_message_assets.py b/products/workflows/backend/api/test/test_message_assets.pyindex 49d11c3c6b15..66314887b125 100644--- a/products/workflows/backend/api/test/test_message_assets.py+++ b/products/workflows/backend/api/test/test_message_assets.py@@ -11,6 +11,7 @@ from posthog.clickhouse.client.execute import sync_executefrom posthog.models.message_assets.sql import INSERT_MESSAGE_ASSET_SQLfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_value+from posthog.test.persons import create_personfrom products.workflows.backend.models.hog_flow.hog_flow import HogFlow@@ -232,3 +233,128 @@ class TestMessageAssets(ClickhouseTestMixin, APIBaseTest):self.feature_enabled_mock.return_value = Falseres = self.client.get(f"{self._base()}/{path}")assert res.status_code == status.HTTP_404_NOT_FOUND+++class TestPersonEmails(ClickhouseTestMixin, APIBaseTest):+ def setUp(self):+ super().setUp()+ self.person = create_person(team=self.team, distinct_ids=["distinct-1"], properties={"email": "[email protected]"})+ self.hog_flow = HogFlow.objects.create(team=self.team, name="Welcome flow")+ ff_patcher = patch(+ "products.workflows.backend.api.message_assets.posthoganalytics.feature_enabled",+ return_value=True,+ )+ self.feature_enabled_mock = ff_patcher.start()+ self.addCleanup(ff_patcher.stop)++ def _emails(self, params=None):+ return self.client.get(f"/api/projects/{self.team.id}/persons/{self.person.uuid}/emails/", params)++ def _seed(self, invocation_id: str, *, person_id: Optional[str] = None, **kwargs):+ create_message_asset(+ team_id=self.team.pk,+ function_id=str(self.hog_flow.pk),+ invocation_id=invocation_id,+ person_id=person_id or str(self.person.uuid),+ **kwargs,+ )++ def test_returns_empty_when_person_has_no_emails(self):+ res = self._emails()+ assert res.status_code == status.HTTP_200_OK+ assert res.json() == []++ def test_returns_emails_with_function_id_for_navigation(self):+ self._seed("inv-1", subject="Hello", recipient="[email protected]")+ rows = self._emails().json()+ assert len(rows) == 1+ row = rows[0]+ assert row["invocation_id"] == "inv-1"+ assert row["subject"] == "Hello"+ assert row["recipient"] == "[email protected]"+ assert row["function_id"] == str(self.hog_flow.pk)+ # Workflow name is enriched from Postgres so the tab shows "Test Flow" instead of a UUID.+ # A regression here would put raw workflow IDs in front of users.+ assert row["function_name"] == self.hog_flow.name+ assert "html" not in row++ def test_function_name_empty_when_workflow_deleted(self):+ create_message_asset(+ team_id=self.team.pk,+ function_id="00000000-0000-0000-0000-000000000abc",+ invocation_id="inv-orphan",+ person_id=str(self.person.uuid),+ )+ row = self._emails().json()[0]+ # No HogFlow row → the frontend falls back to function_id for display, so this must be blank+ # rather than a stale name or a database lookup error.+ assert row["function_name"] == ""++ def test_isolated_from_other_persons(self):+ self._seed("mine")+ self._seed("theirs", person_id="00000000-0000-0000-0000-000000000999")+ rows = self._emails().json()+ assert {r["invocation_id"] for r in rows} == {"mine"}++ def test_isolated_from_other_teams(self):+ self._seed("mine")+ create_message_asset(+ team_id=self.team.pk + 9999,+ function_id=str(self.hog_flow.pk),+ invocation_id="other-team",+ person_id=str(self.person.uuid),+ )+ rows = self._emails().json()+ assert {r["invocation_id"] for r in rows} == {"mine"}++ def test_excludes_standalone_hog_function_emails(self):+ self._seed("flow-row")+ self._seed("fn-row", function_kind="hog_function")+ rows = self._emails().json()+ assert {r["invocation_id"] for r in rows} == {"flow-row"}++ def test_collapses_to_latest_version(self):+ self._seed("inv-1", subject="first", version=1)+ self._seed("inv-1", subject="second", version=2)+ rows = self._emails().json()+ assert len(rows) == 1+ assert rows[0]["subject"] == "second"++ def test_excludes_deleted(self):+ self._seed("inv-1", version=1)+ self._seed("inv-1", version=2, is_deleted=1)+ assert self._emails().json() == []++ def test_sorted_newest_first(self):+ now = datetime.now(tz=UTC)+ self._seed("older", sent_at=now - timedelta(hours=2))+ self._seed("newer", sent_at=now - timedelta(minutes=5))+ rows = self._emails().json()+ assert [r["invocation_id"] for r in rows] == ["newer", "older"]++ def test_respects_limit_and_offset(self):+ for i in range(5):+ self._seed(f"inv-{i}")+ assert len(self._emails({"limit": 2}).json()) == 2+ assert len(self._emails({"limit": 2, "offset": 4}).json()) == 1++ def test_personal_api_key_requires_person_read_scope(self):+ self._seed("inv-1")+ key = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="no person scope",+ user=self.user,+ secure_value=hash_key_value(key),+ scopes=["hog_flow:read"],+ )+ res = self.client.get(+ f"/api/projects/{self.team.id}/persons/{self.person.uuid}/emails/",+ headers={"authorization": f"Bearer {key}"},+ )+ assert res.status_code == 403, res.json()+ assert "person:read" in res.json().get("detail", "")++ def test_404_when_ui_flag_disabled(self):+ self._seed("inv-1")+ self.feature_enabled_mock.return_value = False+ assert self._emails().status_code == status.HTTP_404_NOT_FOUNDdiff --git a/products/workflows/frontend/Workflows/EmailViewerModal.tsx b/products/workflows/frontend/Workflows/EmailViewerModal.tsxnew file mode 100644index 000000000000..4f398c41a2e8--- /dev/null+++ b/products/workflows/frontend/Workflows/EmailViewerModal.tsx@@ -0,0 +1,84 @@+import { useValues } from 'kea'+import { useState } from 'react'++import { IconLetter } from '@posthog/icons'+import { LemonModal, Link } from '@posthog/lemon-ui'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { HogFlow } from './hogflows/types'+import { getMessageAssetContentUrl } from './messageAssetsApi'++interface EmailViewerModalProps {+ workflowId: HogFlow['id']+ invocationId: string+ actionId: string+ isOpen: boolean+ onClose: () => void+ title?: string+ description?: string+}++// sandbox="" disables scripts so the captured email HTML can't run anything.+export function EmailViewerModal({+ workflowId,+ invocationId,+ actionId,+ isOpen,+ onClose,+ title = 'Email',+ description,+}: EmailViewerModalProps): JSX.Element {+ return (+ <LemonModal isOpen={isOpen} onClose={onClose} width={720} title={title} description={description}>+ <iframe+ title="Rendered email"+ sandbox=""+ src={getMessageAssetContentUrl(workflowId, invocationId, actionId)}+ className="w-full h-[60vh] bg-white rounded border"+ />+ </LemonModal>+ )+}++// Inline chip used by `renderWorkflowLogMessage` when the email service emits the+// `[Email:<invocation_id>:<action_id>]` token alongside its success log line.+export function EmailViewerChip({+ workflowId,+ invocationId,+ actionId,+}: {+ workflowId: HogFlow['id']+ invocationId: string+ actionId: string+}): JSX.Element | null {+ const { featureFlags } = useValues(featureFlagLogic)+ const [open, setOpen] = useState(false)+ if (!featureFlags[FEATURE_FLAGS.WORKFLOW_EMAIL_ASSETS_UI]) {+ return null+ }+ return (+ <>+ <Link+ className="rounded p-1 -m-1 bg-border text-bg-primary"+ onClick={(e) => {+ e.stopPropagation()+ setOpen(true)+ }}+ >+ <span className="mr-1">+ <IconLetter />+ </span>+ View email+ </Link>+ <EmailViewerModal+ workflowId={workflowId}+ invocationId={invocationId}+ actionId={actionId}+ isOpen={open}+ onClose={() => setOpen(false)}+ />+ </>+ )+}diff --git a/products/workflows/frontend/Workflows/WorkflowAssets.tsx b/products/workflows/frontend/Workflows/WorkflowAssets.tsxindex a8c17ac6eff9..aa4efea1e190 100644--- a/products/workflows/frontend/Workflows/WorkflowAssets.tsx+++ b/products/workflows/frontend/Workflows/WorkflowAssets.tsx@@ -3,11 +3,12 @@ import { router } from 'kea-router'import { useEffect } from 'react'import { HedgehogGreek } from '@posthog/brand/hoggies'-import { LemonCollapse, LemonInput, LemonModal, LemonTable, ProfilePicture, Spinner } from '@posthog/lemon-ui'+import { LemonCollapse, LemonInput, LemonTable, ProfilePicture, Spinner } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'import { batchWorkflowJobsLogic } from './batchWorkflowJobsLogic'+import { EmailViewerModal } from './EmailViewerModal'import { HogFlowBatchJob } from './hogflows/types'import { MessageAsset } from './messageAssetsApi'import { workflowAssetsLogic } from './workflowAssetsLogic'@@ -27,27 +28,19 @@ function EmptyAssets(): JSX.Element {function AssetViewerModal({ workflowId, parentRunId, actionId, invocationId }: AssetsTableProps): JSX.Element {const logic = workflowAssetsLogic({ id: workflowId, parentRunId, actionId, invocationId })- const { selectedAsset, contentUrl } = useValues(logic)+ const { selectedAsset } = useValues(logic)const { closeAsset } = useActions(logic)return (- <LemonModal+ <EmailViewerModal+ workflowId={workflowId}+ invocationId={selectedAsset?.invocation_id ?? ''}+ actionId={selectedAsset?.action_id ?? ''}isOpen={!!selectedAsset}onClose={closeAsset}- width={720}title={selectedAsset?.subject || 'Email'}description={selectedAsset ? `Sent to ${selectedAsset.recipient}` : undefined}- >- {selectedAsset ? (- // sandbox="" disables scripts so the captured email HTML can't run anything.- <iframe- title="Rendered email"- sandbox=""- src={contentUrl(selectedAsset)}- className="w-full h-[60vh] bg-white rounded border"- />- ) : null}- </LemonModal>+ />)}diff --git a/products/workflows/frontend/Workflows/logs/log-utils.tsx b/products/workflows/frontend/Workflows/logs/log-utils.tsxindex a616091b6f51..bf8d2ba7b366 100644--- a/products/workflows/frontend/Workflows/logs/log-utils.tsx+++ b/products/workflows/frontend/Workflows/logs/log-utils.tsx@@ -1,17 +1,12 @@-import { useValues } from 'kea'-import { useState } from 'react'+import { IconTrash } from '@posthog/icons'+import { Link } from '@posthog/lemon-ui'-import { IconLetter, IconTrash } from '@posthog/icons'-import { LemonModal, Link } from '@posthog/lemon-ui'--import { FEATURE_FLAGS } from 'lib/constants'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { PersonDisplay } from 'scenes/persons/PersonDisplay'import { urls } from 'scenes/urls'+import { EmailViewerChip } from '../EmailViewerModal'import { getHogFlowStep } from '../hogflows/steps/HogFlowSteps'import { HogFlow } from '../hogflows/types'-import { getMessageAssetContentUrl } from '../messageAssetsApi'// We pull out actions like [Action:action_function_webhook_13ec288f-10af-4e98-abd4-e2828de3305e] and replace them with a link to the action@@ -23,47 +18,6 @@ const EVENT_REGEX = /\[Event:([a-zA-Z0-9_-]+)\|(.*?)\|(.*?)\]/const ACTOR_REGEX = /\[Actor:(.*?)\]/const EMAIL_REGEX = /\[Email:([a-zA-Z0-9_-]+):([a-zA-Z0-9_-]*)\]/-function EmailViewerChip({- workflowId,- invocationId,- actionId,-}: {- workflowId: HogFlow['id']- invocationId: string- actionId: string-}): JSX.Element | null {- const { featureFlags } = useValues(featureFlagLogic)- const [open, setOpen] = useState(false)- if (!featureFlags[FEATURE_FLAGS.WORKFLOW_EMAIL_ASSETS_UI]) {- return null- }- return (- <>- <Link- className="rounded p-1 -m-1 bg-border text-bg-primary"- onClick={(e) => {- e.stopPropagation()- setOpen(true)- }}- >- <span className="mr-1">- <IconLetter />- </span>- View email- </Link>- <LemonModal isOpen={open} onClose={() => setOpen(false)} width={720} title="Email">- {/* sandbox="" disables scripts so the captured email HTML can't run anything. */}- <iframe- title="Rendered email"- sandbox=""- src={getMessageAssetContentUrl(workflowId, invocationId, actionId)}- className="w-full h-[60vh] bg-white rounded border"- />- </LemonModal>- </>- )-}-export const renderWorkflowLogMessage = (workflow: HogFlow, message: string): JSX.Element => {// Modifies the rendered log message to auto-detect action or person parts and replace them with a linkconst parts = message.split(RICH_LOG_REGEX)diff --git a/products/workflows/frontend/Workflows/messageAssetsApi.ts b/products/workflows/frontend/Workflows/messageAssetsApi.tsindex e5bd83fa9642..519ee26e97cd 100644--- a/products/workflows/frontend/Workflows/messageAssetsApi.ts+++ b/products/workflows/frontend/Workflows/messageAssetsApi.ts@@ -1,5 +1,10 @@import { ApiRequest } from 'lib/api'+import { TeamType } from '~/types'++import { personsEmailsList } from 'products/persons/frontend/generated/api'+import { MessageAssetApi } from 'products/persons/frontend/generated/api.schemas'+import { HogFlow } from './hogflows/types'// Scoped to this product to keep Jest's `--findRelatedTests` selection small —@@ -8,6 +13,10 @@ import { HogFlow } from './hogflows/types'export interface MessageAsset {invocation_id: stringaction_id: string+ /** Workflow id that sent this email — used by the person Emails tab to navigate back. */+ function_id: string+ /** Workflow name; empty when the workflow has been deleted (fall back to function_id). */+ function_name: string/** HogFlowBatchJob id for batch-triggered sends; empty for event-triggered runs. */parent_run_id: stringkind: string@@ -39,6 +48,25 @@ export async function getMessageAssets(return await new ApiRequest().hogFlow(hogFlowId).withAction('assets').withQueryString(params).get()}+export interface PersonMessageAssetsParams {+ after?: string+ before?: string+ limit?: number+ offset?: number+}++export async function getPersonMessageAssets(+ teamId: TeamType['id'],+ personId: string,+ params: PersonMessageAssetsParams = {}+): Promise<MessageAsset[]> {+ // The persons viewset accepts both numeric PKs and person UUIDs at runtime; drf-spectacular+ // only sees the numeric case, so the generated helper types `id: number`. Cast at the call+ // boundary rather than at every consumer.+ const rows: MessageAssetApi[] = await personsEmailsList(String(teamId), personId as unknown as number, params)+ return rows as MessageAsset[]+}+// Same-origin URL — used as an `<iframe src>` so the browser carries session auth.export function getMessageAssetContentUrl(hogFlowId: HogFlow['id'], invocationId: string, actionId: string): string {return new ApiRequest()diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.tsindex 32e6dcdfce12..13cb3b196222 100644--- a/products/workflows/frontend/generated/api.schemas.ts+++ b/products/workflows/frontend/generated/api.schemas.ts@@ -567,6 +567,10 @@ export interface MessageAssetApi {invocation_id: string/** The email step (action node) within the workflow that sent this email. */action_id: string+ /** The workflow id that sent this email — used to navigate from a person's Emails tab back into the originating workflow. */+ function_id: string+ /** Human-readable workflow name for display. Empty when the workflow has been deleted; clients should fall back to function_id in that case. */+ function_name: string/** The batch run this email belongs to, for batch-triggered workflows. Empty for event-triggered runs. */parent_run_id: string/** Asset kind. Currently always 'email'. */diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex f14e24d12556..65703e3bdd96 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -29878,6 +29878,10 @@ export namespace Schemas {invocation_id: string;/** The email step (action node) within the workflow that sent this email. */action_id: string;+ /** The workflow id that sent this email — used to navigate from a person's Emails tab back into the originating workflow. */+ function_id: string;+ /** Human-readable workflow name for display. Empty when the workflow has been deleted; clients should fall back to function_id in that case. */+ function_name: string;/** The batch run this email belongs to, for batch-triggered workflows. Empty for event-triggered runs. */parent_run_id: string;/** Asset kind. Currently always 'email'. */@@ -59438,6 +59442,39 @@ export namespace Schemas {Json: 'json',} as const;+ export type EnvironmentsPersonsEmailsListParams = {+ /**+ * Start of the time range, matched on sent time. Relative ('-30d', '-24h') or ISO 8601. Defaults to -30d (the retention window) — bounds the ClickHouse partition scan.+ * @minLength 1+ */+ after?: string;+ /**+ * End of the time range, matched on sent time. Same format as 'after'. Defaults to now.+ * @minLength 1+ */+ before?: string;+ format?: EnvironmentsPersonsEmailsListFormat;+ /**+ * Maximum number of emails to return (1-500, default 50).+ * @minimum 1+ * @maximum 500+ */+ limit?: number;+ /**+ * Number of emails to skip, for pagination.+ * @minimum 0+ */+ offset?: number;+ };++ export type EnvironmentsPersonsEmailsListFormat = typeof EnvironmentsPersonsEmailsListFormat[keyof typeof EnvironmentsPersonsEmailsListFormat];+++ export const EnvironmentsPersonsEmailsListFormat = {+ Csv: 'csv',+ Json: 'json',+ } as const;+export type EnvironmentsPersonsPropertiesTimelineRetrieveParams = {format?: EnvironmentsPersonsPropertiesTimelineRetrieveFormat;};@@ -66404,6 +66441,39 @@ export namespace Schemas {Json: 'json',} as const;+ export type PersonsEmailsListParams = {+ /**+ * Start of the time range, matched on sent time. Relative ('-30d', '-24h') or ISO 8601. Defaults to -30d (the retention window) — bounds the ClickHouse partition scan.+ * @minLength 1+ */+ after?: string;+ /**+ * End of the time range, matched on sent time. Same format as 'after'. Defaults to now.+ * @minLength 1+ */+ before?: string;+ format?: PersonsEmailsListFormat;+ /**+ * Maximum number of emails to return (1-500, default 50).+ * @minimum 1+ * @maximum 500+ */+ limit?: number;+ /**+ * Number of emails to skip, for pagination.+ * @minimum 0+ */+ offset?: number;+ };++ export type PersonsEmailsListFormat = typeof PersonsEmailsListFormat[keyof typeof PersonsEmailsListFormat];+++ export const PersonsEmailsListFormat = {+ Csv: 'csv',+ Json: 'json',+ } as const;+export type PersonsPropertiesTimelineRetrieveParams = {format?: PersonsPropertiesTimelineRetrieveFormat;};