: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
import { useActions, useMountedLogic, useValues } from 'kea'
import { memo } from 'react'
import { IconChevronDown, IconCopy, IconInfo, IconRefresh, IconTrash } from '@posthog/icons'
import { LemonButton, LemonButtonProps, LemonDivider, LemonMenu, LemonSelect, LemonTag, Link } from '@posthog/lemon-ui'
import { Button } from '@posthog/quill'
import api from 'lib/api'
import { ActivityLog } from 'lib/components/ActivityLog/ActivityLog'
import { appEditorUrl } from 'lib/components/AuthorizedUrlList/authorizedUrlListLogic'
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 { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { groupsAccessLogic } from 'lib/introductions/groupsAccessLogic'
import { IconOpenInApp } from 'lib/lemon-ui/icons'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
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'
import { pluralize } from 'lib/utils/strings'
import { tryDecodeURIComponent } from 'lib/utils/url'
import { NotebookSelectButton } from 'scenes/notebooks/NotebookSelectButton/NotebookSelectButton'
import { NotebookNodeType } from 'scenes/notebooks/types'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene, SceneExport } from 'scenes/sceneTypes'
import { SessionRecordingsPlaylist } from 'scenes/session-recordings/playlist/SessionRecordingsPlaylist'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneDivider } from '~/layout/scenes/components/SceneDivider'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { Query } from '~/queries/Query/Query'
import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'
import {
AccessControlLevel,
AccessControlResourceType,
ActivityScope,
PersonType,
PersonsTabType,
PropertyDefinitionType,
} from '~/types'
import { ComposeTicketButton } from 'products/conversations/frontend/components/ComposeTicket/ComposeTicketButton'
import { FeedbackButton } from 'products/customer_analytics/frontend/components/FeedbackButton'
import { RelatedGroups } from 'products/groups/frontend/components/RelatedGroups'
import { MergeSplitPerson } from '../components/MergeSplitPerson'
import { PersonCohorts } from '../components/PersonCohorts'
import { PersonDeleteModal } from '../components/PersonDeleteModal'
import { PersonEmailsTab } from '../components/PersonEmailsTab'
import { PersonLogsTab } from '../components/PersonLogsTab'
import PersonProfileCanvas from '../components/PersonProfileCanvas'
import { PersonPushNotificationsTab } from '../components/PersonPushNotificationsTab'
import { RelatedFeatureFlags } from '../components/RelatedFeatureFlags'
import { personDeleteModalLogic } from '../logics/personDeleteModalLogic'
import { PERSON_EVENTS_CONTEXT_KEY, PersonsLogicProps, personsLogic } from '../logics/personsLogic'
import { asDisplay, pickBestPersonDistinctId } from '../person-utils'
export const scene: SceneExport<PersonsLogicProps> = {
component: PersonScene,
logic: personsLogic,
paramsToProps: ({ params: { _: rawUrlId } }) => ({
syncWithUrl: true,
// A distinct ID with a stray `%` (e.g. `50%off`) makes decodeURIComponent throw
// `URIError: URI malformed`. Fall back to the raw id so the scene still renders.
urlId: tryDecodeURIComponent(rawUrlId),
}),
}
function PersonCaption({ person }: { person: PersonType }): JSX.Element {
// Show the most human-readable distinct ID first; the rest fall into the "+N" menu.
const primaryDistinctId = pickBestPersonDistinctId(person.distinct_ids) ?? person.distinct_ids[0]
const otherDistinctIds = person.distinct_ids.filter((distinct_id) => distinct_id !== primaryDistinctId)
return (
<div className="flex flex-wrap items-center gap-2">
<div className="flex deprecated-space-x-1">
<div>
<span className="text-secondary">IDs:</span>{' '}
<span data-attr="person-distinct-id">
<CopyToClipboardInline
tooltipMessage={null}
description="person distinct ID"
style={{ justifyContent: 'flex-end' }}
>
{primaryDistinctId}
</CopyToClipboardInline>
</span>
</div>
{otherDistinctIds.length > 0 && (
<LemonMenu
items={otherDistinctIds.map((distinct_id: string) => ({
label: distinct_id,
sideIcon: <IconCopy className="text-primary-3000" />,
onClick: () => copyToClipboard(distinct_id, 'distinct id'),
}))}
>
<LemonTag type="primary" className="inline-flex">
<span>+{otherDistinctIds.length}</span>
<IconChevronDown className="w-4 h-4" />
</LemonTag>
</LemonMenu>
)}
</div>
<div>
<span className="text-secondary">First seen:</span>{' '}
{person.created_at ? (
<span className="relative -top-px">
<TZLabel time={person.created_at} />
</span>
) : (
'unknown'
)}
</div>
<div className="flex items-center gap-1">
<span className="text-secondary">Merge restrictions:</span> {person.is_identified ? 'applied' : 'none'}
<Link
to="https://posthog.com/docs/data/identify#alias-assigning-multiple-distinct-ids-to-the-same-user"
target="_blank"
>
<Tooltip
title={
<>
{person.is_identified ? <strong>Cannot</strong> : 'Can'} be used as `alias_id` - click
for more info.
</>
}
>
<IconInfo className="ml-1 text-base shrink-0" />
</Tooltip>
</Link>
</div>
</div>
)
}
interface LaunchToolbarButtonProps {
distinctId: string
}
function LaunchToolbarButton({ distinctId }: LaunchToolbarButtonProps): JSX.Element {
const { currentTeam } = useValues(teamLogic)
const toolbarAccessDisabledReason = getAccessControlDisabledReason(
AccessControlResourceType.Toolbar,
AccessControlLevel.Viewer
)
const handleLaunchToolbar = async (targetUrl: string): Promise<void> => {
if (!currentTeam?.app_urls?.length) {
lemonToast.error('No authorized URLs configured. Please add a URL in Toolbar settings.')
return
}
try {
// Prepare toolbar flags on backend and get cache key
// This posts to the user API, which has no generated function.
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
const response = await api.create('api/user/prepare_toolbar_preloaded_flags', {
distinct_id: distinctId,
})
const toolbarUrl = appEditorUrl(targetUrl, {
toolbarFlagsKey: response.key,
})
window.open(toolbarUrl, '_blank')
lemonToast.success(`Launching toolbar with ${pluralize(response.flag_count, 'feature flag override')}`)
} catch (error) {
lemonToast.error('Failed to launch toolbar. Please try again.')
console.error('Error launching toolbar:', error)
}
}
return (
<LemonSelect
size="medium"
icon={<IconOpenInApp />}
data-attr="launch-toolbar-with-loaded-flags-button"
tooltip="Launch authorized URL with this user's feature flag values as overrides"
options={(currentTeam?.app_urls || []).map((url) => ({
label: `Launch ${url}`,
value: url,
}))}
placeholder="Launch toolbar with this user's feature flags"
onChange={(value) => value && handleLaunchToolbar(value)}
disabledReason={toolbarAccessDisabledReason}
/>
)
}
export function PersonScene(): JSX.Element | null {
const mountedPersonsLogic = useMountedLogic(personsLogic)
const {
feedEnabled,
person,
personLoading,
personError,
currentTab,
splitMergeModalShown,
urlId,
distinctId,
primaryDistinctId,
eventsQuery,
eventsQueryIsDirty,
exceptionsQuery,
surveyResponsesQuery,
} = useValues(mountedPersonsLogic)
const {
loadPersons,
editProperty,
deleteProperty,
navigateToTab,
setSplitMergeModalShown,
setDistinctId,
setEventsQuery,
resetEventsQuery,
setExceptionsQuery,
setSurveyResponsesQuery,
} = useActions(mountedPersonsLogic)
const { showPersonDeleteModal } = useActions(personDeleteModalLogic)
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 todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')
const eventsQueryLogicKey = `${PERSON_EVENTS_CONTEXT_KEY}-${mountedPersonsLogic.key}`
if (personError) {
return (
<div className="flex flex-col items-center justify-center w-full p-8">
<LemonBanner
type="error"
className="max-w-200 w-full"
action={{
children: 'Reload',
onClick: () => window.location.reload(),
'data-attr': 'person-load-error-reload',
}}
>
<p>We couldn't load this person.</p>
<p className="text-muted mb-0">{personError}</p>
</LemonBanner>
</div>
)
}
if (!person) {
return personLoading ? <SpinnerOverlay sceneLevel /> : <NotFound object="person" meta={{ urlId }} />
}
return (
<SceneContent>
<SceneTitleSection
name={asDisplay(person, undefined, true)}
resourceType={{
type: sceneConfigurations[Scene.Person].iconType || 'default_icon_type',
}}
forceBackTo={{
name: sceneConfigurations[Scene.Persons].name,
path: urls.persons(),
key: 'people',
}}
actions={
<>
<FeedbackButton id="customer-analytics-person-profile-feedback-button" />
<ComposeTicketButton
size="small"
type="secondary"
distinctId={primaryDistinctId ?? person.distinct_ids[0]}
email={typeof person.properties?.email === 'string' ? person.properties.email : undefined}
/>
{user?.is_staff && <OpenInAdminPanelButton />}
<NotebookSelectButton
resource={{
type: NotebookNodeType.Person,
attrs: { id: person?.uuid },
}}
type="secondary"
size="small"
/>
{todayRailNav ? (
<>
<Button
onClick={() => showPersonDeleteModal(person, () => loadPersons())}
disabled={deletedPersonLoading}
loading={deletedPersonLoading}
variant="destructive-outline"
data-attr="delete-person"
size={isMobile() ? 'icon' : undefined}
aria-label={isMobile() ? 'Delete person' : undefined}
tooltip={isMobile() ? 'Delete person' : undefined}
>
{isMobile() ? <IconTrash /> : 'Delete person'}
</Button>
{person.distinct_ids.length > 1 && (
<Button
onClick={() => setSplitMergeModalShown(true)}
data-attr="merge-person-button"
variant="outline"
>
Split IDs
</Button>
)}
</>
) : (
<>
<LemonButton
onClick={() => showPersonDeleteModal(person, () => loadPersons())}
disabled={deletedPersonLoading}
loading={deletedPersonLoading}
type="secondary"
status="danger"
data-attr="delete-person"
size="small"
icon={isMobile() ? <IconTrash /> : null}
>
{isMobile() ? null : 'Delete person'}
</LemonButton>
{person.distinct_ids.length > 1 && (
<LemonButton
onClick={() => setSplitMergeModalShown(true)}
data-attr="merge-person-button"
type="secondary"
size="small"
>
Split IDs
</LemonButton>
)}
</>
)}
</>
}
/>
<PersonCaption person={person} />
<SceneDivider />
<PersonDeleteModal />
<LemonTabs
activeKey={currentTab}
onChange={(tab) => {
navigateToTab(tab as PersonsTabType)
}}
data-attr="persons-tabs"
tabs={[
feedEnabled
? {
key: PersonsTabType.PROFILE,
label: <span data-attr="persons-profile-tab">Profile</span>,
content: <PersonProfileCanvas person={person} attachTo={mountedPersonsLogic} />,
}
: false,
{
key: PersonsTabType.PROPERTIES,
label: <span data-attr="persons-properties-tab">Properties</span>,
content: (
<PropertiesTable
type={PropertyDefinitionType.Person}
properties={person.properties || {}}
searchable
onEdit={editProperty}
sortProperties
embedded={false}
onDelete={(key) => deleteProperty(key)}
filterable
collapsible
/>
),
},
{
key: PersonsTabType.EVENTS,
label: <span data-attr="persons-events-tab">Events</span>,
content: (
<Query
uniqueKey="person-profile-events"
attachTo={mountedPersonsLogic}
query={eventsQuery}
setQuery={(q) => setEventsQuery(q)}
context={{
insightProps: {
dashboardItemId: `new-${eventsQueryLogicKey}`,
dataNodeCollectionId: eventsQueryLogicKey,
},
emptyStateDetail: eventsQueryIsDirty
? 'Try changing the date range, or pick another action, event or breakdown.'
: 'This only shows events from the last 24 hours by default. Try widening the date range, or pick another action, event or breakdown.',
customActions: (
<LemonButton
key="reset-events-filters"
type="secondary"
size="small"
icon={<IconRefresh />}
onClick={() => resetEventsQuery()}
disabledReason={eventsQueryIsDirty ? undefined : 'No active filters'}
data-attr="person-events-reset-filters"
>
Reset all filters
</LemonButton>
),
}}
/>
),
},
{
key: PersonsTabType.SESSION_RECORDINGS,
label: <span data-attr="person-session-recordings-tab">Recordings</span>,
content: (
<>
{!currentTeam?.session_recording_opt_in ? (
<div className="mb-4">
<LemonBanner type="info">
Session recordings are currently disabled for this project. To use this
feature, please go to your{' '}
<Link
to={`${urls.settings('project')}#recordings`}
onClick={() => {
addProductIntentForCrossSell({
from: ProductKey.PERSONS,
to: ProductKey.SESSION_REPLAY,
intent_context: ProductIntentContext.PERSON_VIEW_RECORDINGS,
})
}}
>
project settings
</Link>{' '}
and enable it.
</LemonBanner>
</div>
) : null}
<div className="SessionRecordingPlaylistHeightWrapper">
<SessionRecordingsPlaylist
logicKey={`person-scene-${person.uuid}`}
personUUID={person.uuid}
distinctIds={person.distinct_ids}
updateSearchParams
/>
</div>
</>
),
},
{
key: PersonsTabType.LOGS,
label: <span data-attr="persons-logs-tab">Logs</span>,
content: <PersonLogsTab person={person} />,
},
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,
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>,
content: (
<Query
uniqueKey="person-profile-exceptions"
attachTo={mountedPersonsLogic}
query={exceptionsQuery}
setQuery={(q) => setExceptionsQuery(q)}
/>
),
},
{
key: PersonsTabType.SURVEY_RESPONSES,
label: <span data-attr="persons-survey-responses-tab">Surveys</span>,
content: (
<Query
uniqueKey="person-profile-surveys"
attachTo={mountedPersonsLogic}
query={surveyResponsesQuery}
setQuery={(q) => setSurveyResponsesQuery(q)}
/>
),
},
{
key: PersonsTabType.COHORTS,
label: <span data-attr="persons-cohorts-tab">Cohorts</span>,
content: <PersonCohorts />,
},
groupsEnabled && person.uuid
? {
key: PersonsTabType.RELATED,
label: (
<span className="flex items-center" data-attr="persons-related-tab">
Related groups
<Tooltip title="People and groups that have shared events with this person in the last 90 days.">
<IconInfo className="ml-1 text-base shrink-0" />
</Tooltip>
</span>
),
content: <RelatedGroups id={person.uuid} groupTypeIndex={null} />,
}
: false,
person.uuid
? {
key: PersonsTabType.FEATURE_FLAGS,
tooltip: `Only shows feature flags with targeting conditions based on person properties.`,
label: <span data-attr="persons-related-flags-tab">Feature flags</span>,
content: (
<PersonFeatureFlagsTab
person={person}
distinctId={distinctId}
primaryDistinctId={primaryDistinctId}
setDistinctId={setDistinctId}
/>
),
}
: false,
{
key: PersonsTabType.HISTORY,
label: 'History',
content: (
<ActivityLog
scope={ActivityScope.PERSON}
id={person.id}
caption={
<LemonBanner type="info">
This page only shows changes made by users in the PostHog site. Automatic
changes from the API aren't shown here.
</LemonBanner>
}
/>
),
},
]}
/>
{splitMergeModalShown && person && <MergeSplitPerson person={person} />}
</SceneContent>
)
}
// memoized with stable props so edits elsewhere in the scene don't re-render the mounted tab
const PersonFeatureFlagsTab = memo(function PersonFeatureFlagsTab({
person,
distinctId,
primaryDistinctId,
setDistinctId,
}: {
person: PersonType
distinctId: string | null
primaryDistinctId: string | null
setDistinctId: (distinctId: string) => void
}): JSX.Element {
const selectedDistinctId = distinctId || primaryDistinctId
return (
<>
<div className="flex deprecated-space-x-2 items-center mb-2">
<div className="flex items-center">
Choose ID:
<Tooltip
docLink="https://posthog.com/docs/feature-flags/creating-feature-flags#persisting-feature-flags-across-authentication-steps"
title={
<div className="deprecated-space-y-2">
<div>Feature flags values can depend on a person's distinct ID.</div>
<div>
If you want your flag values to stay consistent for each user, you can enable flag
persistence in the feature flag settings.
</div>
<div>This option may depend on your specific setup and isn't always suitable.</div>
</div>
}
>
<IconInfo className="ml-1 text-base" />
</Tooltip>
</div>
<LemonSelect
value={selectedDistinctId}
onChange={(value) => value && setDistinctId(value)}
options={person.distinct_ids.map((distinct_id) => ({
label: distinct_id,
value: distinct_id,
}))}
data-attr="person-feature-flags-select"
/>
{selectedDistinctId && <LaunchToolbarButton distinctId={selectedDistinctId} />}
</div>
<LemonDivider className="mb-4" />
<RelatedFeatureFlags distinctId={selectedDistinctId} />
</>
)
})
function OpenInAdminPanelButton({ size = 'small' }: { size?: LemonButtonProps['size'] }): JSX.Element {
const { person } = useValues(personsLogic)
const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')
const disabledReason = !person?.properties.email ? 'Person has no email' : undefined
const openInAdminPanel = async (email: string): Promise<void> => {
try {
const response = await api.users.list(email)
if (!response.results || response.results.length === 0) {
throw new Error('User not found')
}
const userId = response.results[0].id
window.open(`/admin/posthog/user/${userId}/change/`, '_blank')
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
lemonToast.error(`Failed to open admin panel: ${message}`)
}
}
if (todayRailNav) {
return (
<Button
variant="outline"
onClick={() => openInAdminPanel(person?.properties.email)}
disabledReason={disabledReason}
>
Open in admin panel
</Button>
)
}
return (
<LemonButton
type="secondary"
onClick={() => openInAdminPanel(person?.properties.email)}
disabledReason={disabledReason}
size={size}
>
Open in admin panel
</LemonButton>
)
}