: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 email log activity on one collapsible rail (#130597)
Daniel Marchukc7d03c2d93b2
diff --git a/products/workflows/frontend/Transactional/log/TransactionalEmailActivity.tsx b/products/workflows/frontend/Transactional/log/TransactionalEmailActivity.tsxindex 589bf67c05eb..fe0cc9a3ba0b 100644--- a/products/workflows/frontend/Transactional/log/TransactionalEmailActivity.tsx+++ b/products/workflows/frontend/Transactional/log/TransactionalEmailActivity.tsx@@ -8,6 +8,16 @@ import { emailSentAt } from './emailActivity'import { TransactionalEmailActivityTimeline } from './TransactionalEmailActivityTimeline'import { transactionalEmailLogEntryLogic } from './transactionalEmailLogEntryLogic'+function ActivitySkeleton(): JSX.Element {+ return (+ <div className="flex flex-col gap-3">+ {Array.from({ length: 6 }).map((_, index) => (+ <LemonSkeleton key={index} className="h-5" />+ ))}+ </div>+ )+}+export function TransactionalEmailActivity({ email }: { email: TransactionalEmailLogDetailApi }): JSX.Element {const { person, personLoading, personFailed, activity, activityLoading, activityFailed } = useValues(transactionalEmailLogEntryLogic@@ -39,6 +49,8 @@ export function TransactionalEmailActivity({ email }: { email: TransactionalEmaiThe person behind this send couldn't load. Check your connection and try again.</LemonBanner>)+ } else if (person === undefined || personLoading) {+ content = <ActivitySkeleton />} else if (person === null) {content = (<p className="text-sm text-secondary m-0">@@ -46,27 +58,22 @@ export function TransactionalEmailActivity({ email }: { email: TransactionalEmaithe email shows up here.</p>)- } else if (activityFailed && !activityLoading && person) {+ } else if (activityFailed && !activityLoading) {+ const distinctId = email.distinct_idcontent = (<LemonBannertype="error"action={{children: 'Try again',- onClick: () => loadActivity({ personId: person.id, sentAt: emailSentAt(email) }),+ onClick: () => loadActivity({ distinctId, sentAt: emailSentAt(email) }),'data-attr': 'transactional-email-activity-retry',}}>The activity couldn't load. Check your connection and try again.</LemonBanner>)- } else if (!activity || activityLoading || personLoading) {- content = (- <div className="flex flex-col gap-3">- {Array.from({ length: 6 }).map((_, index) => (- <LemonSkeleton key={index} className="h-5" />- ))}- </div>- )+ } else if (!activity || activityLoading) {+ content = <ActivitySkeleton />} else {content = <TransactionalEmailActivityTimeline email={email} activity={activity} />}@@ -76,7 +83,7 @@ export function TransactionalEmailActivity({ email }: { email: TransactionalEmai<div className="flex flex-col gap-0.5"><h3 className="text-base font-semibold m-0">{title}</h3><p className="text-xs text-secondary m-0">- The person's events in your product, with this email's delivery and engagement in between.+ The person's events in your product before and after this email.</p></div>{content}diff --git a/products/workflows/frontend/Transactional/log/TransactionalEmailActivityRail.stories.tsx b/products/workflows/frontend/Transactional/log/TransactionalEmailActivityRail.stories.tsxnew file mode 100644index 000000000000..fee3682accf9--- /dev/null+++ b/products/workflows/frontend/Transactional/log/TransactionalEmailActivityRail.stories.tsx@@ -0,0 +1,56 @@+import { Meta, StoryFn } from '@storybook/react'++import type { ActivityEvent } from './emailActivity'+import { buildActivityTimeline } from './emailActivity'+import { groupActivityRows } from './emailActivityGroups'+import { TransactionalEmailActivityRail } from './TransactionalEmailActivityRail'++const meta: Meta<typeof TransactionalEmailActivityRail> = {+ title: 'Scenes-App/Transactional/Email activity rail',+ component: TransactionalEmailActivityRail,+ parameters: { mockDate: '2026-06-15', testOptions: { snapshotBrowsers: [] } },+}+export default meta++const SENT_AT = '2026-06-15T09:00:00Z'++function event(uuid: string, timestamp: string, sessionId: string | null, name = '$pageview'): ActivityEvent {+ return {+ uuid,+ event: name,+ timestamp,+ url: null,+ pathname: '/pricing',+ sessionId,+ eventType: null,+ elementsChain: '',+ }+}++const timeline = buildActivityTimeline(+ [+ event('before', '2026-06-14T08:59:00Z', 'session-1'),+ event('after', '2026-06-15T09:03:00Z', 'session-2'),+ event('outcome', '2026-06-15T09:04:00Z', 'session-2', 'upgraded_plan'),+ event('no-session', '2026-06-15T14:00:00Z', null, 'invoice_paid'),+ ],+ [],+ SENT_AT+)++export const SessionsAroundTheSend: StoryFn = () => (+ <TransactionalEmailActivityRail+ before={groupActivityRows(timeline.before)}+ after={groupActivityRows(timeline.after)}+ sentAt={SENT_AT}+ failed={false}+ sendLabel="Email sent"+ sendDetail="Welcome email"+ comeback="Back in your app 1m after clicking the email"+ emptyAfter={null}+ hiddenBefore={2}+ onShowEarlier={() => {}}+ hiddenAfter={0}+ onShowLater={() => {}}+ />+)diff --git a/products/workflows/frontend/Transactional/log/TransactionalEmailActivityRail.tsx b/products/workflows/frontend/Transactional/log/TransactionalEmailActivityRail.tsxnew file mode 100644index 000000000000..8a0da88178a2--- /dev/null+++ b/products/workflows/frontend/Transactional/log/TransactionalEmailActivityRail.tsx@@ -0,0 +1,427 @@+import clsx from 'clsx'+import { ReactNode, useState } from 'react'++import { IconLetter } from '@posthog/icons'+import { LemonButton, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'++import ViewRecordingButton, { RecordingPlayerType } from 'lib/components/ViewRecordingButton/ViewRecordingButton'+import { dayjs } from 'lib/dayjs'+import { pluralize } from 'lib/utils/strings'+import { urls } from 'scenes/urls'++import { ActivityRow, describeActivityEvent, isCustomEvent, relativeToSend } from './emailActivity'+import { ActivityGroup, collapseGroup, gapBetween, groupDuration } from './emailActivityGroups'+import { EMAIL_STATUS_LABEL, EMAIL_STATUS_TAG } from './emailLogStatus'++type Marker = 'event' | 'outcome' | 'email'+type RailPosition = 'first' | 'middle' | 'last' | 'only'++function RailLine({ inSession, position }: { inSession: boolean; position: RailPosition }): JSX.Element | null {+ if (position === 'only') {+ return null+ }+ return (+ <span+ className={clsx(+ 'absolute left-1/2 -translate-x-1/2',+ position === 'first' ? 'top-1/2' : 'top-0',+ position === 'last' ? 'bottom-1/2' : 'bottom-0',+ 'bg-muted opacity-40',+ inSession ? 'w-0.5' : 'w-px'+ )}+ />+ )+}++function RailRow({+ time,+ inSession = false,+ position,+ marker,+ children,+}: {+ time?: ReactNode+ inSession?: boolean+ position: RailPosition+ marker?: ReactNode+ children: ReactNode+}): JSX.Element {+ return (+ <li className="grid grid-cols-[3.5rem_1.25rem_minmax(0,1fr)] gap-x-2 min-h-8">+ <span className="flex items-center text-xs text-secondary tabular-nums whitespace-nowrap">{time}</span>+ <span className="relative flex items-center justify-center">+ <RailLine inSession={inSession} position={position} />+ {marker}+ </span>+ <div className="flex items-center gap-2 min-w-0">{children}</div>+ </li>+ )+}++function Dot({ marker }: { marker: Marker }): JSX.Element {+ return (+ <span+ className={clsx(+ 'relative size-2 rounded-full border',+ marker === 'event' && 'bg-surface-primary border-muted',+ marker === 'outcome' && 'bg-warning border-warning',+ marker === 'email' && 'bg-surface-primary border-accent'+ )}+ />+ )+}++function Time({ at, sentAt }: { at: string; sentAt: string }): JSX.Element {+ return (+ <Tooltip title={relativeToSend(at, sentAt)}>+ <span>{dayjs(at).format('HH:mm:ss')}</span>+ </Tooltip>+ )+}++function RowContent({ row }: { row: ActivityRow }): JSX.Element {+ if (row.kind === 'otherEmail') {+ return (+ <>+ <span className="text-sm truncate">+ Got{' '}+ <Link+ to={urls.transactionalEmailLogEntry(row.entry.message_id)}+ data-attr="transactional-email-activity-other-email"+ >+ {row.entry.template_name || 'a deleted email'}+ </Link>+ </span>+ <LemonTag size="small" type={EMAIL_STATUS_TAG[row.entry.status]} className="shrink-0">+ {EMAIL_STATUS_LABEL[row.entry.status]}+ </LemonTag>+ </>+ )+ }+ const description = describeActivityEvent(row.event)+ return (+ <span className={clsx('text-sm truncate', isCustomEvent(row.event) && 'font-semibold')} title={description}>+ {description}+ {row.count > 1 && <span className="font-normal text-secondary"> ×{row.count}</span>}+ </span>+ )+}++function SessionLabel({ group }: { group: ActivityGroup }): JSX.Element {+ return (+ <>+ <span className="text-xs font-semibold uppercase tracking-wide text-secondary">Session</span>+ <span className="text-xs text-secondary whitespace-nowrap">+ {groupDuration(group)} · {pluralize(group.eventCount, 'event')}+ </span>+ <span className="flex-1" />+ <ViewRecordingButton+ sessionId={group.sessionId as string}+ timestamp={group.startAt}+ checkRecordingExists+ openPlayerIn={RecordingPlayerType.Modal}+ size="xsmall"+ type="secondary"+ label="Watch"+ data-attr="transactional-email-activity-recording"+ />+ </>+ )+}++type RailItem =+ | { key: string; kind: 'earlier' }+ | { key: string; kind: 'date'; label: string; inSession: boolean }+ | { key: string; kind: 'session'; group: ActivityGroup }+ | { key: string; kind: 'row'; row: ActivityRow; inSession: boolean }+ | { key: string; kind: 'gap'; text: string; highlighted: boolean }+ | { key: string; kind: 'send' }+ | { key: string; kind: 'note'; text: string }+ | { key: string; kind: 'later' }+ | { key: string; kind: 'more'; groupKey: string; hidden: number; inSession: boolean }++function dayLabel(at: string): string {+ return dayjs(at).format('MMM D')+}++/** Flattens the groups into one list, with a date row wherever the list crosses into another day. */+function buildRailItems(+ before: ActivityGroup[],+ after: ActivityGroup[],+ sentAt: string,+ comeback: string | null,+ emptyAfter: string | null,+ hasEarlier: boolean,+ hasLater: boolean,+ openGroups: ReadonlySet<string>+): RailItem[] {+ const items: RailItem[] = hasEarlier ? [{ key: 'earlier', kind: 'earlier' }] : []+ let day = dayLabel(before[0]?.startAt ?? sentAt)+ if (day !== dayLabel(sentAt)) {+ items.push({ key: `date-${day}`, kind: 'date', label: day, inSession: false })+ }+ const addDate = (at: string, inSession: boolean): void => {+ if (dayLabel(at) !== day) {+ day = dayLabel(at)+ items.push({ key: `date-${day}`, kind: 'date', label: day, inSession })+ }+ }+ const addGroups = (groups: ActivityGroup[], firstGapFrom: string | null): void => {+ groups.forEach((group, index) => {+ const previousEnd = index > 0 ? groups[index - 1].endAt : firstGapFrom+ const gap = previousEnd ? gapBetween(previousEnd, group.startAt) : null+ if (gap && dayLabel(group.startAt) === day) {+ items.push({ key: `gap-${group.key}`, kind: 'gap', text: gap, highlighted: false })+ }+ addDate(group.startAt, false)+ if (group.sessionId) {+ items.push({ key: `session-${group.key}`, kind: 'session', group })+ }+ const inSession = !!group.sessionId+ const { rows, hidden } = openGroups.has(group.key) ? { rows: group.rows, hidden: 0 } : collapseGroup(group)+ for (const row of rows) {+ addDate(row.at, inSession)+ items.push({ key: row.key, kind: 'row', row, inSession })+ }+ if (hidden > 0) {+ items.push({ key: `more-${group.key}`, kind: 'more', groupKey: group.key, hidden, inSession })+ }+ })+ }+ addGroups(before, null)+ addDate(sentAt, false)+ items.push({ key: 'send', kind: 'send' })+ if (comeback) {+ items.push({ key: 'comeback', kind: 'gap', text: comeback, highlighted: true })+ }+ addGroups(after, comeback ? null : sentAt)+ if (emptyAfter) {+ items.push({ key: 'empty', kind: 'note', text: emptyAfter })+ }+ if (hasLater) {+ items.push({ key: 'later', kind: 'later' })+ }+ return items+}++function railPosition(index: number, count: number): RailPosition {+ if (count === 1) {+ return 'only'+ }+ return index === 0 ? 'first' : index === count - 1 ? 'last' : 'middle'+}++function SendRow({+ position,+ sentAt,+ failed,+ sendLabel,+ sendDetail,+}: {+ position: RailPosition+ sentAt: string+ failed: boolean+ sendLabel: string+ sendDetail: string | null+}): JSX.Element {+ return (+ <RailRow+ position={position}+ time={dayjs(sentAt).format('HH:mm:ss')}+ marker={+ <span+ className={clsx(+ 'relative flex items-center justify-center size-5 rounded-full',+ failed ? 'bg-danger text-white' : 'bg-accent text-primary-inverse'+ )}+ >+ <IconLetter className="size-3" />+ </span>+ }+ >+ <div+ className={clsx(+ 'flex flex-1 flex-wrap items-center gap-x-2 min-w-0 rounded border px-2 py-1 my-1 text-sm font-semibold',+ failed+ ? 'border-danger bg-danger-highlight text-danger'+ : 'border-accent bg-accent-highlight-secondary text-accent'+ )}+ >+ {sendLabel}+ {sendDetail && <span className="text-xs font-normal text-secondary truncate">{sendDetail}</span>}+ </div>+ </RailRow>+ )+}++function ActivityRowEntry({+ row,+ inSession,+ position,+ sentAt,+}: {+ row: ActivityRow+ inSession: boolean+ position: RailPosition+ sentAt: string+}): JSX.Element {+ const marker: Marker = row.kind === 'otherEmail' ? 'email' : isCustomEvent(row.event) ? 'outcome' : 'event'+ return (+ <RailRow+ position={position}+ inSession={inSession}+ time={<Time at={row.at} sentAt={sentAt} />}+ marker={<Dot marker={marker} />}+ >+ <RowContent row={row} />+ </RailRow>+ )+}++export interface TransactionalEmailActivityRailProps {+ before: ActivityGroup[]+ after: ActivityGroup[]+ sentAt: string+ failed: boolean+ sendLabel: string+ sendDetail: string | null+ comeback: string | null+ emptyAfter: string | null+ hiddenBefore: number+ onShowEarlier: () => void+ hiddenAfter: number+ onShowLater: () => void+}++export function TransactionalEmailActivityRail({+ before,+ after,+ sentAt,+ failed,+ sendLabel,+ sendDetail,+ comeback,+ emptyAfter,+ hiddenBefore,+ onShowEarlier,+ hiddenAfter,+ onShowLater,+}: TransactionalEmailActivityRailProps): JSX.Element {+ const [openGroups, setOpenGroups] = useState<ReadonlySet<string>>(new Set())+ const items = buildRailItems(+ before,+ after,+ sentAt,+ comeback,+ emptyAfter,+ hiddenBefore > 0,+ hiddenAfter > 0,+ openGroups+ )+ const renderItem = (item: RailItem, position: RailPosition): JSX.Element => {+ switch (item.kind) {+ case 'earlier':+ return (+ <RailRow key={item.key} position={position}>+ <LemonButton+ size="xsmall"+ type="tertiary"+ className="-ml-1.5"+ onClick={onShowEarlier}+ data-attr="transactional-email-activity-show-earlier"+ >+ Show {pluralize(hiddenBefore, 'earlier event')}+ </LemonButton>+ </RailRow>+ )+ case 'more':+ return (+ <RailRow key={item.key} position={position} inSession={item.inSession}>+ <LemonButton+ size="xsmall"+ type="tertiary"+ className="-ml-1.5"+ onClick={() => setOpenGroups(new Set([...openGroups, item.groupKey]))}+ data-attr="transactional-email-activity-show-group"+ >+ Show {item.hidden} more+ </LemonButton>+ </RailRow>+ )+ case 'later':+ return (+ <RailRow key={item.key} position={position}>+ <LemonButton+ size="xsmall"+ type="tertiary"+ className="-ml-1.5"+ onClick={onShowLater}+ data-attr="transactional-email-activity-show-later"+ >+ Show {pluralize(hiddenAfter, 'later event')}+ </LemonButton>+ </RailRow>+ )+ case 'date':+ return (+ <RailRow key={item.key} position={position} inSession={item.inSession}>+ <span className="text-xs font-semibold text-secondary">{item.label}</span>+ </RailRow>+ )+ case 'session':+ return (+ <RailRow key={item.key} position={position} inSession>+ <SessionLabel group={item.group} />+ </RailRow>+ )+ case 'gap':+ return (+ <RailRow key={item.key} position={position}>+ <span+ className={clsx(+ 'text-xs truncate',+ item.highlighted ? 'font-semibold text-success' : 'text-secondary'+ )}+ >+ {item.text}+ </span>+ </RailRow>+ )+ case 'note':+ return (+ <RailRow key={item.key} position={position}>+ <span className="text-sm text-secondary">{item.text}</span>+ </RailRow>+ )+ case 'send':+ return (+ <SendRow+ key={item.key}+ position={position}+ sentAt={sentAt}+ failed={failed}+ sendLabel={sendLabel}+ sendDetail={sendDetail}+ />+ )+ case 'row':+ return (+ <ActivityRowEntry+ key={item.key}+ row={item.row}+ inSession={item.inSession}+ position={position}+ sentAt={sentAt}+ />+ )+ }+ }+ return (+ <ol+ className="flex flex-col m-0 p-0 list-none max-h-160 overflow-y-auto"+ data-attr="transactional-email-activity"+ >+ {items.map((item, index) => renderItem(item, railPosition(index, items.length)))}+ </ol>+ )+}diff --git a/products/workflows/frontend/Transactional/log/TransactionalEmailActivityRow.tsx b/products/workflows/frontend/Transactional/log/TransactionalEmailActivityRow.tsxdeleted file mode 100644index c56996b2c248..000000000000--- a/products/workflows/frontend/Transactional/log/TransactionalEmailActivityRow.tsx+++ /dev/null@@ -1,131 +0,0 @@-import clsx from 'clsx'--import { IconBolt, IconCursorClick, IconEye, IconLetter } from '@posthog/icons'-import { LemonTag, Link, Tooltip } from '@posthog/lemon-ui'--import { TZLabel } from 'lib/components/TZLabel'-import ViewRecordingButton, { RecordingPlayerType } from 'lib/components/ViewRecordingButton/ViewRecordingButton'-import { urls } from 'scenes/urls'--import type { EmailLogEventKindEnumApi } from 'products/messaging/frontend/generated/api.schemas'--import { ActivityEvent, ActivityRow, describeActivityEvent, isCustomEvent, relativeToSend } from './emailActivity'-import { EMAIL_STATUS_LABEL, EMAIL_STATUS_TAG, emailReasonText } from './emailLogStatus'--const EMAIL_EVENT_LABEL: Record<EmailLogEventKindEnumApi, string> = {- queued: 'Email queued',- sent: 'Email sent',- delivered: 'Email delivered',- opened: 'Opened the email',- clicked: 'Clicked a link in the email',- bounced: 'Email bounced',- complained: 'Marked the email as spam',- failed: "Email wasn't sent",-}--const FAILED_KINDS: EmailLogEventKindEnumApi[] = ['bounced', 'complained', 'failed']--function EventIcon({ event }: { event: ActivityEvent }): JSX.Element {- if (event.event === '$pageview' || event.event === '$screen') {- return <IconEye />- }- if (event.event === '$autocapture' || event.event === '$rageclick') {- return <IconCursorClick />- }- return <IconBolt />-}--function TimeCell({ at, sentAt }: { at: string; sentAt: string }): JSX.Element {- return (- <Tooltip title={<TZLabel time={at} formatDate="MMM D, YYYY" formatTime="HH:mm:ss" noStyles />}>- <span className="text-xs text-secondary whitespace-nowrap tabular-nums">{relativeToSend(at, sentAt)}</span>- </Tooltip>- )-}--export function TransactionalEmailActivityRow({ row, sentAt }: { row: ActivityRow; sentAt: string }): JSX.Element {- if (row.kind === 'session') {- return (- <li className="flex items-center gap-3 pt-3 first:pt-0">- <span className="text-xs font-semibold uppercase tracking-wide text-secondary">Session</span>- <TZLabel time={row.at} className="text-xs text-secondary" />- <span className="h-px flex-1 bg-border" />- <ViewRecordingButton- sessionId={row.sessionId}- timestamp={row.at}- checkRecordingExists- openPlayerIn={RecordingPlayerType.Modal}- size="xsmall"- type="secondary"- label="Watch"- data-attr="transactional-email-activity-recording"- />- </li>- )- }- if (row.kind === 'emailGroup') {- return (- <li className="flex flex-col gap-1 rounded border border-l-2 border-l-accent bg-surface-secondary px-3 py-2">- {row.rows.map((emailRow) => {- const failed = FAILED_KINDS.includes(emailRow.event.kind)- const reason = emailReasonText(emailRow.event.reason)- return (- <div key={emailRow.key} className="flex items-center gap-3 min-w-0">- <span className={clsx('flex shrink-0 text-base', failed ? 'text-danger' : 'text-accent')}>- <IconLetter />- </span>- <span- className={clsx(- 'flex-1 min-w-0 text-sm font-semibold truncate',- failed && 'text-danger'- )}- >- {EMAIL_EVENT_LABEL[emailRow.event.kind]}- {reason && <span className="font-normal text-secondary"> · {reason}</span>}- </span>- <TimeCell at={emailRow.at} sentAt={sentAt} />- </div>- )- })}- </li>- )- }- if (row.kind === 'otherEmail') {- return (- <li className="flex items-center gap-3 px-2 -mx-2 py-1">- <span className="flex shrink-0 text-base text-secondary">- <IconLetter />- </span>- <span className="flex-1 min-w-0 flex items-center gap-2 text-sm">- <span className="truncate">- Got{' '}- <Link- to={urls.transactionalEmailLogEntry(row.entry.message_id)}- data-attr="transactional-email-activity-other-email"- >- {row.entry.template_name || 'a deleted email'}- </Link>- </span>- <LemonTag size="small" type={EMAIL_STATUS_TAG[row.entry.status]} className="shrink-0">- {EMAIL_STATUS_LABEL[row.entry.status]}- </LemonTag>- </span>- <TimeCell at={row.at} sentAt={sentAt} />- </li>- )- }- const custom = isCustomEvent(row.event)- const description = describeActivityEvent(row.event)- return (- <li className="flex items-center gap-3 px-2 -mx-2 py-1">- <span className={clsx('flex shrink-0 text-base', custom ? 'text-warning' : 'text-secondary')}>- <EventIcon event={row.event} />- </span>- <span className={clsx('flex-1 min-w-0 text-sm truncate', custom && 'font-semibold')} title={description}>- {description}- {row.count > 1 && <span className="font-normal text-secondary"> ×{row.count}</span>}- </span>- <TimeCell at={row.at} sentAt={sentAt} />- </li>- )-}diff --git a/products/workflows/frontend/Transactional/log/TransactionalEmailActivitySummary.tsx b/products/workflows/frontend/Transactional/log/TransactionalEmailActivitySummary.tsxdeleted file mode 100644index bce14bf7947f..000000000000--- a/products/workflows/frontend/Transactional/log/TransactionalEmailActivitySummary.tsx+++ /dev/null@@ -1,39 +0,0 @@-import { IconBolt } from '@posthog/icons'-import { LemonTag } from '@posthog/lemon-ui'--import { pluralize } from 'lib/utils/strings'--import type { TransactionalEmailLogEventApi } from 'products/messaging/frontend/generated/api.schemas'--import { ActivityEvent, summarizeAfter } from './emailActivity'--/** How many custom events the summary names before it stops. */-const MAX_OUTCOMES = 4--export function TransactionalEmailActivitySummary({- after,- timeline,-}: {- after: ActivityEvent[]- timeline: readonly TransactionalEmailLogEventApi[]-}): JSX.Element | null {- if (!after.length) {- return null- }- const { comeback, eventCount, sessionCount, outcomes } = summarizeAfter(after, timeline)- return (- <div className="flex flex-wrap items-center gap-2 text-sm">- {comeback && <LemonTag type="success">{comeback}</LemonTag>}- <LemonTag type="muted">- {pluralize(eventCount, 'event')} after the email- {sessionCount > 0 ? ` across ${pluralize(sessionCount, 'session')}` : ''}- </LemonTag>- {outcomes.length > 0 && <span className="text-xs text-secondary">Then did</span>}- {outcomes.slice(0, MAX_OUTCOMES).map((outcome) => (- <LemonTag key={outcome} type="warning" icon={<IconBolt />}>- {outcome}- </LemonTag>- ))}- </div>- )-}diff --git a/products/workflows/frontend/Transactional/log/TransactionalEmailActivityTimeline.tsx b/products/workflows/frontend/Transactional/log/TransactionalEmailActivityTimeline.tsxindex fb7e5d7021e3..e48ce782addd 100644--- a/products/workflows/frontend/Transactional/log/TransactionalEmailActivityTimeline.tsx+++ b/products/workflows/frontend/Transactional/log/TransactionalEmailActivityTimeline.tsx@@ -1,21 +1,60 @@import { useActions, useValues } from 'kea'-import { LemonBanner, LemonButton } from '@posthog/lemon-ui'+import { LemonBanner } from '@posthog/lemon-ui'import { dayjs } from 'lib/dayjs'import { pluralize } from 'lib/utils/strings'import type { TransactionalEmailLogDetailApi } from 'products/messaging/frontend/generated/api.schemas'-import { ACTIVITY_WINDOW_DAYS, PersonActivity, buildActivityTimeline, emailSentAt } from './emailActivity'-import { TransactionalEmailActivityRow } from './TransactionalEmailActivityRow'-import { TransactionalEmailActivitySummary } from './TransactionalEmailActivitySummary'+import {+ ACTIVITY_WINDOW_DAYS,+ PersonActivity,+ buildActivityTimeline,+ describeComeback,+ emailSentAt,+} from './emailActivity'+import { groupActivityRows } from './emailActivityGroups'+import { gapLabel } from './emailDeliverySteps'+import { TransactionalEmailActivityRail } from './TransactionalEmailActivityRail'import { transactionalEmailLogEntryLogic } from './transactionalEmailLogEntryLogic'/** How many events before the send show until the reader asks for more. */const BEFORE_PREVIEW = 5-/** The person's loaded activity, split into what they did before and after the email. */+/** How many sessions or runs of events after the send show until the reader asks for more. */+const AFTER_GROUPS_PREVIEW = 5++function sendLabel(email: TransactionalEmailLogDetailApi, sentAt: string): string {+ const went = email.timeline.some((event) => event.kind === 'sent')+ if (email.status === 'bounced') {+ const bouncedAt = email.timeline.find((event) => event.kind === 'bounced')?.at+ const gap = bouncedAt ? gapLabel(bouncedAt, sentAt) : null+ return `Email sent, bounced${gap ? ` ${gap}` : ''}`+ }+ if (email.status === 'complained') {+ return 'Email sent, marked as spam'+ }+ if (email.status === 'failed') {+ return went ? 'Email sent, then failed' : "Email wasn't sent"+ }+ return 'Email sent'+}++function emptyAfterText(activity: PersonActivity, sentAt: string): string | null {+ if (activity.after.length) {+ return null+ }+ const days = pluralize(ACTIVITY_WINDOW_DAYS, 'day')+ if (!activity.before.length) {+ return `No events from this person in the ${days} before or after this email.`+ }+ return dayjs().isAfter(dayjs(sentAt).add(ACTIVITY_WINDOW_DAYS, 'day'))+ ? `No activity in your product in the ${days} after this email.`+ : 'No activity in your product since this email.'+}++/** The person's loaded activity on one rail, with the email pinned where it went out. */export function TransactionalEmailActivityTimeline({email,activity,@@ -23,24 +62,28 @@ export function TransactionalEmailActivityTimeline({email: TransactionalEmailLogDetailApiactivity: PersonActivity}): JSX.Element {- const { beforeExpanded, otherEmails, otherEmailsFailed, otherEmailsLoading } = useValues(+ const { beforeExpanded, afterExpanded, otherEmails, otherEmailsFailed, otherEmailsLoading } = useValues(transactionalEmailLogEntryLogic)- const { showAllBefore, loadOtherEmails } = useActions(transactionalEmailLogEntryLogic)+ const { showAllBefore, showAllAfter, loadOtherEmails } = useActions(transactionalEmailLogEntryLogic)const before = beforeExpanded ? activity.before : activity.before.slice(-BEFORE_PREVIEW)const hiddenBefore = activity.before.length - before.length- const emailEvents = email.timeline.filter((event) => event.kind !== 'queued')// Other emails before the send only show alongside the events the reader chose to show.const earliestShown = before[0]?.timestamp ?? email.created_atconst shownOtherEmails = otherEmails.filter((entry) => !dayjs(entry.created_at).isBefore(earliestShown))- // Times read relative to when the email went out, which is what a reader compares against.const sentAt = emailSentAt(email)- const timeline = buildActivityTimeline([...before, ...activity.after], emailEvents, shownOtherEmails, sentAt)+ const timeline = buildActivityTimeline([...before, ...activity.after], shownOtherEmails, sentAt)+ const groupsBefore = groupActivityRows(timeline.before)+ const allGroupsAfter = groupActivityRows(timeline.after)+ const groupsAfter = afterExpanded ? allGroupsAfter : allGroupsAfter.slice(0, AFTER_GROUPS_PREVIEW)+ const hiddenAfter = allGroupsAfter+ .slice(groupsAfter.length)+ .reduce((total, group) => total + Math.max(group.eventCount, group.rows.length), 0)const nothingAround = !activity.before.length && !activity.after.length+ const noSessions = !nothingAround && ![...groupsBefore, ...allGroupsAfter].some((group) => group.sessionId)return (- <div className="flex flex-col gap-4">- <TransactionalEmailActivitySummary after={activity.after} timeline={email.timeline} />+ <div className="flex flex-col gap-3">{otherEmailsFailed && !otherEmailsLoading && (<LemonBannertype="error"@@ -53,54 +96,31 @@ export function TransactionalEmailActivityTimeline({This person's other emails couldn't load. Check your connection and try again.</LemonBanner>)}- {timeline.before.length > 0 && (- <div className="flex flex-col gap-2">- <div className="flex items-center justify-between gap-2">- <h4 className="text-sm font-semibold m-0">Before the email</h4>- {hiddenBefore > 0 && (- <LemonButton- size="xsmall"- type="tertiary"- onClick={showAllBefore}- data-attr="transactional-email-activity-show-earlier"- >- Show {pluralize(hiddenBefore, 'earlier event')}- </LemonButton>- )}- </div>- <ol className="flex flex-col gap-1 m-0 p-0 list-none">- {timeline.before.map((row) => (- <TransactionalEmailActivityRow key={row.key} row={row} sentAt={sentAt} />- ))}- </ol>+ <TransactionalEmailActivityRail+ before={groupsBefore}+ after={groupsAfter}+ sentAt={sentAt}+ failed={['bounced', 'complained', 'failed'].includes(email.status)}+ sendLabel={sendLabel(email, sentAt)}+ sendDetail={email.template_name || null}+ comeback={describeComeback(activity.after, email.timeline)}+ emptyAfter={emptyAfterText(activity, sentAt)}+ hiddenBefore={hiddenBefore}+ onShowEarlier={showAllBefore}+ hiddenAfter={hiddenAfter}+ onShowLater={showAllAfter}+ />+ {(noSessions || (activity.hasMoreAfter && hiddenAfter === 0)) && (+ <div className="flex flex-col gap-1 text-xs text-secondary">+ {noSessions && <span>These events have no session, so there's no replay to watch.</span>}+ {activity.hasMoreAfter && hiddenAfter === 0 && (+ <span>+ Showing the first {activity.after.length} events after the email. See the rest on the+ person's page.+ </span>+ )}</div>)}- <div className="flex flex-col gap-2">- <h4 className="text-sm font-semibold m-0">After the email</h4>- <ol className="flex flex-col gap-1 m-0 p-0 list-none" data-attr="transactional-email-activity">- {timeline.after.map((row) => (- <TransactionalEmailActivityRow key={row.key} row={row} sentAt={sentAt} />- ))}- </ol>- {!activity.after.length && (- <p- className="text-sm text-secondary m-0 rounded border border-dashed px-3 py-2"- data-attr="transactional-email-activity-nothing-after"- >- {nothingAround- ? `No events from this person in the ${pluralize(ACTIVITY_WINDOW_DAYS, 'day')} before or after this email.`- : dayjs().isAfter(dayjs(sentAt).add(ACTIVITY_WINDOW_DAYS, 'day'))- ? `No activity in your product in the ${pluralize(ACTIVITY_WINDOW_DAYS, 'day')} after this email.`- : 'No activity in your product since this email.'}- </p>- )}- {activity.hasMoreAfter && (- <p className="text-xs text-secondary m-0">- Showing the first {activity.after.length} events after the email. See the rest on the person's- page.- </p>- )}- </div></div>)}diff --git a/products/workflows/frontend/Transactional/log/TransactionalEmailDeliveryProgress.tsx b/products/workflows/frontend/Transactional/log/TransactionalEmailDeliveryProgress.tsxindex c5b2d6a87cf2..1c232aea7e00 100644--- a/products/workflows/frontend/Transactional/log/TransactionalEmailDeliveryProgress.tsx+++ b/products/workflows/frontend/Transactional/log/TransactionalEmailDeliveryProgress.tsx@@ -5,14 +5,25 @@ import { TransactionalEmailDeliveryStep } from './TransactionalEmailDeliveryStepexport function TransactionalEmailDeliveryProgress({ email }: { email: TransactionalEmailLogDetailApi }): JSX.Element {const steps = buildDeliverySteps(email)+ const failureReason = steps.find((step) => step.state === 'failed')?.detailreturn (- <ol- className="flex flex-col @2xl:flex-row gap-3 @2xl:gap-0 m-0 p-4 list-none border rounded bg-surface-primary"- data-attr="transactional-email-delivery-progress"- >- {steps.map((step, index) => (- <TransactionalEmailDeliveryStep key={step.key} step={step} next={steps[index + 1]} />- ))}- </ol>+ <div className="border rounded bg-surface-primary overflow-hidden">+ <ol+ className="flex flex-col @2xl:flex-row gap-3 @2xl:gap-0 m-0 p-4 list-none"+ data-attr="transactional-email-delivery-progress"+ >+ {steps.map((step, index) => (+ <TransactionalEmailDeliveryStep key={step.key} step={step} next={steps[index + 1]} />+ ))}+ </ol>+ {failureReason && (+ <div+ className="border-t border-danger bg-danger-highlight text-danger px-4 py-2 text-sm"+ data-attr="transactional-email-failure-reason"+ >+ {failureReason}+ </div>+ )}+ </div>)}diff --git a/products/workflows/frontend/Transactional/log/TransactionalEmailDeliveryStep.tsx b/products/workflows/frontend/Transactional/log/TransactionalEmailDeliveryStep.tsxindex c97252c24222..4e86f6a88bd9 100644--- a/products/workflows/frontend/Transactional/log/TransactionalEmailDeliveryStep.tsx+++ b/products/workflows/frontend/Transactional/log/TransactionalEmailDeliveryStep.tsx@@ -7,6 +7,11 @@ import { TZLabel } from 'lib/components/TZLabel'import { DeliveryStep, gapLabel } from './emailDeliverySteps'+function StepDetail({ detail }: { detail: string }): JSX.Element {+ const text = <span className="text-xs text-secondary truncate">{detail}</span>+ return detail.length > 40 ? <Tooltip title={detail}>{text}</Tooltip> : text+}+/** One step of the delivery progress, and the line that leads to the next step. */export function TransactionalEmailDeliveryStep({step,@@ -61,14 +66,7 @@ export function TransactionalEmailDeliveryStep({</span>))}- {step.detail &&- (step.detail.length > 40 ? (- <Tooltip title={step.detail}>- <span className="text-xs text-secondary truncate">{step.detail}</span>- </Tooltip>- ) : (- <span className="text-xs text-secondary">{step.detail}</span>- ))}+ {step.detail && step.state !== 'failed' && <StepDetail detail={step.detail} />}</div></li>)diff --git a/products/workflows/frontend/Transactional/log/TransactionalEmailDetails.tsx b/products/workflows/frontend/Transactional/log/TransactionalEmailDetails.tsxindex 97b44dafdb9a..6336549635c8 100644--- a/products/workflows/frontend/Transactional/log/TransactionalEmailDetails.tsx+++ b/products/workflows/frontend/Transactional/log/TransactionalEmailDetails.tsx@@ -1,3 +1,5 @@+import clsx from 'clsx'+import { LemonTag, Link, Tooltip } from '@posthog/lemon-ui'import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'@@ -21,7 +23,9 @@ function DetailRow({return (<divclassName={- stacked ? 'flex flex-col gap-0.5 text-sm' : 'flex justify-between items-baseline gap-4 text-sm min-w-0'+ stacked+ ? 'flex flex-col gap-0.5 text-sm min-w-0'+ : 'flex justify-between items-baseline gap-4 text-sm min-w-0'}><dt className="text-secondary shrink-0">{label}</dt>@@ -30,6 +34,26 @@ function DetailRow({)}+/** Long IDs truncate beside their copy button, so the button stays in view. */+function CopyableId({+ description,+ value,+ className,+}: {+ description: string+ value: string+ className?: string+}): JSX.Element {+ return (+ <div className={clsx('flex items-center gap-1 min-w-0', className)}>+ <span className="truncate font-mono text-xs" title={value}>+ {value}+ </span>+ <CopyToClipboardInline description={description} explicitValue={value} iconSize="xsmall" />+ </div>+ )+}+export function TransactionalEmailDetails({ email }: { email: TransactionalEmailLogDetailApi }): JSX.Element {return (<section className="border rounded bg-surface-primary p-4 flex flex-col gap-3">@@ -57,21 +81,11 @@ export function TransactionalEmailDetails({ email }: { email: TransactionalEmail{email.sending_domain && <DetailRow label="Sending domain">{email.sending_domain}</DetailRow>}{email.distinct_id && (<DetailRow label="Distinct ID" stacked>- <span className="ph-no-capture">- <CopyToClipboardInline- description="distinct ID"- explicitValue={email.distinct_id}- iconSize="xsmall"- >- <span className="font-mono text-xs">{email.distinct_id}</span>- </CopyToClipboardInline>- </span>+ <CopyableId description="distinct ID" value={email.distinct_id} className="ph-no-capture" /></DetailRow>)}<DetailRow label="Message ID" stacked>- <CopyToClipboardInline description="message ID" explicitValue={email.message_id} iconSize="xsmall">- <span className="font-mono text-xs">{email.message_id}</span>- </CopyToClipboardInline>+ <CopyableId description="message ID" value={email.message_id} /></DetailRow></dl></section>diff --git a/products/workflows/frontend/Transactional/log/emailActivity.test.ts b/products/workflows/frontend/Transactional/log/emailActivity.test.tsindex 9b12fafb0e8a..c3a7a376a958 100644--- a/products/workflows/frontend/Transactional/log/emailActivity.test.ts+++ b/products/workflows/frontend/Transactional/log/emailActivity.test.ts@@ -1,9 +1,9 @@-import { ActivityEvent, ActivityRow, buildActivityTimeline, emailSentAt, summarizeAfter } from './emailActivity'+import { ActivityEvent, ActivityRow, buildActivityTimeline, describeComeback, emailSentAt } from './emailActivity'-function event(uuid: string, timestamp: string, sessionId: string | null): ActivityEvent {+function event(uuid: string, timestamp: string, sessionId: string | null, name = '$pageview'): ActivityEvent {return {uuid,- event: '$pageview',+ event: name,timestamp,url: null,pathname: '/files',@@ -14,7 +14,7 @@ function event(uuid: string, timestamp: string, sessionId: string | null): Activ}describe('emailActivity', () => {- it('splits at the send, starts the after part with the email block, folds repeats, and keeps other emails in order', () => {+ it('splits at the send, folds repeats, and keeps other emails in order', () => {const timeline = buildActivityTimeline([event('before', '2026-06-15T08:59:00Z', 's1'),@@ -22,11 +22,6 @@ describe('emailActivity', () => {{ ...event('after-2', '2026-06-15T09:04:00Z', 's2'), pathname: '/pricing' },{ ...event('after-3', '2026-06-15T09:04:10Z', 's2'), pathname: '/pricing' },],- [- { kind: 'sent', at: '2026-06-15T09:00:00Z', reason: null },- { kind: 'delivered', at: '2026-06-15T09:00:02Z', reason: null },- { kind: 'clicked', at: '2026-06-15T09:02:00Z', reason: null },- ],[{message_id: 'receipt',@@ -47,19 +42,22 @@ describe('emailActivity', () => {)const shape = (rows: ActivityRow[]): string[] =>- rows.map((row) =>- row.kind === 'emailGroup'- ? `emailGroup(${row.rows.length})`- : row.kind === 'event'- ? `event(${row.count})`- : row.kind- )- expect(shape(timeline.before)).toEqual(['session', 'event(1)'])- expect(shape(timeline.after)).toEqual(['emailGroup(3)', 'session', 'event(1)', 'event(2)', 'otherEmail'])+ rows.map((row) => (row.kind === 'event' ? `event(${row.count})` : row.kind))+ expect(shape(timeline.before)).toEqual(['event(1)'])+ expect(shape(timeline.after)).toEqual(['event(1)', 'event(2)', 'otherEmail'])+ })++ it('does not count a server-side event as the person coming back', () => {+ const clicked = { kind: 'clicked' as const, at: '2026-06-15T09:02:00Z', reason: null }++ expect(describeComeback([event('server', '2026-06-15T09:03:00Z', null, 'invoice_paid')], [clicked])).toBeNull()+ expect(describeComeback([event('page', '2026-06-15T09:03:00Z', null)], [clicked])).toBe(+ 'Back in your app 1m after clicking the email'+ )})it('keeps a return to the app that came before a later open of the email', () => {- const summary = summarizeAfter(+ const comeback = describeComeback([event('return', '2026-06-15T09:03:00Z', 's1')],[{ kind: 'clicked', at: '2026-06-15T09:02:00Z', reason: null },@@ -67,7 +65,7 @@ describe('emailActivity', () => {])- expect(summary.comeback).toBe('Back in your app 1m after clicking the email')+ expect(comeback).toBe('Back in your app 1m after clicking the email')})it('splits the activity at the send, or at the queue time when nothing went out', () => {diff --git a/products/workflows/frontend/Transactional/log/emailActivity.ts b/products/workflows/frontend/Transactional/log/emailActivity.tsindex 73a4d1a62477..36f6d26a3ff0 100644--- a/products/workflows/frontend/Transactional/log/emailActivity.ts+++ b/products/workflows/frontend/Transactional/log/emailActivity.ts@@ -14,6 +14,8 @@ import type {export const ACTIVITY_WINDOW_DAYS = 7export const ACTIVITY_BEFORE_LIMIT = 50export const ACTIVITY_AFTER_LIMIT = 100+/** A row with no session of its own stays with activity it happened this close to. */+export const ACTIVITY_JOIN_MINUTES = 30export interface ActivityEvent {uuid: string@@ -81,6 +83,8 @@ export type ActivityEventRow = {event: ActivityEvent/** How many identical events in a row this one stands for. */count: number+ /** When the last of those identical events happened. */+ lastAt: string}export type ActivityOtherEmailRow = {kind: 'otherEmail'@@ -88,33 +92,31 @@ export type ActivityOtherEmailRow = {at: stringentry: TransactionalEmailLogEntryApi}-export type ActivityEmailRow = { kind: 'email'; key: string; at: string; event: TransactionalEmailLogEventApi }-export type ActivityRow =- | { kind: 'session'; key: string; sessionId: string; at: string }- | ActivityEventRow- | ActivityOtherEmailRow- | { kind: 'emailGroup'; key: string; at: string; rows: ActivityEmailRow[] }+export type ActivityRow = ActivityEventRow | ActivityOtherEmailRowexport interface ActivityTimeline {/** What the person did before the email went out. */before: ActivityRow[]- /** The email's own steps, then what the person did after it went out. */+ /** What the person did after the email went out. */after: ActivityRow[]}-/**- * The person's events, this email's steps and their other emails, in time order and split at the send. A row starts- * each session, the email's consecutive steps fold into one block, and repeats of one interaction fold into one row.- */+/** The person's events and other emails, in time order and split at the send. Repeats of one interaction fold into one row. */export function buildActivityTimeline(events: ActivityEvent[],- emailEvents: TransactionalEmailLogEventApi[],otherEmails: TransactionalEmailLogEntryApi[],sentAt: string): ActivityTimeline {- const merged: (ActivityEventRow | ActivityEmailRow | ActivityOtherEmailRow)[] = [+ const merged: ActivityRow[] = [...events.map(- (event): ActivityEventRow => ({ kind: 'event', key: event.uuid, at: event.timestamp, event, count: 1 })+ (event): ActivityEventRow => ({+ kind: 'event',+ key: event.uuid,+ at: event.timestamp,+ lastAt: event.timestamp,+ event,+ count: 1,+ })),...otherEmails.map((entry): ActivityOtherEmailRow => ({@@ -124,55 +126,32 @@ export function buildActivityTimeline(entry,})),- ...emailEvents.map(- (event, index): ActivityEmailRow => ({- kind: 'email',- key: `email-${event.kind}-${index}`,- at: event.at,- event,- })- ),].sort((a, b) => dayjs(a.at).valueOf() - dayjs(b.at).valueOf())const sent = dayjs(sentAt)- const isBefore = (row: ActivityEventRow | ActivityEmailRow | ActivityOtherEmailRow): boolean =>- row.kind !== 'email' && dayjs(row.at).isBefore(sent)+ const isBefore = (row: ActivityRow): boolean => dayjs(row.at).isBefore(sent)return {before: foldRows(merged.filter(isBefore)),after: foldRows(merged.filter((row) => !isBefore(row))),}}-function foldRows(merged: (ActivityEventRow | ActivityEmailRow | ActivityOtherEmailRow)[]): ActivityRow[] {+function foldRows(merged: ActivityRow[]): ActivityRow[] {const rows: ActivityRow[] = []- let currentSession: string | null = nullfor (const row of merged) {const last = rows[rows.length - 1]- if (row.kind === 'email') {- if (last?.kind === 'emailGroup') {- last.rows.push(row)- } else {- rows.push({ kind: 'emailGroup', key: `group-${row.key}`, at: row.at, rows: [row] })- }- continue- }- if (row.kind === 'otherEmail') {- rows.push(row)- continue- }if (+ row.kind === 'event' &&last?.kind === 'event' &&last.event.event === row.event.event &&last.event.sessionId === row.event.sessionId &&+ (!!row.event.sessionId || dayjs(row.at).diff(dayjs(last.lastAt), 'minute') < ACTIVITY_JOIN_MINUTES) &&describeActivityEvent(last.event) === describeActivityEvent(row.event)) {last.count += 1+ last.lastAt = row.atcontinue}- if (row.event.sessionId && row.event.sessionId !== currentSession) {- currentSession = row.event.sessionId- rows.push({ kind: 'session', key: `session-${row.key}`, sessionId: row.event.sessionId, at: row.at })- }rows.push(row)}return rows@@ -188,26 +167,22 @@ export function relativeToSend(at: string, sentAt: string): string {return seconds < 0 ? `${duration} before` : `${duration} after`}-export interface ActivityAfterSummary {- /** For example "Back in your app 3m after clicking", when the person returned after engaging with the email. */- comeback: string | null- eventCount: number- sessionCount: number- /** The custom events they did after the email, in the order they first did them. */- outcomes: string[]-}-/** When the email went out, which is the line between what the person did before and after it. */export function emailSentAt(email: Pick<TransactionalEmailLogDetailApi, 'timeline' | 'created_at'>): string {return email.timeline.find((event) => event.kind === 'sent')?.at ?? email.created_at}+/** A server-side event has no session or page, so it does not show that the person came back. */+function isPersonInApp(event: ActivityEvent): boolean {+ return !!event.sessionId || event.event === '$pageview' || event.event === '$screen'+}+function firstReturnToApp(after: ActivityEvent[],timeline: readonly TransactionalEmailLogEventApi[]): { event: ActivityEvent; engagement: TransactionalEmailLogEventApi } | null {const engagements = timeline.filter((event) => event.kind === 'clicked' || event.kind === 'opened').reverse()- for (const event of after) {+ for (const event of after.filter(isPersonInApp)) {const engagement = engagements.find((candidate) => dayjs(event.timestamp).isAfter(candidate.at))if (engagement) {return { event, engagement }@@ -216,21 +191,18 @@ function firstReturnToApp(return null}-export function summarizeAfter(+/** For example "Back in your app 3m after clicking the email", when the person returned after engaging with it. */+export function describeComeback(after: ActivityEvent[],timeline: readonly TransactionalEmailLogEventApi[]-): ActivityAfterSummary {+): string | null {const firstReturn = firstReturnToApp(after, timeline)- const comeback = firstReturn- ? `Back in your app ${humanFriendlyDuration(- Math.max(1, dayjs(firstReturn.event.timestamp).diff(dayjs(firstReturn.engagement.at), 'second')),- { maxUnits: 1 }- )} after ${firstReturn.engagement.kind === 'clicked' ? 'clicking the email' : 'opening the email'}`- : null- return {- comeback,- eventCount: after.length,- sessionCount: new Set(after.map((event) => event.sessionId).filter(Boolean)).size,- outcomes: Array.from(new Set(after.filter(isCustomEvent).map((event) => event.event))),+ if (!firstReturn) {+ return null}+ const backAfter = humanFriendlyDuration(+ Math.max(1, dayjs(firstReturn.event.timestamp).diff(dayjs(firstReturn.engagement.at), 'second')),+ { maxUnits: 1 }+ )+ return `Back in your app ${backAfter} after ${firstReturn.engagement.kind === 'clicked' ? 'clicking' : 'opening'} the email`}diff --git a/products/workflows/frontend/Transactional/log/emailActivityGroups.test.ts b/products/workflows/frontend/Transactional/log/emailActivityGroups.test.tsnew file mode 100644index 000000000000..77a3ff5d1b79--- /dev/null+++ b/products/workflows/frontend/Transactional/log/emailActivityGroups.test.ts@@ -0,0 +1,110 @@+import { ActivityEvent, ActivityRow, buildActivityTimeline } from './emailActivity'+import { collapseGroup, groupActivityRows, groupDuration } from './emailActivityGroups'++function event(uuid: string, timestamp: string, sessionId: string | null, name = '$pageview'): ActivityEvent {+ return {+ uuid,+ event: name,+ timestamp,+ url: null,+ pathname: name === '$pageview' ? `/${uuid}` : null,+ sessionId,+ eventType: null,+ elementsChain: '',+ }+}++function rows(events: ActivityEvent[]): ActivityRow[] {+ return buildActivityTimeline(events, [], '2026-06-15T08:00:00Z').after+}++describe('emailActivityGroups', () => {+ it.each([+ {+ name: 'starts a new group for each session',+ events: [+ event('a', '2026-06-15T09:00:00Z', 's1'),+ event('b', '2026-06-15T09:01:00Z', 's1'),+ event('c', '2026-06-15T10:00:00Z', 's2'),+ ],+ expected: [+ ['s1', ['a', 'b']],+ ['s2', ['c']],+ ],+ },+ {+ name: 'keeps a server-side event inside the session it happened in',+ events: [+ event('a', '2026-06-15T09:00:00Z', 's1'),+ event('paid', '2026-06-15T09:01:00Z', null, 'invoice_paid'),+ event('b', '2026-06-15T09:02:00Z', 's1'),+ ],+ expected: [['s1', ['a', 'paid', 'b']]],+ },+ {+ name: 'splits off an event with no session once the session has gone quiet',+ events: [event('a', '2026-06-15T09:00:00Z', 's1'), event('later', '2026-06-15T12:00:00Z', null)],+ expected: [+ ['s1', ['a']],+ [null, ['later']],+ ],+ },+ {+ name: 'does not fold a much later event with no session into the session',+ events: [+ event('a', '2026-06-15T09:00:00Z', 's1'),+ event('sync-1', '2026-06-15T09:01:00Z', null, 'synced'),+ event('sync-2', '2026-06-15T12:00:00Z', null, 'synced'),+ ],+ expected: [+ ['s1', ['a', 'sync-1']],+ [null, ['sync-2']],+ ],+ },+ {+ name: 'starts a session group after events with no session',+ events: [event('first', '2026-06-15T09:00:00Z', null), event('a', '2026-06-15T09:01:00Z', 's1')],+ expected: [+ [null, ['first']],+ ['s1', ['a']],+ ],+ },+ ])('$name', ({ events, expected }) => {+ const groups = groupActivityRows(rows(events))+ expect(groups.map((group) => [group.sessionId, group.rows.map((row) => row.key)])).toEqual(expected)+ })++ it('collapses a long group to its custom events once each, and counts what it leaves out', () => {+ const events = [+ event('a', '2026-06-15T09:00:00Z', 's1'),+ event('sync-1', '2026-06-15T09:00:10Z', 's1', 'synced'),+ event('b', '2026-06-15T09:00:20Z', 's1'),+ event('paid', '2026-06-15T09:00:30Z', 's1', 'paid'),+ event('c', '2026-06-15T09:00:40Z', 's1'),+ event('sync-2', '2026-06-15T09:00:50Z', 's1', 'synced'),+ ]+ const { rows: shown, hidden } = collapseGroup(groupActivityRows(rows(events))[0])+ expect(shown.map((row) => (row.kind === 'event' ? [row.event.event, row.count] : null))).toEqual([+ ['synced', 2],+ ['paid', 1],+ ])+ expect(hidden).toBe(4)+ })++ it('shows the first rows of a long group with no custom events', () => {+ const events = ['a', 'b', 'c', 'd', 'e', 'f'].map((id, i) => event(id, `2026-06-15T09:00:0${i}Z`, 's1'))+ const { rows: shown, hidden } = collapseGroup(groupActivityRows(rows(events))[0])+ expect(shown.map((row) => row.key)).toEqual(['a', 'b', 'c', 'd'])+ expect(hidden).toBe(2)+ })++ it('ends a session at the last of its folded events', () => {+ const [group] = groupActivityRows(+ rows([+ event('a', '2026-06-15T09:00:00Z', 's1', 'opened'),+ event('b', '2026-06-15T09:20:00Z', 's1', 'opened'),+ ])+ )+ expect(groupDuration(group)).toBe('20m')+ })+})diff --git a/products/workflows/frontend/Transactional/log/emailActivityGroups.ts b/products/workflows/frontend/Transactional/log/emailActivityGroups.tsnew file mode 100644index 000000000000..a33d9aa19fb5--- /dev/null+++ b/products/workflows/frontend/Transactional/log/emailActivityGroups.ts@@ -0,0 +1,97 @@+import { dayjs } from 'lib/dayjs'+import { humanFriendlyDuration } from 'lib/utils/durations'++import { ACTIVITY_JOIN_MINUTES, ActivityEventRow, ActivityRow, isCustomEvent } from './emailActivity'++export interface ActivityGroup {+ key: string+ /** Null for rows outside any session, which have no replay. */+ sessionId: string | null+ rows: ActivityRow[]+ startAt: string+ endAt: string+ eventCount: number+}++function lastRowAt(row: ActivityRow): string {+ return row.kind === 'event' ? row.lastAt : row.at+}++function toGroup(sessionId: string | null, rows: ActivityRow[]): ActivityGroup {+ const events = rows.filter((row): row is ActivityEventRow => row.kind === 'event')+ return {+ key: `${sessionId ?? 'no-session'}-${rows[0].key}`,+ sessionId,+ rows,+ startAt: rows[0].at,+ endAt: lastRowAt(rows[rows.length - 1]),+ eventCount: events.reduce((total, row) => total + row.count, 0),+ }+}++/** Splits timeline rows at each session, so a session and its replay read as one thing. */+export function groupActivityRows(rows: ActivityRow[]): ActivityGroup[] {+ const groups: ActivityGroup[] = []+ let sessionId: string | null = null+ let current: ActivityRow[] = []+ const flush = (): void => {+ if (current.length) {+ groups.push(toGroup(sessionId, current))+ }+ current = []+ }+ for (const row of rows) {+ const rowSession = row.kind === 'event' ? row.event.sessionId : null+ const last = current[current.length - 1]+ const closeToLast = !!last && dayjs(row.at).diff(dayjs(lastRowAt(last)), 'minute') < ACTIVITY_JOIN_MINUTES+ if (rowSession ? rowSession !== sessionId : !!sessionId && !closeToLast) {+ flush()+ sessionId = rowSession+ }+ current.push(row)+ }+ flush()+ return groups+}++/** "21s", the time between a group's first and last row. */+export function groupDuration(group: ActivityGroup): string {+ return humanFriendlyDuration(Math.max(1, dayjs(group.endAt).diff(dayjs(group.startAt), 'second')), { maxUnits: 2 })+}++/** "8h later", when a noticeable stretch of time separates two groups. */+export function gapBetween(fromAt: string, toAt: string): string | null {+ const seconds = dayjs(toAt).diff(dayjs(fromAt), 'second')+ return seconds >= 60 ? `${humanFriendlyDuration(seconds, { maxUnits: 1 })} later` : null+}++/** The most rows a group shows until the reader opens it. */+const COLLAPSED_GROUP_ROWS = 4++export interface CollapsedGroup {+ rows: ActivityRow[]+ /** How many more rows the group shows when it opens. */+ hidden: number+}++/** What a long group shows at first: its custom events and emails once each, or else its first rows. */+export function collapseGroup(group: ActivityGroup): CollapsedGroup {+ if (group.rows.length <= COLLAPSED_GROUP_ROWS) {+ return { rows: group.rows, hidden: 0 }+ }+ const byName = new Map<string, ActivityRow>()+ for (const row of group.rows) {+ if (row.kind === 'otherEmail') {+ byName.set(row.key, row)+ } else if (isCustomEvent(row.event)) {+ const seen = byName.get(row.event.event)+ byName.set(+ row.event.event,+ seen?.kind === 'event' ? { ...seen, count: seen.count + row.count, lastAt: row.lastAt } : row+ )+ }+ }+ const important = Array.from(byName.values())+ const rows = (important.length ? important : group.rows).slice(0, COLLAPSED_GROUP_ROWS)+ return { rows, hidden: group.rows.length - rows.length }+}diff --git a/products/workflows/frontend/Transactional/log/emailActivityQueries.ts b/products/workflows/frontend/Transactional/log/emailActivityQueries.tsindex bde3a4b722e1..95150cf54718 100644--- a/products/workflows/frontend/Transactional/log/emailActivityQueries.ts+++ b/products/workflows/frontend/Transactional/log/emailActivityQueries.ts@@ -33,6 +33,14 @@ const HIDDEN_EVENTS = ['$feature_view','$feature_interaction','$snapshot',+ // The delivery steps at the top of the page already show the email's own progress.+ '$workflows_email_sent',+ '$workflows_email_failed',+ '$workflows_email_delivered',+ '$workflows_email_opened',+ '$workflows_email_link_clicked',+ '$workflows_email_bounced',+ '$workflows_email_blocked',]const QUERY_TAGS = { productKey: 'workflows', scene: 'TransactionalEmailLogEntry' }@@ -71,7 +79,7 @@ LIMIT 1`,}}-export async function fetchPersonActivity(personId: string, sentAt: string): Promise<PersonActivity> {+export async function fetchPersonActivity(distinctId: string, sentAt: string): Promise<PersonActivity> {const sent = dayjs(sentAt)const from = sent.subtract(ACTIVITY_WINDOW_DAYS, 'day')const to = sent.add(ACTIVITY_WINDOW_DAYS, 'day')@@ -79,7 +87,8 @@ export async function fetchPersonActivity(personId: string, sentAt: string): Proconst [before, after] = await Promise.all([api.queryHogQL(hogql`SELECT ${hogql.raw(columns)} FROM events-WHERE person_id = ${personId} AND timestamp >= ${from} AND timestamp < ${sent}+WHERE person_id IN (SELECT person_id FROM person_distinct_ids WHERE distinct_id = ${distinctId})+AND timestamp >= ${from} AND timestamp < ${sent}AND event NOT IN ${HIDDEN_EVENTS}ORDER BY timestamp DESCLIMIT ${ACTIVITY_BEFORE_LIMIT + 1}`,@@ -87,7 +96,8 @@ LIMIT ${ACTIVITY_BEFORE_LIMIT + 1}`,),api.queryHogQL(hogql`SELECT ${hogql.raw(columns)} FROM events-WHERE person_id = ${personId} AND timestamp >= ${sent} AND timestamp <= ${to}+WHERE person_id IN (SELECT person_id FROM person_distinct_ids WHERE distinct_id = ${distinctId})+AND timestamp >= ${sent} AND timestamp <= ${to}AND event NOT IN ${HIDDEN_EVENTS}ORDER BY timestamp ASCLIMIT ${ACTIVITY_AFTER_LIMIT + 1}`,diff --git a/products/workflows/frontend/Transactional/log/transactionalEmailLogEntryLogic.ts b/products/workflows/frontend/Transactional/log/transactionalEmailLogEntryLogic.tsindex 945697073f3e..1d368f98a890 100644--- a/products/workflows/frontend/Transactional/log/transactionalEmailLogEntryLogic.ts+++ b/products/workflows/frontend/Transactional/log/transactionalEmailLogEntryLogic.ts@@ -27,6 +27,7 @@ export interface transactionalEmailLogEntryLogicValues {activity: PersonActivity | nullactivityFailed: booleanactivityLoading: boolean+ afterExpanded: booleanbeforeExpanded: booleanbreadcrumbs: Breadcrumb[]email: TransactionalEmailLogDetailApi | null | undefined@@ -42,8 +43,8 @@ export interface transactionalEmailLogEntryLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface transactionalEmailLogEntryLogicActions {- loadActivity: ({ personId, sentAt }: { personId: string; sentAt: string }) => {- personId: string+ loadActivity: ({ distinctId, sentAt }: { distinctId: string; sentAt: string }) => {+ distinctId: stringsentAt: string}loadActivityFailure: (@@ -56,13 +57,13 @@ export interface transactionalEmailLogEntryLogicActions {loadActivitySuccess: (activity: PersonActivity,payload?: {- personId: string+ distinctId: stringsentAt: string}) => {activity: PersonActivitypayload?: {- personId: string+ distinctId: stringsentAt: string}}@@ -111,6 +112,9 @@ export interface transactionalEmailLogEntryLogicActions {person: ActivityPerson | nullpayload?: string}+ showAllAfter: () => {+ value: true+ }showAllBefore: () => {value: true}@@ -146,9 +150,11 @@ export const transactionalEmailLogEntryLogic = kea<transactionalEmailLogEntryLogconnect(() => ({ values: [projectLogic, ['currentProjectId']] })),actions({showAllBefore: true,+ showAllAfter: true,}),reducers({beforeExpanded: [false, { showAllBefore: () => true }],+ afterExpanded: [false, { showAllAfter: () => true }],personFailed: [false,{@@ -226,8 +232,8 @@ export const transactionalEmailLogEntryLogic = kea<transactionalEmailLogEntryLogactivity: [null as PersonActivity | null,{- loadActivity: async ({ personId, sentAt }: { personId: string; sentAt: string }) =>- await fetchPersonActivity(personId, sentAt),+ loadActivity: async ({ distinctId, sentAt }: { distinctId: string; sentAt: string }) =>+ await fetchPersonActivity(distinctId, sentAt),},],})),@@ -251,15 +257,11 @@ export const transactionalEmailLogEntryLogic = kea<transactionalEmailLogEntryLog],],}),- listeners(({ actions, values }) => ({- loadPersonSuccess: ({ person }) => {- if (person && values.email) {- actions.loadActivity({ personId: person.id, sentAt: emailSentAt(values.email) })- }- },+ listeners(({ actions }) => ({loadEmailSuccess: ({ email }) => {if (email?.distinct_id) {actions.loadPerson(email.distinct_id)+ actions.loadActivity({ distinctId: email.distinct_id, sentAt: emailSentAt(email) })}if (email?.recipient) {actions.loadOtherEmails(email)