: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(workflows): show sent push notifications on the person view (#75552)
Daniel Marchukc175cf24a8e9
diff --git a/frontend/src/scenes/persons/PersonPushNotificationsTab.tsx b/frontend/src/scenes/persons/PersonPushNotificationsTab.tsxnew file mode 100644index 000000000000..ed2a72b8dd9b--- /dev/null+++ b/frontend/src/scenes/persons/PersonPushNotificationsTab.tsx@@ -0,0 +1,89 @@+import { useValues } from 'kea'+import { useState } from 'react'++import * as greekPng from '@posthog/brand/hoggies/png/greek'+import { LemonTable, Link } from '@posthog/lemon-ui'++import { pngHoggie } from 'lib/brand/hoggies'+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 { personPushNotificationsLogic } from './personPushNotificationsLogic'++const HedgehogGreek = pngHoggie(greekPng)++interface PersonPushNotificationsTabProps {+ teamId: number+ personId: string+}++function EmptyPushNotifications(): 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 push notifications sent to this person</h2>+ <p className="text-sm text-balance text-tertiary">+ Once a workflow sends this person a push notification, it will show up here. Notifications only appear+ once a device took delivery.+ </p>+ </div>+ )+}++export function PersonPushNotificationsTab({ teamId, personId }: PersonPushNotificationsTabProps): JSX.Element {+ const logic = personPushNotificationsLogic({ teamId, personId })+ const { pushNotifications, pushNotificationsLoading } = useValues(logic)+ const [selected, setSelected] = useState<MessageAsset | null>(null)++ return (+ <>+ <LemonTable+ loading={pushNotificationsLoading}+ dataSource={pushNotifications}+ onRow={(asset: MessageAsset) => ({+ onClick: () => setSelected(asset),+ className: 'cursor-pointer',+ })}+ emptyState={<EmptyPushNotifications />}+ columns={[+ {+ title: 'Title',+ 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 || 'Push notification'}+ description={undefined}+ />+ </>+ )+}diff --git a/frontend/src/scenes/persons/PersonScene.tsx b/frontend/src/scenes/persons/PersonScene.tsxindex ea69de2e4b93..377dd021b011 100644--- a/frontend/src/scenes/persons/PersonScene.tsx+++ b/frontend/src/scenes/persons/PersonScene.tsx@@ -11,6 +11,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'@@ -18,6 +19,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 { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'import { copyToClipboard } from 'lib/utils/copyToClipboard'import { isMobile } from 'lib/utils/dom'@@ -58,6 +60,7 @@ import { PersonCohorts } from './PersonCohorts'import { PersonEmailsTab } from './PersonEmailsTab'import { PersonLogsTab } from './PersonLogsTab'import PersonProfileCanvas from './PersonProfileCanvas'+import { PersonPushNotificationsTab } from './PersonPushNotificationsTab'import { PERSON_EVENTS_CONTEXT_KEY, PersonsLogicProps, personsLogic } from './personsLogic'import { RelatedFeatureFlags } from './RelatedFeatureFlags'@@ -224,6 +227,7 @@ export function PersonScene(): JSX.Element | null {const { deletedPersonLoading } = useValues(personDeleteModalLogic)const { groupsEnabled } = useValues(groupsAccessLogic)const { currentTeam } = useValues(teamLogic)+ const { featureFlags } = useValues(featureFlagLogic)const { addProductIntentForCrossSell } = useActions(teamLogic)const { user } = useValues(userLogic)const eventsQueryLogicKey = `${PERSON_EVENTS_CONTEXT_KEY}-${mountedPersonsLogic.key}`@@ -422,6 +426,18 @@ export function PersonScene(): JSX.Element | null {content: <PersonEmailsTab teamId={currentTeam?.id ?? 0} personId={String(person.uuid)} />,}: false,+ person.uuid && featureFlags[FEATURE_FLAGS.WORKFLOWS_PUSH_NOTIFICATIONS]+ ? {+ key: PersonsTabType.PUSH_NOTIFICATIONS,+ label: <span data-attr="persons-push-notifications-tab">Push notifications</span>,+ content: (+ <PersonPushNotificationsTab+ 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/personPushNotificationsLogic.ts b/frontend/src/scenes/persons/personPushNotificationsLogic.tsnew file mode 100644index 000000000000..2c2910e357a2--- /dev/null+++ b/frontend/src/scenes/persons/personPushNotificationsLogic.ts@@ -0,0 +1,65 @@+import { MakeLogicType, kea, key, path, props } from 'kea'+import { lazyLoaders } from 'kea-loaders'++import { getPersonPushNotifications, MessageAsset } from 'products/workflows/frontend/Workflows/messageAssetsApi'++export interface PersonPushNotificationsLogicProps {+ teamId: number+ personId: string+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface personPushNotificationsLogicValues {+ pushNotifications: MessageAsset[]+ pushNotificationsLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface personPushNotificationsLogicActions {+ loadPushNotifications: () => any+ loadPushNotificationsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadPushNotificationsSuccess: (+ pushNotifications: MessageAsset[],+ payload?: any+ ) => {+ pushNotifications: MessageAsset[]+ payload?: any+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface personPushNotificationsLogicMeta {+ key: string+}++export type personPushNotificationsLogicType = MakeLogicType<+ personPushNotificationsLogicValues,+ personPushNotificationsLogicActions,+ PersonPushNotificationsLogicProps,+ personPushNotificationsLogicMeta+>++export const personPushNotificationsLogic = kea<personPushNotificationsLogicType>([+ path(['scenes', 'persons', 'personPushNotificationsLogic']),+ props({} as PersonPushNotificationsLogicProps),+ key((props) => `${props.teamId}-${props.personId}`),+ lazyLoaders(({ props }) => ({+ pushNotifications: [+ [] as MessageAsset[],+ {+ loadPushNotifications: async () => {+ if (!props.personId) {+ return []+ }+ return await getPersonPushNotifications(props.teamId, props.personId)+ },+ },+ ],+ })),+])diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex ab7061f7464b..eba4a9fb80b3 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -1872,6 +1872,7 @@ export enum PersonsTabType {HISTORY = 'history',FEATURE_FLAGS = 'featureFlags',EMAILS = 'emails',+ PUSH_NOTIFICATIONS = 'pushNotifications',}export enum GroupsTabType {diff --git a/posthog/api/person.py b/posthog/api/person.pyindex 95b5350dd6ed..dcdf4a3638f3 100644--- a/posthog/api/person.py+++ b/posthog/api/person.py@@ -1240,6 +1240,17 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):)@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:+ return self._message_assets_response(request, kind="email")++ @extend_schema(+ parameters=[PersonMessageAssetsRequestSerializer],+ responses=MessageAssetSerializer(many=True),+ )+ @action(methods=["GET"], detail=True, required_scopes=["person:read"], pagination_class=None, filter_backends=[])+ def push_notifications(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:+ return self._message_assets_response(request, kind="push")++ def _message_assets_response(self, request: request.Request, kind: str) -> response.Response:person = self.get_object()param_serializer = PersonMessageAssetsRequestSerializer(data=request.query_params)param_serializer.is_valid(raise_exception=True)@@ -1259,6 +1270,7 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):offset=params["offset"],after=after_date,before=before_date,+ kind=kind,)# 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 mapdiff --git a/products/persons/frontend/generated/api.schemas.ts b/products/persons/frontend/generated/api.schemas.tsindex 753cfa02db86..8289d85bedbe 100644--- a/products/persons/frontend/generated/api.schemas.ts+++ b/products/persons/frontend/generated/api.schemas.ts@@ -257,7 +257,7 @@ export interface MessageAssetApi {function_name: string/** The batch run this email belongs to, for batch-triggered workflows. Empty for event-triggered runs. */parent_run_id: string- /** Message channel this asset was sent on: 'email' or 'push'. The per-person endpoint currently returns only 'email'. */+ /** Message channel this asset was sent on: 'email' or 'push'. The per-person endpoints return one channel each. */kind: string/** The recipient's distinct_id. */distinct_id: string@@ -510,13 +510,13 @@ export type PersonsEmailsListParams = {before?: stringformat?: PersonsEmailsListFormat/**- * Maximum number of emails to return (1-500, default 50).+ * Maximum number of assets to return (1-500, default 50).* @minimum 1* @maximum 500*/limit?: number/**- * Number of emails to skip, for pagination.+ * Number of assets to skip, for pagination.* @minimum 0*/offset?: number@@ -541,6 +541,39 @@ export const PersonsPropertiesTimelineRetrieveFormat = {Json: 'json',} as const+export type PersonsPushNotificationsListParams = {+ /**+ * 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?: PersonsPushNotificationsListFormat+ /**+ * Maximum number of assets to return (1-500, default 50).+ * @minimum 1+ * @maximum 500+ */+ limit?: number+ /**+ * Number of assets to skip, for pagination.+ * @minimum 0+ */+ offset?: number+}++export type PersonsPushNotificationsListFormat =+ (typeof PersonsPushNotificationsListFormat)[keyof typeof PersonsPushNotificationsListFormat]++export const PersonsPushNotificationsListFormat = {+ Csv: 'csv',+ Json: 'json',+} as const+export type PersonsSplitCreateParams = {format?: PersonsSplitCreateFormat}diff --git a/products/persons/frontend/generated/api.ts b/products/persons/frontend/generated/api.tsindex b3c9a5679660..aa1f05132d02 100644--- a/products/persons/frontend/generated/api.ts+++ b/products/persons/frontend/generated/api.ts@@ -34,6 +34,7 @@ import type {PersonsPartialUpdateParams,PersonsPropertiesAtTimeRetrieveParams,PersonsPropertiesTimelineRetrieveParams,+ PersonsPushNotificationsListParams,PersonsResetPersonDistinctIdCreateParams,PersonsRetrieveParams,PersonsSplitCreateParams,@@ -329,6 +330,41 @@ export const personsPropertiesTimelineRetrieve = async (})}+export const getPersonsPushNotificationsListUrl = (+ projectId: string,+ id: number,+ params?: PersonsPushNotificationsListParams+) => {+ 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}/push_notifications/?${stringifiedParams}`+ : `/api/projects/${projectId}/persons/${id}/push_notifications/`+}++/**+ * 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 personsPushNotificationsList = async (+ projectId: string,+ id: number,+ params?: PersonsPushNotificationsListParams,+ options?: RequestInit+): Promise<MessageAssetApi[]> => {+ return apiMutator<MessageAssetApi[]>(getPersonsPushNotificationsListUrl(projectId, id, params), {+ ...options,+ method: 'GET',+ })+}+export const getPersonsSplitCreateUrl = (projectId: string, id: string, params?: PersonsSplitCreateParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/persons/mcp/tools.yaml b/products/persons/mcp/tools.yamlindex e53d1286122f..7dcb4228c4ef 100644--- a/products/persons/mcp/tools.yaml+++ b/products/persons/mcp/tools.yaml@@ -133,6 +133,9 @@ tools:Returns 202 Accepted.exclude_params:- format+ persons-push-notifications-list:+ operation: persons_push_notifications_list+ enabled: falsepersons-reset-person-distinct-id-create:operation: persons_reset_person_distinct_id_createenabled: falsediff --git a/products/workflows/backend/api/message_assets.py b/products/workflows/backend/api/message_assets.pyindex dffe72dd722c..fbb154bab29a 100644--- a/products/workflows/backend/api/message_assets.py+++ b/products/workflows/backend/api/message_assets.py@@ -75,8 +75,8 @@ class MessageAssetSerializer(serializers.Serializer):help_text="The batch run this email belongs to, for batch-triggered workflows. Empty for event-triggered runs.")kind = serializers.CharField(- help_text="Message channel this asset was sent on: 'email' or 'push'. The per-person endpoint "- "currently returns only 'email'."+ help_text="Message channel this asset was sent on: 'email' or 'push'. The per-person endpoints "+ "return one channel each.")distinct_id = serializers.CharField(help_text="The recipient's distinct_id.")person_id = serializers.CharField(help_text="The recipient's person UUID, if resolved.")@@ -166,13 +166,13 @@ class PersonMessageAssetsRequestSerializer(serializers.Serializer):default=50,max_value=500,min_value=1,- help_text="Maximum number of emails to return (1-500, default 50).",+ help_text="Maximum number of assets 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.",+ help_text="Number of assets to skip, for pagination.",)@@ -267,6 +267,7 @@ def fetch_message_assets_for_person(offset: int = 0,after: Optional[datetime] = None,before: Optional[datetime] = None,+ kind: str = "email",) -> list[MessageAsset]:where = ["team_id = %(team_id)s",@@ -274,14 +275,15 @@ def fetch_message_assets_for_person(# Standalone hog_function email destinations aren't surfaced anywhere yet,# so this endpoint only returns workflow-step rows."function_kind = 'hog_flow'",- # Push assets are captured but not yet surfaced: this backs the person Emails tab, and a push- # rendered as an email row would misrepresent it. Drop this filter when that tab becomes a- # combined Messages view.- "kind = 'email'",+ # One channel per call. The person view shows email and push in separate tabs, each with+ # columns shaped for its channel, so returning both from one call would misrepresent whichever+ # tab it landed in.+ "kind = %(kind)s",]kwargs: dict[str, Any] = {"team_id": team_id,"person_id": person_id,+ "kind": kind,"limit": limit,"offset": offset,}diff --git a/products/workflows/frontend/Workflows/messageAssetsApi.ts b/products/workflows/frontend/Workflows/messageAssetsApi.tsindex 519ee26e97cd..ad0945653a0f 100644--- a/products/workflows/frontend/Workflows/messageAssetsApi.ts+++ b/products/workflows/frontend/Workflows/messageAssetsApi.ts@@ -2,7 +2,7 @@ import { ApiRequest } from 'lib/api'import { TeamType } from '~/types'-import { personsEmailsList } from 'products/persons/frontend/generated/api'+import { personsEmailsList, personsPushNotificationsList } from 'products/persons/frontend/generated/api'import { MessageAssetApi } from 'products/persons/frontend/generated/api.schemas'import { HogFlow } from './hogflows/types'@@ -67,6 +67,20 @@ export async function getPersonMessageAssets(return rows as MessageAsset[]}+export async function getPersonPushNotifications(+ teamId: TeamType['id'],+ personId: string,+ params: PersonMessageAssetsParams = {}+): Promise<MessageAsset[]> {+ // Same UUID-vs-numeric-PK cast as getPersonMessageAssets above.+ const rows: MessageAssetApi[] = await personsPushNotificationsList(+ 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 fd39995c6974..b53780da7c1c 100644--- a/products/workflows/frontend/generated/api.schemas.ts+++ b/products/workflows/frontend/generated/api.schemas.ts@@ -674,7 +674,7 @@ export interface MessageAssetApi {function_name: string/** The batch run this email belongs to, for batch-triggered workflows. Empty for event-triggered runs. */parent_run_id: string- /** Message channel this asset was sent on: 'email' or 'push'. The per-person endpoint currently returns only 'email'. */+ /** Message channel this asset was sent on: 'email' or 'push'. The per-person endpoints return one channel each. */kind: string/** The recipient's distinct_id. */distinct_id: stringdiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 418d258e69ae..26a9c2615642 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -40567,7 +40567,7 @@ export namespace Schemas {function_name: string;/** The batch run this email belongs to, for batch-triggered workflows. Empty for event-triggered runs. */parent_run_id: string;- /** Message channel this asset was sent on: 'email' or 'push'. The per-person endpoint currently returns only 'email'. */+ /** Message channel this asset was sent on: 'email' or 'push'. The per-person endpoints return one channel each. */kind: string;/** The recipient's distinct_id. */distinct_id: string;@@ -80685,13 +80685,13 @@ export namespace Schemas {before?: string;format?: PersonsEmailsListFormat;/**- * Maximum number of emails to return (1-500, default 50).+ * Maximum number of assets to return (1-500, default 50).* @minimum 1* @maximum 500*/limit?: number;/**- * Number of emails to skip, for pagination.+ * Number of assets to skip, for pagination.* @minimum 0*/offset?: number;@@ -80717,6 +80717,39 @@ export namespace Schemas {Json: 'json',} as const;+ export type PersonsPushNotificationsListParams = {+ /**+ * 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?: PersonsPushNotificationsListFormat;+ /**+ * Maximum number of assets to return (1-500, default 50).+ * @minimum 1+ * @maximum 500+ */+ limit?: number;+ /**+ * Number of assets to skip, for pagination.+ * @minimum 0+ */+ offset?: number;+ };++ export type PersonsPushNotificationsListFormat = typeof PersonsPushNotificationsListFormat[keyof typeof PersonsPushNotificationsListFormat];+++ export const PersonsPushNotificationsListFormat = {+ Csv: 'csv',+ Json: 'json',+ } as const;+export type PersonsSplitCreateParams = {format?: PersonsSplitCreateFormat;};