Skip to content

: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.

feat(workflows): add an experimental overview tab to active workflows (#116215)

Daniel Marchuk57a6ee1224a0
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 95d12135bcdd..2cf84ba38faa 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -641,6 +641,7 @@ export const FEATURE_FLAGS = {
WORKFLOWS_INTERNAL_EVENT_FILTERS: 'workflows-internal-event-filters', // owner: @haven #team-workflows
WORKFLOWS_ISP_SENDING_HEALTH: 'workflows-isp-sending-health', // owner: #team-workflows
WORKFLOWS_LINEAR_VIEW: 'workflows-linear-view', // owner: #team-workflows
+ WORKFLOWS_OVERVIEW_TAB: 'workflows-overview-tab', // owner: @dmarchuk #team-workflows, experimental Overview tab on a workflow
WORKFLOWS_PUSH_NOTIFICATIONS: 'workflows-push-notifications', // owner: #team-workflows
WORKFLOWS_TRIGGER_VOLUME_ESTIMATE: 'workflows-trigger-volume-estimate', // owner: @mayteio #team-workflows
XAA_AUTHENTICATION: 'xaa-authentication', // owner: @reecejones #team-platform-features
diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.py
index 2e4aa792c322..2f89e4f8e5d3 100644
--- a/products/workflows/backend/presentation/views/hog_flow.py
+++ b/products/workflows/backend/presentation/views/hog_flow.py
@@ -3552,6 +3552,22 @@ class HogFlowPublishImpactMoveTargetSerializer(serializers.Serializer):
name = serializers.CharField(help_text="Name of the surviving step.")
+class HogFlowInFlightSerializer(serializers.Serializer):
+ count = serializers.IntegerField(
+ allow_null=True,
+ help_text="About how many runs are in flight (parked on a delay or wait, or executing). Null when the count is unavailable.",
+ )
+ by_action = serializers.DictField(
+ child=serializers.IntegerField(),
+ allow_null=True,
+ help_text="In-flight runs keyed by the id of the step they are on. Null when the count is unavailable.",
+ )
+ position_unknown = serializers.IntegerField(
+ allow_null=True,
+ help_text="In-flight runs whose current step could not be read. Null when the count is unavailable.",
+ )
+
+
class HogFlowPublishImpactDeletedStepSerializer(serializers.Serializer):
action_id = serializers.CharField(help_text="Id of the step this publish deletes.")
name = serializers.CharField(help_text="Name of the deleted step.")
@@ -4173,6 +4189,7 @@ class DraftExistsError(exceptions.APIException):
# and it signs the exact draft it previewed — so a valid token proves the caller saw the impact
# summary for the draft being published. Short max-age keeps the previewed counts fresh.
PUBLISH_CONFIRM_TOKEN_MAX_AGE = timedelta(minutes=15)
+IN_FLIGHT_CACHE_SECONDS = 30
_PUBLISH_CONFIRM_SALT = "hogflow-publish"
@@ -4309,6 +4326,7 @@ class HogFlowViewSet(
"revision_detail",
"proposal_detail",
"proposal_outcome",
+ "in_flight",
]
scope_object_write_actions = [
"create",
@@ -5260,6 +5278,19 @@ class HogFlowViewSet(
return Response(self.get_serializer(instance).data)
+ @extend_schema(responses={200: HogFlowInFlightSerializer})
+ @action(detail=True, methods=["GET"], url_path="in_flight", filter_backends=[], pagination_class=None)
+ def in_flight(self, request: Request, *args, **kwargs):
+ instance = self.get_object()
+ cache_key = f"hog_flow_in_flight:{self.team_id}:{instance.id}"
+ counts = cache.get(cache_key)
+ if counts is None:
+ counts = self._get_in_flight_counts(instance)
+ if counts is not None:
+ cache.set(cache_key, counts, IN_FLIGHT_CACHE_SECONDS)
+ # An unreachable counting service yields nulls, not an error. A failed count is not cached.
+ return Response(HogFlowInFlightSerializer(counts or dict.fromkeys(HogFlowInFlightSerializer().fields)).data)
+
@extend_schema(responses={200: HogFlowRevisionBasicSerializer(many=True)})
# filter_backends=[]: don't inherit the viewset's HogFlow filterset — its fields would be
# advertised as query params in the generated contract but silently ignored here.
diff --git a/products/workflows/backend/tests/api/test_hog_flow.py b/products/workflows/backend/tests/api/test_hog_flow.py
index a26d90f9ff17..936f9d690cc4 100644
--- a/products/workflows/backend/tests/api/test_hog_flow.py
+++ b/products/workflows/backend/tests/api/test_hog_flow.py
@@ -5702,6 +5702,22 @@ class TestHogFlowAPI(APIBaseTest):
)
assert response.status_code == 200, response.json()
+ def test_in_flight_allowed_with_hog_flow_read_key(self):
+ flow_id = self._create_flow()
+ key = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="hog_flow read", user=self.user, secure_value=hash_key_value(key), scopes=["hog_flow:read"]
+ )
+ with patch(
+ "products.workflows.backend.presentation.views.hog_flow.get_hog_flow_in_flight_count",
+ return_value=MagicMock(status_code=200, json=lambda: {"count": 3, "by_action": {"action_1": 3}}),
+ ):
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/in_flight",
+ headers={"authorization": f"Bearer {key}"},
+ )
+ assert response.status_code == 200, response.json()
+
def test_bulk_delete_archived_workflows(self):
ids = [self._create_flow(name=f"Flow {i}") for i in range(3)]
for fid in ids:
diff --git a/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.tsx b/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.tsx
index fbf2922c55e1..7634cf5c4e0b 100644
--- a/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.tsx
+++ b/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.tsx
@@ -15,6 +15,7 @@ import type {
WorkflowEmailSendingRatesApi,
} from 'products/workflows/frontend/generated/api.schemas'
+import { RATE_LEVEL_TAG, RATE_THRESHOLDS, classifyRate, minimumVolumeToClassify } from './emailRateLevels'
import { workflowsReputationLogic } from './workflowsReputationLogic'
function formatRate(rate: number): string {
@@ -28,47 +29,6 @@ const HEALTH_TAG: Record<AwsTenantReputationHealthEnumApi, { label: string; type
suspended: { label: 'Suspended', type: 'danger' },
}
-// Per-workflow rate classification. Reserved words like "Warning" / "Critical" belong to the
-// tenant-level AWS verdict (HEALTH_TAG above) — these coarser buckets are just a triage aid for
-// spotting which workflows are pulling the project's numbers in the wrong direction.
-//
-// Thresholds mirror SES's account-level reputation dashboard warning lines (bounce: 5% review /
-// 10% pause; complaint: 0.1% review / 0.5% pause), deliberately conservative early warnings.
-// Actual tenant enforcement (the Standard reputation policy) pauses much higher — high-severity
-// findings at >15% bounce / >1% complaint — so a "high" rate here means "fix this now", not
-// "sending is about to stop". Sources:
-// https://docs.aws.amazon.com/ses/latest/dg/reputationdashboardmessages.html (dashboard lines)
-// https://aws.amazon.com/blogs/messaging-and-targeting/implement-tenants-in-your-amazon-ses-environment-part-3-implementation-guide/ (tenant policy lines)
-const RATE_THRESHOLDS = {
- bounce: { elevated: 0.03, high: 0.05 },
- complaint: { elevated: 0.001, high: 0.005 },
-} as const
-
-type RateLevel = 'healthy' | 'elevated' | 'high'
-
-// Below this much volume one event on its own clears the elevated line, so a tag would be
-// reporting noise: one bounce in 20 sends reads as 5%.
-function minimumVolumeToClassify(kind: 'bounce' | 'complaint'): number {
- return Math.ceil(1 / RATE_THRESHOLDS[kind].elevated)
-}
-
-function classifyRate(rate: number, kind: 'bounce' | 'complaint'): RateLevel {
- const thresholds = RATE_THRESHOLDS[kind]
- if (rate >= thresholds.high) {
- return 'high'
- }
- if (rate >= thresholds.elevated) {
- return 'elevated'
- }
- return 'healthy'
-}
-
-const RATE_LEVEL_TAG: Record<RateLevel, { label: string; type: LemonTagType }> = {
- healthy: { label: 'Healthy', type: 'success' },
- elevated: { label: 'Elevated', type: 'warning' },
- high: { label: 'High', type: 'danger' },
-}
-
// AWS returning nothing for a metric is not the same as the metric being zero, and a 0.00% spam
// complaint rate with a green tag is the most misleading thing this table could show. The API names
// the rates it could not load, and those say so instead.
diff --git a/products/workflows/frontend/Workflows/Reputation/emailRateLevels.ts b/products/workflows/frontend/Workflows/Reputation/emailRateLevels.ts
new file mode 100644
index 000000000000..c96ab46f27a4
--- /dev/null
+++ b/products/workflows/frontend/Workflows/Reputation/emailRateLevels.ts
@@ -0,0 +1,42 @@
+import type { LemonTagType } from '@posthog/lemon-ui'
+
+// Per-workflow rate classification. Reserved words like "Warning" / "Critical" belong to the
+// tenant-level AWS verdict (the reputation page's HEALTH_TAG) — these coarser buckets are just a triage aid for
+// spotting which workflows are pulling the project's numbers in the wrong direction.
+//
+// Thresholds mirror SES's account-level reputation dashboard warning lines (bounce: 5% review /
+// 10% pause; complaint: 0.1% review / 0.5% pause), deliberately conservative early warnings.
+// Actual tenant enforcement (the Standard reputation policy) pauses much higher — high-severity
+// findings at >15% bounce / >1% complaint — so a "high" rate here means "fix this now", not
+// "sending is about to stop". Sources:
+// https://docs.aws.amazon.com/ses/latest/dg/reputationdashboardmessages.html (dashboard lines)
+// https://aws.amazon.com/blogs/messaging-and-targeting/implement-tenants-in-your-amazon-ses-environment-part-3-implementation-guide/ (tenant policy lines)
+export const RATE_THRESHOLDS = {
+ bounce: { elevated: 0.03, high: 0.05 },
+ complaint: { elevated: 0.001, high: 0.005 },
+} as const
+
+export type RateLevel = 'healthy' | 'elevated' | 'high'
+
+// Below this much volume one event on its own clears the elevated line, so a tag would be
+// reporting noise: one bounce in 20 sends reads as 5%.
+export function minimumVolumeToClassify(kind: 'bounce' | 'complaint'): number {
+ return Math.ceil(1 / RATE_THRESHOLDS[kind].elevated)
+}
+
+export function classifyRate(rate: number, kind: 'bounce' | 'complaint'): RateLevel {
+ const thresholds = RATE_THRESHOLDS[kind]
+ if (rate >= thresholds.high) {
+ return 'high'
+ }
+ if (rate >= thresholds.elevated) {
+ return 'elevated'
+ }
+ return 'healthy'
+}
+
+export const RATE_LEVEL_TAG: Record<RateLevel, { label: string; type: LemonTagType }> = {
+ healthy: { label: 'Healthy', type: 'success' },
+ elevated: { label: 'Elevated', type: 'warning' },
+ high: { label: 'High', type: 'danger' },
+}
diff --git a/products/workflows/frontend/Workflows/WorkflowMetricCard.tsx b/products/workflows/frontend/Workflows/WorkflowMetricCard.tsx
index 6ca5da2d52f7..89d8a85806f5 100644
--- a/products/workflows/frontend/Workflows/WorkflowMetricCard.tsx
+++ b/products/workflows/frontend/Workflows/WorkflowMetricCard.tsx
@@ -78,6 +78,7 @@ export interface WorkflowMetricCardProps {
footer?: ReactNode
/** Shorter card, so a page with tables below it does not push them off screen. */
compact?: boolean
+ className?: string
}
// Collapse a response into the numbers the tile reads (per-index sums plus the grand total). A
@@ -108,6 +109,7 @@ export function WorkflowMetricCard({
onClickTooltip,
footer,
compact,
+ className,
}: WorkflowMetricCardProps): JSX.Element {
const theme = useChartTheme()
@@ -164,13 +166,14 @@ export function WorkflowMetricCard({
const cardClassName = cn(
CARD_CHROME,
+ className,
onClick &&
'cursor-pointer transition-colors hover:bg-surface-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'
)
if (loading) {
return (
- <div className={CARD_CHROME}>
+ <div className={cn(CARD_CHROME, className)}>
<div className="flex flex-col px-3">
<Skeleton className="h-4 w-24" />
<Skeleton className="mt-3 h-9 w-32" />
diff --git a/products/workflows/frontend/Workflows/WorkflowMetrics.tsx b/products/workflows/frontend/Workflows/WorkflowMetrics.tsx
index 24bb3eea687a..0f43b8007cb9 100644
--- a/products/workflows/frontend/Workflows/WorkflowMetrics.tsx
+++ b/products/workflows/frontend/Workflows/WorkflowMetrics.tsx
@@ -19,6 +19,7 @@ import { batchWorkflowJobsLogic } from './batchWorkflowJobsLogic'
import { EmailMetricsSummary } from './EmailMetricsSummary'
import { getHogFlowStep } from './hogflows/steps/HogFlowSteps'
import { HogFlowBatchJob } from './hogflows/types'
+import { metricsRangeFromSearchParams, metricsRangeSearchParams } from './metricsDrillParams'
import { PushMetricsSummary } from './PushMetricsSummary'
import { WorkflowLogicProps, workflowLogic } from './workflowLogic'
import { WorkflowMetricCard } from './WorkflowMetricCard'
@@ -59,7 +60,15 @@ export const WORKFLOW_METRICS_INFO: Record<string, { name: string; description:
function WorkflowRunMetrics(props: WorkflowLogicProps): JSX.Element {
const logicKey = `hog-flow-metrics-${props.id}`
const { searchParams } = useValues(router)
- const { workflow, hogFunctionTemplatesById } = useValues(workflowLogic)
+ const { workflow, originalWorkflow, hogFunctionTemplatesById } = useValues(workflowLogic)
+ // A step a staged draft removes still has live metrics, and the overview links to it.
+ const knownActions = useMemo(
+ () => [
+ ...workflow.actions,
+ ...(originalWorkflow?.actions ?? []).filter((live) => !workflow.actions.some((a) => a.id === live.id)),
+ ],
+ [workflow.actions, originalWorkflow?.actions]
+ )
// Seed the drilled-in step from ?action= so a refreshed or shared metrics link restores it, but
// only honor a value that points at a real step — a stale/deleted/mistyped id would otherwise
@@ -68,8 +77,7 @@ function WorkflowRunMetrics(props: WorkflowLogicProps): JSX.Element {
// overview first. Later changes (clicks, back/forward) are synced by workflowSceneLogic's urlToAction.
const requestedAction = (searchParams.action as string) || undefined
const instanceId =
- requestedAction &&
- (!workflow.actions.length || workflow.actions.some((action) => action.id === requestedAction))
+ requestedAction && (!knownActions.length || knownActions.some((action) => action.id === requestedAction))
? requestedAction
: undefined
@@ -77,6 +85,7 @@ function WorkflowRunMetrics(props: WorkflowLogicProps): JSX.Element {
logicKey,
loadOnChanges: true,
loadOnMount: true,
+ defaultParams: metricsRangeFromSearchParams(searchParams),
forceParams: {
appSource: 'hog_flow',
appSourceId: props.id,
@@ -88,7 +97,7 @@ function WorkflowRunMetrics(props: WorkflowLogicProps): JSX.Element {
const { appMetricsTrendsLoading, appMetricsTrends, getSingleTrendSeries, params, getDateRangeAbsolute } =
useValues(logic)
- const selectedAction = workflow.actions.find((action) => action.id === params.instanceId)
+ const selectedAction = knownActions.find((action) => action.id === params.instanceId)
const modifiedAppMetricsTrends = useMemo(
() =>
@@ -114,7 +123,7 @@ function WorkflowRunMetrics(props: WorkflowLogicProps): JSX.Element {
{
// A titled section makes it obvious you can drill into a single step's metrics.
title: 'Per step',
- options: workflow.actions
+ options: knownActions
.filter((action) => action.id !== 'trigger_node')
.map((action) => {
const Step = getHogFlowStep(action, hogFunctionTemplatesById)
@@ -126,7 +135,7 @@ function WorkflowRunMetrics(props: WorkflowLogicProps): JSX.Element {
}),
},
],
- [workflow.actions, hogFunctionTemplatesById]
+ [knownActions, hogFunctionTemplatesById]
)
// Drill an email metric into the invocations behind it over the current window.
@@ -151,8 +160,11 @@ function WorkflowRunMetrics(props: WorkflowLogicProps): JSX.Element {
if (!props.id) {
return
}
- const { action: _prev, ...rest } = searchParams
- router.actions.push(urls.workflow(props.id, 'metrics'), actionId ? { ...rest, action: actionId } : rest)
+ const { action: _prev, date_from: _from, date_to: _to, interval: _interval, ...rest } = searchParams
+ // A range in the URL came from a drill link; replace it with the range picked since, or urlToAction restores the old one.
+ const hadRange = _from !== undefined || _to !== undefined || _interval !== undefined
+ const next = { ...rest, ...(hadRange ? metricsRangeSearchParams(params) : {}) }
+ router.actions.push(urls.workflow(props.id, 'metrics'), actionId ? { ...next, action: actionId } : next)
}
return (
@@ -184,6 +196,7 @@ function WorkflowRunMetrics(props: WorkflowLogicProps): JSX.Element {
<WorkflowMetricsSummary
logicKey={logicKey}
id={props.id ?? ''}
+ defaultRange={{ dateFrom: params.dateFrom, dateTo: params.dateTo, interval: params.interval }}
onSelectAction={(actionId) => selectMetricsAction(actionId)}
onMetricClick={onEmailMetricClick}
/>
@@ -256,12 +269,14 @@ function BatchJobMetrics({ job }: { job: HogFlowBatchJob }): JSX.Element {
},
})
- const { workflow, hogFunctionTemplatesById } = useValues(workflowLogic)
+ const { workflow, originalWorkflow, hogFunctionTemplatesById } = useValues(workflowLogic)
+ // A step a staged draft removes still has live metrics, and the overview links to it.
+ const knownActions = [...workflow.actions, ...(originalWorkflow?.actions ?? [])]
const { appMetricsTrendsLoading, appMetricsTrends, getSingleTrendSeries, params } = useValues(logic)
const { setParams } = useActions(logic)
- const selectedAction = workflow.actions.find((action) => action.id === params.instanceId)
+ const selectedAction = knownActions.find((action) => action.id === params.instanceId)
const modifiedAppMetricsTrends = useMemo(
() =>
diff --git a/products/workflows/frontend/Workflows/WorkflowScene.tsx b/products/workflows/frontend/Workflows/WorkflowScene.tsx
index 353c542b15eb..4d942cefc57c 100644
--- a/products/workflows/frontend/Workflows/WorkflowScene.tsx
+++ b/products/workflows/frontend/Workflows/WorkflowScene.tsx
@@ -7,8 +7,10 @@ import { SpinnerOverlay } from '@posthog/lemon-ui'
import { ActivityLog } from 'lib/components/ActivityLog/ActivityLog'
import { NotFound } from 'lib/components/NotFound'
+import { FEATURE_FLAGS } from 'lib/constants'
import { useDebouncedValue } from 'lib/hooks/useDebouncedValue'
import { LemonTab, LemonTabs } from 'lib/lemon-ui/LemonTabs'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
import { AI_FIRST_COMPOSER_OVERRIDE } from 'scenes/max/aiFirstCreate/aiFirstMode'
import { sceneAgentPanelLogic } from 'scenes/max/sceneAgentPanelLogic'
@@ -26,6 +28,7 @@ import { EMAIL_PREFILL_PARAM } from '../MessageAudience/messageDrafts'
import { batchWorkflowJobsLogic } from './batchWorkflowJobsLogic'
import { NewWorkflowAgent } from './NewWorkflowAgent'
import { newWorkflowLogic } from './newWorkflowLogic'
+import { WorkflowOverview } from './overview/WorkflowOverview'
import { WorkflowSuggestions } from './suggestions/WorkflowSuggestions'
import { workflowSuggestionsAvailabilityLogic } from './suggestions/workflowSuggestionsAvailabilityLogic'
import { WorkflowSuggestionsNotice } from './suggestions/WorkflowSuggestionsNotice'
@@ -110,6 +113,8 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {
useMemo(() => ({ workflow, id: workflowSceneProps.id ?? 'new' }), [workflow, workflowSceneProps.id]),
500
)
+ const { featureFlags } = useValues(featureFlagLogic)
+ const overviewTabEnabled = !!featureFlags[FEATURE_FLAGS.WORKFLOWS_OVERVIEW_TAB]
const { suggestionsAvailable } = useValues(workflowSuggestionsAvailabilityLogic)
const isSavedWorkflow = !!props.id && props.id !== 'new'
const { sceneIntegrationEnabled } = useValues(sceneAgentPanelLogic)
@@ -170,6 +175,14 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {
}
const tabs: (LemonTab<WorkflowTab> | null)[] = [
+ // Batch workflows report per run, so a rolling overview does not fit them.
+ overviewTabEnabled && originalWorkflow.trigger?.type !== 'batch' && originalWorkflow.status === 'active'
+ ? {
+ label: 'Overview',
+ key: 'overview',
+ content: <WorkflowOverview id={workflowSceneProps.id!} />,
+ }
+ : null,
{
label: 'Workflow',
key: 'workflow',
diff --git a/products/workflows/frontend/Workflows/WorkflowsTable.tsx b/products/workflows/frontend/Workflows/WorkflowsTable.tsx
index f5e1438e3c74..c5f2c62563be 100644
--- a/products/workflows/frontend/Workflows/WorkflowsTable.tsx
+++ b/products/workflows/frontend/Workflows/WorkflowsTable.tsx
@@ -15,6 +15,7 @@ import {
import { AccessControlAction } from 'lib/components/AccessControlAction'
import { AppMetricsSparkline } from 'lib/components/AppMetrics/AppMetricsSparkline'
import { MemberSelect } from 'lib/components/MemberSelect'
+import { FEATURE_FLAGS } from 'lib/constants'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { More } from 'lib/lemon-ui/LemonButton/More'
@@ -22,6 +23,7 @@ import { LemonTable, LemonTableColumn, LemonTableColumns } from 'lib/lemon-ui/Le
import { updatedAtColumn } from 'lib/lemon-ui/LemonTable/columnUtils'
import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { capitalizeFirstLetter } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
@@ -115,6 +117,8 @@ function WorkflowActionsSummary({ workflow }: { workflow: HogFlow }): JSX.Elemen
}
export function WorkflowsTable(): JSX.Element {
+ const { featureFlags } = useValues(featureFlagLogic)
+ const overviewTabEnabled = !!featureFlags[FEATURE_FLAGS.WORKFLOWS_OVERVIEW_TAB]
const { suggestionsAvailable } = useValues(workflowSuggestionsAvailabilityLogic)
const logic = workflowsLogic()
const {
@@ -201,7 +205,12 @@ export function WorkflowsTable(): JSX.Element {
</Tooltip>
) : (
<LemonTableLink
- to={urls.workflow(item.id, 'workflow')}
+ to={urls.workflow(
+ item.id,
+ overviewTabEnabled && item.status === 'active' && item.trigger?.type !== 'batch'
+ ? 'overview'
+ : 'workflow'
+ )}
title={
<span className="flex items-center gap-2 flex-wrap">
{item.name}
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx
index be6facd878c2..b86077c75b1f 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx
@@ -870,7 +870,7 @@ function StepTriggerConfigurationTrackingPixel({
)
}
-const TTL_OPTIONS = [
+export const TTL_OPTIONS = [
{ value: null, label: 'indefinitely' },
{ value: 5 * 60, label: '5 minutes' },
{ value: 15 * 60, label: '15 minutes' },
diff --git a/products/workflows/frontend/Workflows/metricsDrillParams.ts b/products/workflows/frontend/Workflows/metricsDrillParams.ts
new file mode 100644
index 000000000000..91037cead6e1
--- /dev/null
+++ b/products/workflows/frontend/Workflows/metricsDrillParams.ts
@@ -0,0 +1,45 @@
+import type { AppMetricsCommonParams } from 'lib/components/AppMetrics/appMetricsLogic'
+import { urls } from 'scenes/urls'
+
+type MetricsRange = Pick<AppMetricsCommonParams, 'dateFrom' | 'dateTo' | 'interval'>
+
+const INTERVALS: NonNullable<AppMetricsCommonParams['interval']>[] = ['day', 'hour', 'minute']
+
+export function metricsRangeSearchParams(range: MetricsRange): Record<string, string> {
+ const search: Record<string, string> = {}
+ if (range.dateFrom) {
+ search.date_from = range.dateFrom
+ }
+ if (range.dateTo) {
+ search.date_to = range.dateTo
+ }
+ if (range.interval) {
+ search.interval = range.interval
+ }
+ return search
+}
+
+/** Links to one step on the Metrics tab, keeping the date range the link was clicked from. */
+export function metricsStepUrl(id: string, actionId: string, range: MetricsRange): string {
+ const search = new URLSearchParams({ action: actionId, ...metricsRangeSearchParams(range) })
+ return `${urls.workflow(id, 'metrics')}?${search.toString()}`
+}
+
+/** Reads the date range a Metrics tab link carries. Values that are not strings or not known intervals are ignored. */
+export function metricsRangeFromSearchParams(searchParams: Record<string, unknown>): MetricsRange {
+ const range: MetricsRange = {}
+ if (typeof searchParams.date_from === 'string') {
+ range.dateFrom = searchParams.date_from
+ }
+ if (typeof searchParams.date_to === 'string') {
+ range.dateTo = searchParams.date_to
+ } else if (range.dateFrom) {
+ // A rolling range has no end date, so a stale one from an earlier URL must not survive the merge.
+ range.dateTo = undefined
+ }
+ const interval = INTERVALS.find((value) => value === searchParams.interval)
+ if (interval) {
+ range.interval = interval
+ }
+ return range
+}
diff --git a/products/workflows/frontend/Workflows/overview/WorkflowMessageLeaderboard.tsx b/products/workflows/frontend/Workflows/overview/WorkflowMessageLeaderboard.tsx
new file mode 100644
index 000000000000..9f7adbe6bc03
--- /dev/null
+++ b/products/workflows/frontend/Workflows/overview/WorkflowMessageLeaderboard.tsx
@@ -0,0 +1,207 @@
+import { useActions, useValues } from 'kea'
+import { useMemo, useState } from 'react'
+
+import { IconLetter, IconNotification } from '@posthog/icons'
+import { LemonButton, LemonSegmentedButton, LemonTable, LemonTableColumns, Link } from '@posthog/lemon-ui'
+
+import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'
+
+import { metricsStepUrl } from '../metricsDrillParams'
+import { workflowMetricsSummaryLogic } from '../workflowMetricsSummaryLogic'
+
+type LeaderboardMetric = 'sent' | 'opened' | 'clicked'
+
+type LeaderboardRow = {
+ id: string
+ name: string
+ channel: 'email' | 'push'
+ sent: number
+ opened: number
+ // Push has no link tracking, so it drops out of the clicked ranking instead of ranking as zero.
+ clicked: number | null
+ // Opens and clicks only happen on tracked sends, so rates read against this, not `sent`.
+ engagementBase: number
+ // A step deleted from the workflow still has metrics in the range, but no step to open.
+ removed?: boolean
+}
+
+const METRIC_OPTIONS: { value: LeaderboardMetric; label: string }[] = [
+ { value: 'sent', label: 'Sent' },
+ { value: 'opened', label: 'Opened' },
+ { value: 'clicked', label: 'Clicked' },
+]
+
+export function WorkflowMessageLeaderboard({ id, logicKey }: { id: string; logicKey: string }): JSX.Element {
+ const summaryLogic = workflowMetricsSummaryLogic({ logicKey, id, overview: true })
+ const {
+ emailMetricsRows,
+ pushMetricsRows,
+ emailTotalsByActionIdLoading,
+ pushTotalsByActionIdLoading,
+ params,
+ messageTotalsFailed,
+ emailTotalsByActionId,
+ pushTotalsByActionId,
+ } = useValues(summaryLogic)
+ const { loadEmailTotals, loadPushTotals } = useActions(summaryLogic)
+ const [metric, setMetric] = useState<LeaderboardMetric>('sent')
+
+ const rows = useMemo<LeaderboardRow[]>(() => {
+ const all: LeaderboardRow[] = [
+ ...emailMetricsRows.map((row) => ({
+ id: row.id,
+ name: row.email,
+ channel: 'email' as const,
+ sent: row.sent,
+ opened: row.opened,
+ clicked: row.linkClicked,
+ engagementBase: row.trackedSends,
+ })),
+ ...pushMetricsRows.map((row) => ({
+ id: row.id,
+ name: row.push,
+ channel: 'push' as const,
+ sent: row.sent,
+ opened: row.opened,
+ clicked: null,
+ engagementBase: row.sent,
+ })),
+ ]
+ const known = new Set(all.map((row) => row.id))
+ for (const [actionId, totals] of Object.entries(emailTotalsByActionId)) {
+ const emailActivity =
+ (totals.email_sent ?? 0) + (totals.email_opened ?? 0) + (totals.email_link_clicked ?? 0)
+ if (!known.has(actionId) && emailActivity > 0) {
+ const sent = totals.email_sent ?? 0
+ all.push({
+ id: actionId,
+ name: 'Removed email',
+ channel: 'email',
+ sent,
+ opened: totals.email_opened ?? 0,
+ clicked: totals.email_link_clicked ?? 0,
+ engagementBase: Math.max(0, sent - (totals.email_untracked ?? 0)),
+ removed: true,
+ })
+ }
+ }
+ for (const [actionId, totals] of Object.entries(pushTotalsByActionId)) {
+ if (!known.has(actionId) && (totals.push_sent ?? 0) + (totals.push_opened ?? 0) > 0) {
+ all.push({
+ id: actionId,
+ name: 'Removed push notification',
+ channel: 'push',
+ sent: totals.push_sent ?? 0,
+ opened: totals.push_opened ?? 0,
+ clicked: null,
+ engagementBase: totals.push_sent ?? 0,
+ removed: true,
+ })
+ }
+ }
+ return all.filter((row) => row[metric] !== null).sort((a, b) => (b[metric] ?? 0) - (a[metric] ?? 0))
+ }, [emailMetricsRows, pushMetricsRows, emailTotalsByActionId, pushTotalsByActionId, metric])
+
+ const columns: LemonTableColumns<LeaderboardRow> = [
+ {
+ key: 'rank',
+ width: 0,
+ render: (_, __, index) => <span className="text-muted">{index + 1}</span>,
+ },
+ {
+ title: 'Message',
+ key: 'name',
+ render: (_, row) => {
+ const label = (
+ <>
+ <span className="flex text-base text-secondary">
+ {row.channel === 'email' ? <IconLetter /> : <IconNotification />}
+ </span>
+ <span>{row.name}</span>
+ </>
+ )
+ return row.removed ? (
+ <span className="inline-flex items-center gap-1.5 font-medium text-muted">{label}</span>
+ ) : (
+ <Link
+ to={metricsStepUrl(id, row.id, params)}
+ className="inline-flex items-center gap-1.5 font-medium"
+ data-attr="workflow-overview-leaderboard-message"
+ >
+ {label}
+ </Link>
+ )
+ },
+ },
+ {
+ title: METRIC_OPTIONS.find((o) => o.value === metric)?.label,
+ key: 'value',
+ align: 'right',
+ render: (_, row) => {
+ const value = row[metric] ?? 0
+ return (
+ <span className="whitespace-nowrap">
+ <span translate="no">{humanFriendlyNumber(value)}</span>
+ {metric !== 'sent' ? (
+ <span className="text-muted" translate="no">
+ {` (${row.engagementBase > 0 ? percentage(value / row.engagementBase, 1) : '-'})`}
+ </span>
+ ) : null}
+ </span>
+ )
+ },
+ },
+ ]
+
+ const loading = emailTotalsByActionIdLoading || pushTotalsByActionIdLoading
+ const hasMessages = rows.length > 0 || emailMetricsRows.length > 0 || pushMetricsRows.length > 0
+
+ return (
+ <div
+ className="flex flex-col gap-3 rounded border bg-surface-primary p-4"
+ data-attr="workflow-overview-leaderboard"
+ >
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <h3 className="mb-0 text-base font-semibold">Message leaderboard</h3>
+ {hasMessages ? (
+ <LemonSegmentedButton
+ size="xsmall"
+ value={metric}
+ onChange={setMetric}
+ options={METRIC_OPTIONS}
+ data-attr="workflow-overview-leaderboard-metric"
+ />
+ ) : null}
+ </div>
+ {messageTotalsFailed ? (
+ <span className="flex flex-wrap items-center gap-2 text-sm text-muted">
+ Couldn't load message counts.
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ onClick={() => {
+ loadEmailTotals({})
+ loadPushTotals({})
+ }}
+ loading={loading}
+ data-attr="workflow-overview-leaderboard-retry"
+ >
+ Try again
+ </LemonButton>
+ </span>
+ ) : !loading && !hasMessages ? (
+ <span className="text-sm text-muted">This workflow has no email or push steps yet.</span>
+ ) : (
+ <LemonTable
+ columns={columns}
+ dataSource={rows}
+ loading={loading}
+ rowKey="id"
+ size="small"
+ embedded
+ emptyState="No push steps track clicks. Pick Sent or Opened to rank them."
+ />
+ )}
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/overview/WorkflowOverview.tsx b/products/workflows/frontend/Workflows/overview/WorkflowOverview.tsx
new file mode 100644
index 000000000000..ca458d69cdff
--- /dev/null
+++ b/products/workflows/frontend/Workflows/overview/WorkflowOverview.tsx
@@ -0,0 +1,250 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner, LemonButton, Link } from '@posthog/lemon-ui'
+
+import { getColorVar } from 'lib/colors'
+import { AppMetricsFilters } from 'lib/components/AppMetrics/AppMetricsFilters'
+import { AppMetricsTimeSeriesResponse, appMetricsLogic } from 'lib/components/AppMetrics/appMetricsLogic'
+import { percentage } from 'lib/utils/numbers'
+
+import { workflowSuggestionsAvailabilityLogic } from '../suggestions/workflowSuggestionsAvailabilityLogic'
+import { WorkflowMetricCard } from '../WorkflowMetricCard'
+import { METRIC_COLORS, withDisplayName, workflowMetricsSummaryLogic } from '../workflowMetricsSummaryLogic'
+import { WorkflowMessageLeaderboard } from './WorkflowMessageLeaderboard'
+import { WorkflowOverviewDetails } from './WorkflowOverviewDetails'
+import { WorkflowOverviewFeedback } from './WorkflowOverviewFeedback'
+import { WorkflowOverviewHealth } from './WorkflowOverviewHealth'
+import { WorkflowOverviewInFlight } from './WorkflowOverviewInFlight'
+import { workflowOverviewLogic } from './workflowOverviewLogic'
+import { WorkflowOverviewSuggestions } from './WorkflowOverviewSuggestions'
+import { WorkflowStepReach } from './WorkflowStepReach'
+
+function total(series: AppMetricsTimeSeriesResponse | null): number {
+ return series?.series.reduce((acc, s) => acc + s.values.reduce((a, v) => a + v, 0), 0) ?? 0
+}
+
+// One response with a line per channel, so the tile totals both and the sparkline splits them.
+function byChannel(
+ email: AppMetricsTimeSeriesResponse | null,
+ push: AppMetricsTimeSeriesResponse | null,
+ labels: { email: string; push: string }
+): AppMetricsTimeSeriesResponse | null {
+ const source = email ?? push
+ if (!source) {
+ return null
+ }
+ return {
+ ...source,
+ series: [
+ { name: labels.email, values: email?.series[0]?.values ?? [] },
+ { name: labels.push, values: push?.series[0]?.values ?? [] },
+ ],
+ }
+}
+
+const OPENED_SERIES_COLORS: Record<string, string> = {
+ 'Emails opened': METRIC_COLORS['Opened'],
+ 'Push notifications opened': METRIC_COLORS['Push notifications sent'],
+}
+
+function shareOf(part: number, whole: number, noun: string): JSX.Element | null {
+ return whole > 0 ? <span className="text-muted">{`${percentage(part / whole, 1)} of ${noun}`}</span> : null
+}
+
+export function WorkflowOverview({ id }: { id: string }): JSX.Element {
+ const logicKey = `hog-flow-overview-${id}`
+ const { getSingleTrendSeries: trendSeries, appMetricsTrendsLoading } = useValues(
+ appMetricsLogic({
+ logicKey,
+ loadOnChanges: true,
+ loadOnMount: true,
+ defaultParams: { dateFrom: '-30d', interval: 'day' },
+ forceParams: { appSource: 'hog_flow', appSourceId: id, breakdownBy: 'metric_name' },
+ })
+ )
+ const {
+ messagingChannels,
+ sentSummaryLabel,
+ hasConversionGoal,
+ convertedUsersUrl,
+ conversionStats,
+ conversionRate,
+ conversionStatsLoading,
+ conversionStatsFailed,
+ } = useValues(workflowMetricsSummaryLogic({ logicKey, id, overview: true }))
+ const { loadConversionStats } = useActions(workflowMetricsSummaryLogic({ logicKey, id, overview: true }))
+ const { hasEmail, hasPush } = messagingChannels
+ const overviewLogic = workflowOverviewLogic({ id, logicKey })
+ const { trendsFailed, previousPeriodFailed, retrying } = useValues(overviewLogic)
+ // A failed previous-period read leaves the old baseline in place, so the comparison is hidden instead.
+ const getSingleTrendSeries = (name: string, previous?: boolean): AppMetricsTimeSeriesResponse | null =>
+ previous && previousPeriodFailed ? null : trendSeries(name, previous)
+ const { retry } = useActions(overviewLogic)
+ const retryAll = (): void => {
+ retry()
+ loadConversionStats({})
+ }
+ const { suggestionsAvailable } = useValues(workflowSuggestionsAvailabilityLogic)
+
+ const sentFor = (previous?: boolean): AppMetricsTimeSeriesResponse | null =>
+ hasEmail && hasPush
+ ? byChannel(getSingleTrendSeries('email_sent', previous), getSingleTrendSeries('push_sent', previous), {
+ email: 'Emails sent',
+ push: 'Push notifications sent',
+ })
+ : withDisplayName(getSingleTrendSeries(hasPush ? 'push_sent' : 'email_sent', previous), sentSummaryLabel)
+ const openedFor = (previous?: boolean): AppMetricsTimeSeriesResponse | null =>
+ hasEmail && hasPush
+ ? byChannel(getSingleTrendSeries('email_opened', previous), getSingleTrendSeries('push_opened', previous), {
+ email: 'Emails opened',
+ push: 'Push notifications opened',
+ })
+ : withDisplayName(getSingleTrendSeries(hasPush ? 'push_opened' : 'email_opened', previous), 'Opened')
+
+ const started = withDisplayName(getSingleTrendSeries('triggered'), 'Workflows started')
+ const sent = sentFor()
+ const opened = openedFor()
+ const clicked = withDisplayName(getSingleTrendSeries('email_link_clicked'), 'Link clicked')
+ const converted = withDisplayName(getSingleTrendSeries('conversion'), 'Workflows converted')
+ const sentTotal = total(sent)
+
+ return (
+ <div className="@container flex flex-col gap-4" data-attr="workflow-overview">
+ <WorkflowOverviewFeedback />
+ <div className="flex flex-wrap items-center justify-end gap-2">
+ <AppMetricsFilters logicKey={logicKey} />
+ </div>
+ {trendsFailed || previousPeriodFailed ? (
+ <LemonBanner
+ type="error"
+ action={{
+ children: 'Try again',
+ onClick: retryAll,
+ loading: retrying,
+ 'data-attr': 'workflow-overview-retry',
+ }}
+ >
+ Couldn't load this workflow's metrics, so the numbers below may be missing.
+ </LemonBanner>
+ ) : null}
+
+ <div className="grid grid-cols-1 gap-2 @md:grid-cols-2 @3xl:grid-cols-3 @6xl:grid-cols-5">
+ <WorkflowMetricCard
+ name="Started"
+ description="Workflow runs that started in this date range."
+ loading={appMetricsTrendsLoading}
+ timeSeries={started}
+ previousPeriodTimeSeries={withDisplayName(
+ getSingleTrendSeries('triggered', true),
+ 'Workflows started'
+ )}
+ color={METRIC_COLORS['Workflows started']}
+ colorIfZero={getColorVar('muted')}
+ compact
+ className="min-w-0"
+ />
+ {hasEmail || hasPush ? (
+ <WorkflowMetricCard
+ name="Sent"
+ description={`${sentSummaryLabel} by this workflow in this date range.`}
+ loading={appMetricsTrendsLoading}
+ timeSeries={sent}
+ previousPeriodTimeSeries={sentFor(true)}
+ color={METRIC_COLORS[sentSummaryLabel]}
+ seriesColors={METRIC_COLORS}
+ colorIfZero={getColorVar('muted')}
+ compact
+ className="min-w-0"
+ />
+ ) : null}
+ {hasEmail || hasPush ? (
+ <WorkflowMetricCard
+ name="Opened"
+ description="Opens recorded in this date range. Only tracked emails can record opens."
+ loading={appMetricsTrendsLoading}
+ timeSeries={opened}
+ previousPeriodTimeSeries={openedFor(true)}
+ color={METRIC_COLORS['Opened']}
+ seriesColors={OPENED_SERIES_COLORS}
+ colorIfZero={getColorVar('muted')}
+ footer={shareOf(total(opened), sentTotal, 'sent')}
+ compact
+ className="min-w-0"
+ />
+ ) : null}
+ {hasEmail ? (
+ <WorkflowMetricCard
+ name="Clicked"
+ description="Email link clicks recorded in this date range."
+ loading={appMetricsTrendsLoading}
+ timeSeries={clicked}
+ previousPeriodTimeSeries={withDisplayName(
+ getSingleTrendSeries('email_link_clicked', true),
+ 'Link clicked'
+ )}
+ color={METRIC_COLORS['Link clicked']}
+ colorIfZero={getColorVar('muted')}
+ footer={shareOf(total(clicked), sentTotal, 'sent')}
+ compact
+ className="min-w-0"
+ />
+ ) : null}
+ {hasConversionGoal ? (
+ <WorkflowMetricCard
+ name="Converted"
+ description="Conversions recorded in this date range against the workflow's goal."
+ loading={appMetricsTrendsLoading}
+ timeSeries={converted}
+ previousPeriodTimeSeries={withDisplayName(
+ getSingleTrendSeries('conversion', true),
+ 'Workflows converted'
+ )}
+ color={METRIC_COLORS['Workflows converted']}
+ colorIfZero={getColorVar('muted')}
+ footer={
+ conversionStatsFailed ? (
+ <span className="flex flex-wrap items-center justify-center gap-x-2 text-muted">
+ <span>Couldn't load conversions.</span>
+ <LemonButton
+ size="xsmall"
+ type="tertiary"
+ onClick={() => loadConversionStats({})}
+ loading={conversionStatsLoading}
+ data-attr="workflow-overview-conversion-retry"
+ >
+ Try again
+ </LemonButton>
+ </span>
+ ) : conversionStatsLoading ? null : conversionStats.started > 0 ? (
+ <span className="flex flex-wrap items-center justify-center gap-x-2">
+ <span className="text-muted" data-attr="workflow-overview-conversion-rate">
+ {`${percentage(Math.min(conversionRate, 1), 1)} conversion rate`}
+ </span>
+ {conversionStats.conversions > 0 ? (
+ <Link to={convertedUsersUrl}>View converted people</Link>
+ ) : null}
+ </span>
+ ) : null
+ }
+ compact
+ className="min-w-0"
+ />
+ ) : null}
+ </div>
+
+ <WorkflowOverviewHealth id={id} logicKey={logicKey} />
+
+ <div className="grid grid-cols-1 items-start gap-4 @4xl:grid-cols-2">
+ <div className="flex min-w-0 flex-col gap-4">
+ <WorkflowStepReach id={id} logicKey={logicKey} />
+ <WorkflowOverviewDetails id={id} />
+ </div>
+ <div className="flex min-w-0 flex-col gap-4">
+ <WorkflowOverviewInFlight id={id} logicKey={logicKey} />
+ {suggestionsAvailable ? <WorkflowOverviewSuggestions id={id} /> : null}
+ <WorkflowMessageLeaderboard id={id} logicKey={logicKey} />
+ </div>
+ </div>
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/overview/WorkflowOverviewDetails.tsx b/products/workflows/frontend/Workflows/overview/WorkflowOverviewDetails.tsx
new file mode 100644
index 000000000000..80419e6791df
--- /dev/null
+++ b/products/workflows/frontend/Workflows/overview/WorkflowOverviewDetails.tsx
@@ -0,0 +1,182 @@
+import { useValues } from 'kea'
+
+import { IconBolt, IconChevronRight, IconClock, IconLeave, IconTarget } from '@posthog/icons'
+import { LemonButton, LemonTag } from '@posthog/lemon-ui'
+
+import PropertyFiltersDisplay from 'lib/components/PropertyFilters/components/PropertyFiltersDisplay'
+import { TZLabel } from 'lib/components/TZLabel'
+import { urls } from 'scenes/urls'
+
+import { getDurationText } from '../hogflows/steps/stepDelayLogic'
+import { workflowLogic } from '../workflowLogic'
+import {
+ EXIT_CONDITION_LABELS,
+ conversionGoalEvents,
+ frequencySummary,
+ triggerEventNames,
+ triggerLeadIn,
+ triggerPropertyFilters,
+} from './workflowOverviewSummary'
+
+function DetailsSection({
+ icon,
+ title,
+ editTo,
+ editAttr,
+ children,
+}: {
+ icon: JSX.Element
+ title: string
+ editTo: string
+ editAttr: string
+ children: React.ReactNode
+}): JSX.Element {
+ return (
+ <div className="flex flex-col gap-2 border-t px-4 py-3">
+ <div className="flex items-center justify-between gap-2">
+ <span className="flex items-center gap-1.5 font-semibold">
+ <span className="flex text-lg text-secondary">{icon}</span>
+ {title}
+ </span>
+ <LemonButton
+ size="xsmall"
+ type="tertiary"
+ sideIcon={<IconChevronRight />}
+ to={editTo}
+ data-attr={editAttr}
+ >
+ Edit
+ </LemonButton>
+ </div>
+ <div className="flex flex-col gap-2 text-sm">{children}</div>
+ </div>
+ )
+}
+
+export function WorkflowOverviewDetails({ id }: { id: string }): JSX.Element {
+ const { originalWorkflow } = useValues(workflowLogic)
+
+ if (!originalWorkflow) {
+ return <></>
+ }
+
+ const { trigger, conversion, exit_condition, email_sending_rate_limit, created_at, updated_at } = originalWorkflow
+ const editTriggerUrl = `${urls.workflow(id, 'workflow')}?node=trigger_node`
+ const eventNames = triggerEventNames(trigger)
+ const propertyFilters = triggerPropertyFilters(trigger)
+ const goalEvents = conversionGoalEvents(conversion)
+ const goalProperties = conversion?.filters ?? []
+ const goalWindow = conversion?.window ? getDurationText(conversion.window) : null
+ const hasGoal = goalEvents.length > 0 || goalProperties.length > 0
+
+ return (
+ <div className="flex flex-col rounded border bg-surface-primary" data-attr="workflow-overview-details">
+ <div className="flex flex-wrap items-center justify-between gap-2 px-4 py-3">
+ <h3 className="mb-0 text-base font-semibold">Details</h3>
+ <span className="flex flex-wrap items-center gap-2 text-xs text-muted">
+ <span>
+ Edited <TZLabel time={updated_at} />
+ </span>
+ <span>·</span>
+ <span>
+ Created <TZLabel time={created_at} />
+ </span>
+ </span>
+ </div>
+
+ <DetailsSection
+ icon={<IconBolt />}
+ title="Trigger"
+ editTo={editTriggerUrl}
+ editAttr="workflow-overview-edit-trigger"
+ >
+ <span>
+ {triggerLeadIn(trigger)}
+ {eventNames.length > 0 ? ':' : '.'}
+ </span>
+ {eventNames.length > 0 ? (
+ <div className="flex flex-wrap gap-1">
+ {eventNames.map((name) => (
+ <LemonTag key={name} type="muted" className="font-mono">
+ {name}
+ </LemonTag>
+ ))}
+ </div>
+ ) : null}
+ {propertyFilters.length > 0 ? (
+ <div className="flex flex-col gap-1">
+ <span className="text-xs text-muted">Only people matching</span>
+ <PropertyFiltersDisplay filters={propertyFilters} />
+ </div>
+ ) : null}
+ {trigger &&
+ 'filters' in trigger &&
+ (trigger.filters as { filter_test_accounts?: boolean })?.filter_test_accounts ? (
+ <span className="text-xs text-muted">Internal and test accounts are excluded.</span>
+ ) : null}
+ </DetailsSection>
+
+ <DetailsSection
+ icon={<IconClock />}
+ title="Frequency"
+ editTo={editTriggerUrl}
+ editAttr="workflow-overview-edit-frequency"
+ >
+ <span>{frequencySummary(originalWorkflow)}</span>
+ {email_sending_rate_limit ? (
+ <span className="text-muted">
+ {`Emails send at most ${email_sending_rate_limit.count.toLocaleString()} per ${email_sending_rate_limit.period}.`}
+ </span>
+ ) : null}
+ </DetailsSection>
+
+ <DetailsSection
+ icon={<IconTarget />}
+ title="Goal"
+ editTo={editTriggerUrl}
+ editAttr="workflow-overview-edit-goal"
+ >
+ {hasGoal ? (
+ <>
+ {goalEvents.length > 0 ? (
+ <div className="flex flex-wrap items-center gap-1">
+ <span>People convert when they perform</span>
+ {goalEvents.map((name) => (
+ <LemonTag key={name} type="muted" className="font-mono">
+ {name}
+ </LemonTag>
+ ))}
+ </div>
+ ) : null}
+ {goalProperties.length > 0 ? (
+ <div className="flex flex-col gap-1">
+ <span>
+ {goalEvents.length > 0 ? 'or when they match' : 'People convert when they match'}
+ </span>
+ <PropertyFiltersDisplay filters={goalProperties} />
+ </div>
+ ) : null}
+ {goalWindow ? (
+ <span className="text-xs text-muted">
+ {`Counted within ${goalWindow} of entering the workflow.`}
+ </span>
+ ) : null}
+ </>
+ ) : (
+ <span className="text-muted">
+ No conversion goal. Add one to measure what this workflow drives.
+ </span>
+ )}
+ </DetailsSection>
+
+ <DetailsSection
+ icon={<IconLeave />}
+ title="Exit"
+ editTo={editTriggerUrl}
+ editAttr="workflow-overview-edit-exit"
+ >
+ <span>{EXIT_CONDITION_LABELS[exit_condition] ?? EXIT_CONDITION_LABELS.exit_only_at_end}</span>
+ </DetailsSection>
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/overview/WorkflowOverviewFeedback.tsx b/products/workflows/frontend/Workflows/overview/WorkflowOverviewFeedback.tsx
new file mode 100644
index 000000000000..93521bec7c73
--- /dev/null
+++ b/products/workflows/frontend/Workflows/overview/WorkflowOverviewFeedback.tsx
@@ -0,0 +1,22 @@
+import { FeaturePreviewFeedbackBanner } from '../../FeaturePreviewFeedbackBanner'
+
+const SURVEY_ID = '01a135a4-2f3c-0000-4732-df04655842ff'
+const RATING_QUESTION_ID = '521dcdd1-4a8b-40c4-a8b3-41ac5b9a751f'
+const FEEDBACK_QUESTION_ID = '227c1646-eafa-46ad-823c-d2a8892a806b'
+
+export function WorkflowOverviewFeedback(): JSX.Element {
+ return (
+ <FeaturePreviewFeedbackBanner
+ surveyId={SURVEY_ID}
+ ratingQuestionId={RATING_QUESTION_ID}
+ feedbackQuestionId={FEEDBACK_QUESTION_ID}
+ surface="workflow_overview_tab"
+ dismissKey="workflow-overview-feature-preview"
+ prompt="We're trying out an overview for workflows. Is it useful?"
+ modalTitle="Help shape the workflow overview"
+ feedbackPlaceholder="Tell us what's useful, what's missing, or what you'd change"
+ className=""
+ data-attr="workflow-overview-feature-preview"
+ />
+ )
+}
diff --git a/products/workflows/frontend/Workflows/overview/WorkflowOverviewHealth.tsx b/products/workflows/frontend/Workflows/overview/WorkflowOverviewHealth.tsx
new file mode 100644
index 000000000000..d964f94d5b88
--- /dev/null
+++ b/products/workflows/frontend/Workflows/overview/WorkflowOverviewHealth.tsx
@@ -0,0 +1,189 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonSkeleton, LemonTag, LemonTagType, Link, Tooltip } from '@posthog/lemon-ui'
+
+import type { Dayjs } from 'lib/dayjs'
+import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'
+import { urls } from 'scenes/urls'
+
+import { RATE_LEVEL_TAG, classifyRate, minimumVolumeToClassify } from '../Reputation/emailRateLevels'
+import { workflowLogic } from '../workflowLogic'
+import { workflowMetricsSummaryLogic } from '../workflowMetricsSummaryLogic'
+import { workflowOverviewLogic } from './workflowOverviewLogic'
+
+function HealthItem({
+ label,
+ value,
+ detail,
+ tag,
+ tooltip,
+}: {
+ label: string
+ value: React.ReactNode
+ detail?: React.ReactNode
+ tag?: { label: string; type: LemonTagType } | null
+ tooltip?: string
+}): JSX.Element {
+ return (
+ <div className="flex min-w-0 flex-col gap-1 px-4 py-3">
+ <Tooltip title={tooltip}>
+ <span className="text-xs font-semibold text-secondary">{label}</span>
+ </Tooltip>
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="text-lg font-semibold">{value}</span>
+ {tag ? (
+ <LemonTag type={tag.type} size="small">
+ {tag.label}
+ </LemonTag>
+ ) : null}
+ </div>
+ {detail ? <span className="text-xs text-muted">{detail}</span> : null}
+ </div>
+ )
+}
+
+function rateItem(
+ kind: 'bounce' | 'complaint',
+ count: number,
+ sent: number,
+ detail: string
+): { value: string; tag: { label: string; type: LemonTagType } | null; detail: string } {
+ if (sent === 0) {
+ return { value: '-', tag: null, detail: 'No emails sent' }
+ }
+ const rate = count / sent
+ return {
+ value: percentage(rate, 2, true),
+ tag: sent < minimumVolumeToClassify(kind) ? null : RATE_LEVEL_TAG[classifyRate(rate, kind)],
+ detail,
+ }
+}
+
+// A failed step does not fail the run when the step continues on error, so the run status filter would miss it.
+// Absolute bounds, because Invocations resolves a relative range from the current time rather than the start of the day.
+function loggedErrorsUrl(id: string, dateFrom: Dayjs, dateTo: Dayjs): string {
+ const search = new URLSearchParams({
+ inv_problems: '1',
+ inv_date_from: dateFrom.toISOString(),
+ inv_date_to: dateTo.toISOString(),
+ })
+ return `${urls.workflow(id, 'invocations')}?${search.toString()}`
+}
+
+export function WorkflowOverviewHealth({ id, logicKey }: { id: string; logicKey: string }): JSX.Element {
+ const logic = workflowOverviewLogic({ id, logicKey })
+ const {
+ healthTotals,
+ healthTotalsLoading,
+ failedRuns,
+ stepTotalsLoading,
+ stepTotalsFailed,
+ healthTotalsFailed,
+ retrying,
+ getDateRangeAbsolute,
+ } = useValues(logic)
+ const range = getDateRangeAbsolute()
+ const { retry } = useActions(logic)
+ const { messagingChannels } = useValues(workflowMetricsSummaryLogic({ logicKey, id, overview: true }))
+ const { emailSendingPaused } = useValues(workflowLogic)
+
+ const loading = (healthTotalsLoading && !healthTotals) || (stepTotalsLoading && failedRuns === null)
+ const totals = healthTotals ?? {}
+ const started = totals.triggered ?? 0
+ const emailSent = totals.email_sent ?? 0
+ const pushSent = totals.push_sent ?? 0
+ // Reputation thresholds apply to permanent bounces only, as on the Reputation page.
+ const hardBounces = totals.email_bounced_hard ?? 0
+ const bounce = rateItem(
+ 'bounce',
+ hardBounces,
+ emailSent,
+ `${humanFriendlyNumber(hardBounces)} hard, ${humanFriendlyNumber(totals.email_bounced ?? 0)} bounced in total`
+ )
+ // Spam complaints are stored under the email_blocked metric name.
+ const complaintCount = totals.email_blocked ?? 0
+ const complaint = rateItem(
+ 'complaint',
+ complaintCount,
+ emailSent,
+ `${humanFriendlyNumber(complaintCount)} marked as spam`
+ )
+ const failed = stepTotalsFailed || healthTotalsFailed
+
+ return (
+ <div className="@container rounded border bg-surface-primary" data-attr="workflow-overview-health">
+ <div className="flex items-center justify-between gap-2 border-b px-4 py-2">
+ <h3 className="mb-0 text-base font-semibold">Health</h3>
+ {emailSendingPaused ? (
+ <LemonTag type="danger" data-attr="workflow-overview-health-paused">
+ Email sending paused
+ </LemonTag>
+ ) : null}
+ </div>
+ {failed ? (
+ <div className="flex flex-wrap items-center gap-2 p-4 text-sm text-muted">
+ <span>Couldn't load this workflow's health.</span>
+ <LemonButton
+ size="small"
+ type="secondary"
+ onClick={retry}
+ loading={retrying}
+ data-attr="workflow-overview-health-retry"
+ >
+ Try again
+ </LemonButton>
+ </div>
+ ) : loading ? (
+ <div className="p-4">
+ <LemonSkeleton className="h-12" />
+ </div>
+ ) : (
+ <div className="grid grid-cols-1 divide-y @3xl:auto-cols-fr @3xl:grid-flow-col @3xl:divide-x @3xl:divide-y-0">
+ <HealthItem
+ label="Failed steps"
+ value={humanFriendlyNumber(failedRuns ?? 0)}
+ tag={(failedRuns ?? 0) > 0 ? { label: 'Check logs', type: 'warning' } : RATE_LEVEL_TAG.healthy}
+ tooltip="Steps that errored in this date range. A failed step either stops the run or continues, depending on the step's error setting."
+ detail={
+ (failedRuns ?? 0) > 0 ? (
+ <Link
+ to={loggedErrorsUrl(id, range.dateFrom, range.dateTo)}
+ data-attr="workflow-overview-health-failures"
+ >
+ {`${started > 0 ? `${percentage((failedRuns ?? 0) / started, 1)} of started. ` : ''}View runs with errors`}
+ </Link>
+ ) : (
+ 'No errors'
+ )
+ }
+ />
+ {messagingChannels.hasEmail ? (
+ <>
+ <HealthItem
+ label="Hard bounce rate"
+ tooltip="Permanent bounces as a share of emails sent. A high hard bounce rate can pause email from this workflow automatically."
+ {...bounce}
+ />
+ <HealthItem
+ label="Spam complaint rate"
+ tooltip="Spam complaints as a share of emails sent. A high complaint rate can pause email from this workflow automatically."
+ {...complaint}
+ />
+ </>
+ ) : null}
+ {messagingChannels.hasPush ? (
+ <HealthItem
+ label="Push failures"
+ value={humanFriendlyNumber(totals.push_failed ?? 0)}
+ detail={
+ pushSent > 0
+ ? `${percentage((totals.push_failed ?? 0) / pushSent, 1)} of sent`
+ : 'No push notifications sent'
+ }
+ />
+ ) : null}
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/overview/WorkflowOverviewInFlight.tsx b/products/workflows/frontend/Workflows/overview/WorkflowOverviewInFlight.tsx
new file mode 100644
index 000000000000..13bd11c02b07
--- /dev/null
+++ b/products/workflows/frontend/Workflows/overview/WorkflowOverviewInFlight.tsx
@@ -0,0 +1,89 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonSkeleton, Link } from '@posthog/lemon-ui'
+
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+import { urls } from 'scenes/urls'
+
+import { workflowLogic } from '../workflowLogic'
+import { workflowOverviewLogic } from './workflowOverviewLogic'
+
+const MAX_STEPS = 5
+
+export function WorkflowOverviewInFlight({ id, logicKey }: { id: string; logicKey: string }): JSX.Element {
+ const logic = workflowOverviewLogic({ id, logicKey })
+ const { inFlight, inFlightLoading, inFlightSteps } = useValues(logic)
+ const { loadInFlight } = useActions(logic)
+ // The editor shows the staged draft, so a live step the draft removes has nothing to open there.
+ const { workflow } = useValues(workflowLogic)
+ const count = inFlight?.count ?? null
+ const positionUnknown = inFlight?.position_unknown ?? 0
+
+ return (
+ <div
+ className="flex flex-col gap-3 rounded border bg-surface-primary p-4"
+ data-attr="workflow-overview-in-flight"
+ >
+ <div className="flex flex-col gap-1">
+ <h3 className="mb-0 text-base font-semibold">In the workflow now</h3>
+ <span className="text-xs text-muted">
+ People partway through, waiting on a step or being processed.
+ </span>
+ </div>
+ {inFlightLoading && !inFlight ? (
+ <LemonSkeleton className="h-16" />
+ ) : count === null ? (
+ <span className="flex flex-wrap items-center gap-2 text-sm text-muted">
+ Couldn't count people in the workflow.
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ onClick={loadInFlight}
+ loading={inFlightLoading}
+ data-attr="workflow-overview-in-flight-retry"
+ >
+ Try again
+ </LemonButton>
+ </span>
+ ) : (
+ <>
+ <span className="text-3xl font-semibold">{humanFriendlyNumber(count)}</span>
+ {inFlightSteps.length > 0 ? (
+ <div className="flex flex-col gap-1 text-sm">
+ {inFlightSteps.slice(0, MAX_STEPS).map(({ action, count: stepCount }) => (
+ <div key={action.id} className="flex items-center justify-between gap-2">
+ {workflow?.actions.some((a) => a.id === action.id) ? (
+ <Link
+ to={`${urls.workflow(id, 'workflow')}?node=${encodeURIComponent(action.id)}`}
+ className="truncate"
+ data-attr="workflow-overview-in-flight-step"
+ >
+ {action.name}
+ </Link>
+ ) : (
+ <span className="truncate">{action.name}</span>
+ )}
+ <span className="whitespace-nowrap text-secondary">
+ {humanFriendlyNumber(stepCount)}
+ </span>
+ </div>
+ ))}
+ {inFlightSteps.length > MAX_STEPS ? (
+ <span className="text-xs text-muted">
+ {`And ${inFlightSteps.length - MAX_STEPS} more steps`}
+ </span>
+ ) : null}
+ </div>
+ ) : count === 0 ? (
+ <span className="text-sm text-muted">No one is partway through right now.</span>
+ ) : null}
+ {positionUnknown > 0 ? (
+ <span className="text-xs text-muted">
+ {`${humanFriendlyNumber(positionUnknown)} of them are between steps.`}
+ </span>
+ ) : null}
+ </>
+ )}
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/overview/WorkflowOverviewSuggestions.tsx b/products/workflows/frontend/Workflows/overview/WorkflowOverviewSuggestions.tsx
new file mode 100644
index 000000000000..4dfcb5d5a352
--- /dev/null
+++ b/products/workflows/frontend/Workflows/overview/WorkflowOverviewSuggestions.tsx
@@ -0,0 +1,115 @@
+import { useActions, useValues } from 'kea'
+
+import { IconChevronRight } from '@posthog/icons'
+import { LemonButton, LemonSkeleton, LemonTag, Link } from '@posthog/lemon-ui'
+
+import { urls } from 'scenes/urls'
+
+import { workflowProposalsLogic } from '../suggestions/workflowProposalsLogic'
+import { workflowLogic } from '../workflowLogic'
+
+const MAX_SUGGESTIONS = 3
+
+export function WorkflowOverviewSuggestions({ id }: { id: string }): JSX.Element {
+ const logic = workflowProposalsLogic({ id })
+ const {
+ pendingProposals,
+ optimizationEnabled,
+ proposalsResponseLoading,
+ approvedResponseLoading,
+ appliedResponseLoading,
+ rejectedResponseLoading,
+ optimizationLoading,
+ listsUnreadable,
+ optimizationUnreadable,
+ } = useValues(logic)
+ const { reloadLists, loadOptimization } = useActions(logic)
+ const { workflow } = useValues(workflowLogic({ id }))
+ const selfDrivingUrl = urls.workflow(id, 'self-driving')
+ const watching = optimizationEnabled && workflow?.status === 'active'
+
+ return (
+ <div
+ className="flex flex-col gap-3 rounded border bg-surface-primary p-4"
+ data-attr="workflow-overview-suggestions"
+ >
+ <div className="flex items-center justify-between gap-2">
+ <h3 className="mb-0 flex items-center gap-2 text-base font-semibold">
+ Suggested changes
+ {pendingProposals.length > 0 ? (
+ <LemonTag type="completion" size="small">
+ {pendingProposals.length}
+ </LemonTag>
+ ) : null}
+ </h3>
+ <LemonButton
+ size="xsmall"
+ type="tertiary"
+ sideIcon={<IconChevronRight />}
+ to={selfDrivingUrl}
+ data-attr="workflow-overview-suggestions-open"
+ >
+ {pendingProposals.length > 0 ? 'Review' : 'Open'}
+ </LemonButton>
+ </div>
+ {pendingProposals.length === 0 && (proposalsResponseLoading || optimizationLoading) ? (
+ <LemonSkeleton className="h-5" />
+ ) : listsUnreadable && pendingProposals.length === 0 ? (
+ <span className="flex flex-wrap items-center gap-2 text-sm text-muted">
+ Couldn't load suggestions.
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ onClick={reloadLists}
+ loading={
+ proposalsResponseLoading ||
+ approvedResponseLoading ||
+ appliedResponseLoading ||
+ rejectedResponseLoading
+ }
+ data-attr="workflow-overview-suggestions-retry"
+ >
+ Try again
+ </LemonButton>
+ </span>
+ ) : pendingProposals.length > 0 ? (
+ <div className="flex flex-col gap-1 text-sm">
+ {pendingProposals.slice(0, MAX_SUGGESTIONS).map((proposal) => (
+ <Link
+ key={proposal.id}
+ to={selfDrivingUrl}
+ className="truncate"
+ data-attr="workflow-overview-suggestion"
+ >
+ {proposal.title}
+ </Link>
+ ))}
+ {pendingProposals.length > MAX_SUGGESTIONS ? (
+ <span className="text-xs text-muted">{`And ${pendingProposals.length - MAX_SUGGESTIONS} more`}</span>
+ ) : null}
+ </div>
+ ) : optimizationUnreadable ? (
+ <span className="flex flex-wrap items-center gap-2 text-sm text-muted">
+ Couldn't check whether self-driving is on.
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ onClick={loadOptimization}
+ loading={optimizationLoading}
+ data-attr="workflow-overview-suggestions-retry"
+ >
+ Try again
+ </LemonButton>
+ </span>
+ ) : watching ? (
+ <span className="text-sm text-muted">
+ No suggestions yet. PostHog is watching this workflow and will suggest changes here.
+ </span>
+ ) : (
+ <span className="text-sm text-muted">
+ Turn on self-driving to get suggested changes based on how this workflow performs.
+ </span>
+ )}
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/overview/WorkflowStepReach.tsx b/products/workflows/frontend/Workflows/overview/WorkflowStepReach.tsx
new file mode 100644
index 000000000000..c11c49528455
--- /dev/null
+++ b/products/workflows/frontend/Workflows/overview/WorkflowStepReach.tsx
@@ -0,0 +1,118 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonSkeleton, LemonTag, Link } from '@posthog/lemon-ui'
+
+import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
+import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'
+
+import { metricsStepUrl } from '../metricsDrillParams'
+import { workflowOverviewLogic } from './workflowOverviewLogic'
+
+function ReachRow({
+ name,
+ count,
+ base,
+ to,
+ failed,
+ waiting,
+}: {
+ name: string
+ count: number
+ base: number
+ to?: string
+ failed?: number
+ waiting?: number
+}): JSX.Element {
+ const share = base > 0 ? Math.min(1, count / base) : 0
+ return (
+ <div className="flex flex-col gap-1">
+ <div className="flex items-center justify-between gap-2 text-sm">
+ <span className="flex min-w-0 items-center gap-2">
+ {to ? (
+ <Link to={to} className="truncate" data-attr="workflow-overview-step-reach-step">
+ {name}
+ </Link>
+ ) : (
+ <span className="truncate font-medium">{name}</span>
+ )}
+ {failed ? (
+ <LemonTag type="danger" size="small">
+ {`${humanFriendlyNumber(failed)} failed`}
+ </LemonTag>
+ ) : null}
+ {waiting ? (
+ <span
+ className="whitespace-nowrap text-xs text-muted"
+ data-attr="workflow-overview-step-reach-waiting"
+ >
+ {`${humanFriendlyNumber(waiting)} waiting now`}
+ </span>
+ ) : null}
+ </span>
+ <span className="whitespace-nowrap">
+ <span translate="no">{humanFriendlyNumber(count)}</span>
+ {base > 0 ? (
+ <span className="text-muted" translate="no">{` (${percentage(count / base, 1)})`}</span>
+ ) : null}
+ </span>
+ </div>
+ <LemonProgress percent={share * 100} />
+ </div>
+ )
+}
+
+export function WorkflowStepReach({ id, logicKey }: { id: string; logicKey: string }): JSX.Element {
+ const logic = workflowOverviewLogic({ id, logicKey })
+ const { stepReach, stepTotalsLoading, healthTotals, params, stepTotalsFailed, healthTotalsFailed, retrying } =
+ useValues(logic)
+ const { retry } = useActions(logic)
+ const started = healthTotals?.triggered ?? 0
+
+ return (
+ <div
+ className="flex flex-col gap-3 rounded border bg-surface-primary p-4"
+ data-attr="workflow-overview-step-reach"
+ >
+ <div className="flex flex-col gap-1">
+ <h3 className="mb-0 text-base font-semibold">Step reach</h3>
+ <span className="text-xs text-muted">
+ How many runs finished each step in this date range, as a share of runs started. Runs still waiting
+ at a step count once they move on.
+ </span>
+ </div>
+ {stepTotalsFailed || healthTotalsFailed ? (
+ <span className="flex flex-wrap items-center gap-2 text-sm text-muted">
+ Couldn't load step reach.
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ onClick={retry}
+ loading={retrying}
+ data-attr="workflow-overview-step-reach-retry"
+ >
+ Try again
+ </LemonButton>
+ </span>
+ ) : stepTotalsLoading && !stepReach ? (
+ <LemonSkeleton repeat={4} className="h-6" />
+ ) : !stepReach || stepReach.length === 0 ? (
+ <span className="text-sm text-muted">This workflow has no steps yet.</span>
+ ) : (
+ <div className="flex flex-col gap-3">
+ <ReachRow name="Started" count={started} base={started} />
+ {stepReach.map(({ action, reached, failed, waiting }) => (
+ <ReachRow
+ key={action.id}
+ name={action.name}
+ count={reached}
+ base={started}
+ failed={failed}
+ waiting={waiting}
+ to={metricsStepUrl(id, action.id, params)}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/overview/workflowOverviewLogic.ts b/products/workflows/frontend/Workflows/overview/workflowOverviewLogic.ts
new file mode 100644
index 000000000000..b6b20f0b0a92
--- /dev/null
+++ b/products/workflows/frontend/Workflows/overview/workflowOverviewLogic.ts
@@ -0,0 +1,462 @@
+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { ApiConfig } from 'lib/api'
+import {
+ AppMetricsCommonParams,
+ AppMetricsTimeSeriesResponse,
+ AppMetricsTotalsRequest,
+ appMetricsLogic,
+ loadAppMetricsTotals,
+} from 'lib/components/AppMetrics/appMetricsLogic'
+import type { Dayjs } from 'lib/dayjs'
+
+import type { TeamPublicType, TeamType } from '~/types'
+
+import { hogFlowsInFlightRetrieve } from '../../generated/api'
+import type { HogFlowInFlightApi } from '../../generated/api.schemas'
+import type { HogFlow, HogFlowAction } from '../hogflows/types'
+import { getOrderedActions } from '../templates/workflowTemplateDisplay'
+import { workflowLogic } from '../workflowLogic'
+
+export interface WorkflowOverviewLogicProps {
+ id: string
+ logicKey: string
+}
+
+const STEP_METRICS = ['succeeded', 'failed', 'filtered'] as const
+// Enough for every (step, metric) pair of a large workflow; the query's default limit is 100 rows.
+const STEP_TOTALS_LIMIT = 10_000
+type StepMetric = (typeof STEP_METRICS)[number]
+
+const HEALTH_METRICS = [
+ 'triggered',
+ 'email_sent',
+ 'email_bounced',
+ 'email_bounced_hard',
+ 'email_blocked',
+ 'push_sent',
+ 'push_failed',
+] as const
+export type HealthMetric = (typeof HEALTH_METRICS)[number]
+
+export type StepReach = {
+ action: HogFlowAction
+ // Runs that finished this step in the selected date range. A step records its metric when it finishes.
+ reached: number
+ failed: number
+ // Runs at this step now. Counted only when the date range ends now, because the queue has no history.
+ waiting: number
+}
+
+export type InFlightStep = {
+ action: HogFlowAction
+ count: number
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface workflowOverviewLogicValues {
+ appMetricsTrends: AppMetricsTimeSeriesResponse | null // appMetricsLogic
+ appMetricsTrendsLoading: boolean // appMetricsLogic
+ appMetricsTrendsPreviousPeriodLoading: boolean // appMetricsLogic
+ currentTeam: TeamPublicType | TeamType | null // appMetricsLogic
+ getDateRangeAbsolute: () => {
+ dateFrom: Dayjs
+ dateTo: Dayjs
+ diffMs: number
+ } // appMetricsLogic
+ params: Partial<AppMetricsCommonParams> // appMetricsLogic
+ originalWorkflow: HogFlow | null // workflowLogic
+ failedRuns: number | null
+ healthTotals: Partial<Record<HealthMetric, number>> | null
+ healthTotalsFailed: boolean
+ healthTotalsLoading: boolean
+ inFlight: HogFlowInFlightApi | null
+ inFlightLoading: boolean
+ inFlightSteps: InFlightStep[]
+ orderedSteps: HogFlowAction[]
+ previousPeriodFailed: boolean
+ retrying: boolean
+ stepReach: StepReach[] | null
+ stepTotals: Record<string, Partial<Record<StepMetric, number>>> | null
+ stepTotalsFailed: boolean
+ stepTotalsLoading: boolean
+ trendsFailed: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface workflowOverviewLogicActions {
+ loadAppMetricsTrends: () => {
+ value: true
+ } // appMetricsLogic
+ loadAppMetricsTrendsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ } // appMetricsLogic
+ loadAppMetricsTrendsPreviousPeriod: () => {
+ value: true
+ } // appMetricsLogic
+ loadAppMetricsTrendsPreviousPeriodFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ } // appMetricsLogic
+ loadAppMetricsTrendsPreviousPeriodSuccess: (
+ appMetricsTrendsPreviousPeriod: AppMetricsTimeSeriesResponse,
+ payload?:
+ | {
+ value: true
+ }
+ | undefined
+ ) => {
+ appMetricsTrendsPreviousPeriod: AppMetricsTimeSeriesResponse
+ payload?: {
+ value: true
+ }
+ } // appMetricsLogic
+ loadAppMetricsTrendsSuccess: (
+ appMetricsTrends: AppMetricsTimeSeriesResponse,
+ payload?:
+ | {
+ value: true
+ }
+ | undefined
+ ) => {
+ appMetricsTrends: AppMetricsTimeSeriesResponse
+ payload?: {
+ value: true
+ }
+ } // appMetricsLogic
+ setParams: (params: Partial<AppMetricsCommonParams>) => {
+ params: Partial<AppMetricsCommonParams>
+ } // appMetricsLogic
+ loadHealthTotals: (_: any) => any
+ loadHealthTotalsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadHealthTotalsSuccess: (
+ healthTotals: Partial<
+ Record<
+ | 'email_blocked'
+ | 'email_bounced'
+ | 'email_bounced_hard'
+ | 'email_sent'
+ | 'push_failed'
+ | 'push_sent'
+ | 'triggered',
+ number
+ >
+ >,
+ payload?: any
+ ) => {
+ healthTotals: Partial<
+ Record<
+ | 'email_blocked'
+ | 'email_bounced'
+ | 'email_bounced_hard'
+ | 'email_sent'
+ | 'push_failed'
+ | 'push_sent'
+ | 'triggered',
+ number
+ >
+ >
+ payload?: any
+ }
+ loadInFlight: () => any
+ loadInFlightFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadInFlightSuccess: (
+ inFlight: HogFlowInFlightApi,
+ payload?: any
+ ) => {
+ inFlight: HogFlowInFlightApi
+ payload?: any
+ }
+ loadStepTotals: (_: any) => any
+ loadStepTotalsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadStepTotalsSuccess: (
+ stepTotals: Record<string, Partial<Record<'failed' | 'filtered' | 'succeeded', number>>>,
+ payload?: any
+ ) => {
+ stepTotals: Record<string, Partial<Record<'failed' | 'filtered' | 'succeeded', number>>>
+ payload?: any
+ }
+ retry: () => {
+ value: true
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface workflowOverviewLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ orderedSteps: (originalWorkflow: HogFlow | null) => HogFlowAction[]
+ stepReach: (
+ orderedSteps: HogFlowAction[],
+ stepTotals: Record<string, Partial<Record<'failed' | 'filtered' | 'succeeded', number>>> | null,
+ inFlight: HogFlowInFlightApi | null,
+ params: Partial<AppMetricsCommonParams>
+ ) => StepReach[] | null
+ retrying: (
+ appMetricsTrendsLoading: boolean,
+ appMetricsTrendsPreviousPeriodLoading: boolean,
+ stepTotalsLoading: boolean,
+ healthTotalsLoading: boolean
+ ) => boolean
+ failedRuns: (
+ stepTotals: Record<string, Partial<Record<'failed' | 'filtered' | 'succeeded', number>>> | null
+ ) => number | null
+ inFlightSteps: (orderedSteps: HogFlowAction[], inFlight: HogFlowInFlightApi | null) => InFlightStep[]
+ }
+}
+
+export type workflowOverviewLogicType = MakeLogicType<
+ workflowOverviewLogicValues,
+ workflowOverviewLogicActions,
+ WorkflowOverviewLogicProps,
+ workflowOverviewLogicMeta
+>
+
+export const workflowOverviewLogic = kea<workflowOverviewLogicType>([
+ path(['products', 'workflows', 'frontend', 'Workflows', 'overview', 'workflowOverviewLogic']),
+ props({} as WorkflowOverviewLogicProps),
+ key(({ id }: WorkflowOverviewLogicProps) => id),
+ connect((props: WorkflowOverviewLogicProps) => ({
+ values: [
+ workflowLogic,
+ ['originalWorkflow'],
+ appMetricsLogic({ logicKey: props.logicKey }),
+ [
+ 'params',
+ 'currentTeam',
+ 'getDateRangeAbsolute',
+ 'appMetricsTrends',
+ 'appMetricsTrendsLoading',
+ 'appMetricsTrendsPreviousPeriodLoading',
+ ],
+ ],
+ actions: [
+ appMetricsLogic({ logicKey: props.logicKey }),
+ [
+ 'setParams',
+ 'loadAppMetricsTrends',
+ 'loadAppMetricsTrendsPreviousPeriod',
+ 'loadAppMetricsTrendsSuccess',
+ 'loadAppMetricsTrendsFailure',
+ 'loadAppMetricsTrendsPreviousPeriodSuccess',
+ 'loadAppMetricsTrendsPreviousPeriodFailure',
+ ],
+ ],
+ })),
+ actions({
+ retry: true,
+ }),
+ reducers({
+ trendsFailed: [
+ false,
+ {
+ loadAppMetricsTrendsFailure: () => true,
+ loadAppMetricsTrendsSuccess: () => false,
+ },
+ ],
+ previousPeriodFailed: [
+ false,
+ {
+ loadAppMetricsTrendsPreviousPeriodFailure: () => true,
+ loadAppMetricsTrendsPreviousPeriodSuccess: () => false,
+ },
+ ],
+ stepTotalsFailed: [
+ false,
+ {
+ loadStepTotalsFailure: () => true,
+ loadStepTotalsSuccess: () => false,
+ },
+ ],
+ healthTotalsFailed: [
+ false,
+ {
+ loadHealthTotalsFailure: () => true,
+ loadHealthTotalsSuccess: () => false,
+ },
+ ],
+ }),
+ loaders(({ props, values }) => ({
+ stepTotals: [
+ null as Record<string, Partial<Record<StepMetric, number>>> | null,
+ {
+ loadStepTotals: async (_, breakpoint) => {
+ await breakpoint(10)
+ const dateRange = values.getDateRangeAbsolute()
+ const request: AppMetricsTotalsRequest = {
+ appSource: 'hog_flow',
+ appSourceId: props.id,
+ breakdownBy: ['instance_id', 'metric_name'],
+ metricName: [...STEP_METRICS],
+ limit: STEP_TOTALS_LIMIT,
+ dateFrom: dateRange.dateFrom.toISOString(),
+ dateTo: dateRange.dateTo.toISOString(),
+ }
+ const response = await loadAppMetricsTotals(request, values.currentTeam?.timezone ?? 'UTC')
+ await breakpoint(10)
+ // Step ids come from the workflow author, so a key like "__proto__" must not reach the prototype.
+ const byAction: Record<string, Partial<Record<StepMetric, number>>> = Object.create(null)
+ Object.values(response).forEach(({ total, breakdowns }) => {
+ const [instanceId, metricName] = breakdowns
+ if (!instanceId) {
+ return
+ }
+ byAction[instanceId] = byAction[instanceId] ?? Object.create(null)
+ byAction[instanceId][metricName as StepMetric] =
+ (byAction[instanceId][metricName as StepMetric] ?? 0) + total
+ })
+ return byAction
+ },
+ },
+ ],
+ healthTotals: [
+ null as Partial<Record<HealthMetric, number>> | null,
+ {
+ loadHealthTotals: async (_, breakpoint) => {
+ await breakpoint(10)
+ const dateRange = values.getDateRangeAbsolute()
+ const request: AppMetricsTotalsRequest = {
+ appSource: 'hog_flow',
+ appSourceId: props.id,
+ breakdownBy: ['metric_name'],
+ metricName: [...HEALTH_METRICS],
+ dateFrom: dateRange.dateFrom.toISOString(),
+ dateTo: dateRange.dateTo.toISOString(),
+ }
+ const response = await loadAppMetricsTotals(request, values.currentTeam?.timezone ?? 'UTC')
+ await breakpoint(10)
+ const totals: Partial<Record<HealthMetric, number>> = {}
+ Object.values(response).forEach(({ total, breakdowns }) => {
+ const metricName = breakdowns[0] as HealthMetric
+ totals[metricName] = (totals[metricName] ?? 0) + total
+ })
+ return totals
+ },
+ },
+ ],
+ inFlight: [
+ null as HogFlowInFlightApi | null,
+ {
+ loadInFlight: async () => {
+ return await hogFlowsInFlightRetrieve(String(ApiConfig.getCurrentTeamId()), props.id)
+ },
+ },
+ ],
+ })),
+ selectors({
+ orderedSteps: [
+ (s) => [s.originalWorkflow],
+ (workflow: HogFlow | null): HogFlowAction[] =>
+ workflow
+ ? getOrderedActions(workflow.actions, workflow.edges)
+ .filter((a) => a.type !== 'trigger')
+ // A branch's timeout path can reach the exit before the main path is walked.
+ .sort((a, b) => Number(a.type === 'exit') - Number(b.type === 'exit'))
+ : [],
+ ],
+ stepReach: [
+ (s) => [s.orderedSteps, s.stepTotals, s.inFlight, s.params],
+ (
+ steps: HogFlowAction[],
+ stepTotals: Record<string, Partial<Record<StepMetric, number>>> | null,
+ inFlight: HogFlowInFlightApi | null,
+ params: Partial<AppMetricsCommonParams>
+ ): StepReach[] | null =>
+ stepTotals
+ ? steps.map((action) => {
+ const totals = stepTotals[action.id] ?? {}
+ const failed = totals.failed ?? 0
+ const waiting = params.dateTo ? 0 : (inFlight?.by_action?.[action.id] ?? 0)
+ // A step that continues on error records `succeeded` as well as `failed`. The current
+ // on_error setting is applied to the whole range, so a change to it inside the range skews this.
+ const abortedRuns = action.on_error === 'abort' ? failed : 0
+ return {
+ action,
+ reached: (totals.succeeded ?? 0) + (totals.filtered ?? 0) + abortedRuns,
+ failed,
+ waiting,
+ }
+ })
+ : null,
+ ],
+ // Counts every step with metrics in the range, including steps since removed from the workflow.
+ retrying: [
+ (s) => [
+ s.appMetricsTrendsLoading,
+ s.appMetricsTrendsPreviousPeriodLoading,
+ s.stepTotalsLoading,
+ s.healthTotalsLoading,
+ ],
+ (
+ trendsLoading: boolean,
+ previousPeriodLoading: boolean,
+ stepTotalsLoading: boolean,
+ healthTotalsLoading: boolean
+ ): boolean => trendsLoading || previousPeriodLoading || stepTotalsLoading || healthTotalsLoading,
+ ],
+ failedRuns: [
+ (s) => [s.stepTotals],
+ (stepTotals: Record<string, Partial<Record<StepMetric, number>>> | null): number | null =>
+ stepTotals ? Object.values(stepTotals).reduce((sum, totals) => sum + (totals.failed ?? 0), 0) : null,
+ ],
+ inFlightSteps: [
+ (s) => [s.orderedSteps, s.inFlight],
+ (steps: HogFlowAction[], inFlight: HogFlowInFlightApi | null): InFlightStep[] => {
+ const byAction = inFlight?.by_action ?? {}
+ return steps
+ .map((action) => ({ action, count: byAction[action.id] ?? 0 }))
+ .filter((step) => step.count > 0)
+ .sort((a, b) => b.count - a.count)
+ },
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ setParams: () => {
+ actions.loadStepTotals({})
+ actions.loadHealthTotals({})
+ // appMetricsLogic only reloads its trends on a range change once a load has finished.
+ if (!values.appMetricsTrends) {
+ actions.loadAppMetricsTrends()
+ actions.loadAppMetricsTrendsPreviousPeriod()
+ }
+ },
+ retry: () => {
+ actions.loadAppMetricsTrends()
+ actions.loadAppMetricsTrendsPreviousPeriod()
+ actions.loadStepTotals({})
+ actions.loadHealthTotals({})
+ actions.loadInFlight()
+ },
+ })),
+ afterMount(({ actions }) => {
+ actions.loadStepTotals({})
+ actions.loadHealthTotals({})
+ actions.loadInFlight()
+ }),
+])
diff --git a/products/workflows/frontend/Workflows/overview/workflowOverviewSummary.ts b/products/workflows/frontend/Workflows/overview/workflowOverviewSummary.ts
new file mode 100644
index 000000000000..b06d241ebaf1
--- /dev/null
+++ b/products/workflows/frontend/Workflows/overview/workflowOverviewSummary.ts
@@ -0,0 +1,89 @@
+import { humanFriendlyDuration } from 'lib/utils/durations'
+
+import { PERSON_FREQUENCY_OPTIONS, getRegisteredTriggerTypes } from '../hogflows/registry/triggers/triggerTypeRegistry'
+import { TTL_OPTIONS } from '../hogflows/steps/StepTrigger'
+import type { HogFlow } from '../hogflows/types'
+
+export const EXIT_CONDITION_LABELS: Record<HogFlow['exit_condition'], string> = {
+ exit_only_at_end: 'People leave the workflow when they reach the end.',
+ exit_on_trigger_not_matched: 'People leave the workflow when they no longer match the trigger filters.',
+ exit_on_conversion: 'People leave the workflow when they meet the conversion goal.',
+ exit_on_trigger_not_matched_or_conversion:
+ 'People leave the workflow when they no longer match the trigger filters, or when they meet the conversion goal.',
+}
+
+type TriggerType = NonNullable<HogFlow['trigger']>['type']
+// These triggers always match a registered trigger type, which supplies their label.
+type BuiltInTriggerType = Exclude<TriggerType, 'cohort' | 'data-warehouse-table' | 'data-warehouse-view'>
+
+const BUILT_IN_TRIGGER_LABELS: Record<BuiltInTriggerType, string> = {
+ event: 'when they perform',
+ webhook: 'when a webhook is received',
+ manual: 'when someone runs it manually',
+ schedule: 'on a schedule',
+ tracking_pixel: 'when a tracking pixel loads',
+ batch: 'when a batch run starts',
+ 'internal-event': 'when PostHog records',
+}
+
+export function triggerLeadIn(trigger: HogFlow['trigger']): string {
+ if (!trigger) {
+ return 'No trigger is set up yet.'
+ }
+ const registered = getRegisteredTriggerTypes().find((t) => t.matchConfig?.(trigger))
+ if (registered) {
+ return `People enter this workflow on ${registered.label.toLowerCase()}`
+ }
+ return `People enter this workflow ${BUILT_IN_TRIGGER_LABELS[trigger.type as BuiltInTriggerType] ?? 'when the trigger fires'}`
+}
+
+export function triggerEventNames(trigger: HogFlow['trigger']): string[] {
+ if (!trigger || !('filters' in trigger) || !trigger.filters) {
+ return []
+ }
+ const filters = trigger.filters as { events?: { name?: string; id?: string }[]; actions?: { name?: string }[] }
+ return [...(filters.events ?? []), ...(filters.actions ?? [])]
+ .map((entry) => entry.name || ('id' in entry ? String(entry.id ?? '') : ''))
+ .filter(Boolean)
+}
+
+export function triggerPropertyFilters(trigger: HogFlow['trigger']): any[] {
+ if (!trigger || !('filters' in trigger) || !trigger.filters) {
+ return []
+ }
+ return (trigger.filters as { properties?: any[] }).properties ?? []
+}
+
+export function frequencySummary(workflow: Pick<HogFlow, 'trigger' | 'trigger_masking'>): string {
+ const hash = workflow.trigger_masking?.hash ?? null
+ const registered = workflow.trigger
+ ? getRegisteredTriggerTypes().find((t) => t.matchConfig?.(workflow.trigger))
+ : undefined
+ const option = (registered?.frequencyOptions ?? PERSON_FREQUENCY_OPTIONS).find((o) => o.value === hash)
+ if (!hash) {
+ return 'Every time the trigger fires'
+ }
+ const label = option?.label ?? 'Limited by a custom rule'
+ const ttlSeconds = workflow.trigger_masking?.ttl ?? null
+ const ttlLabel =
+ ttlSeconds === null
+ ? null
+ : (TTL_OPTIONS.find((o) => o.value === ttlSeconds)?.label ?? humanFriendlyDuration(ttlSeconds))
+ const base = option?.fixedTtl || !ttlLabel ? label : `${label} per ${ttlLabel}`
+ // With a threshold of N, the 1st, (N + 1)th, (2N + 1)th... matching events start a run.
+ const threshold = workflow.trigger_masking?.threshold ?? null
+ return threshold && threshold > 1 ? `${base}, then again every ${threshold} matching events` : base
+}
+
+type GoalEntity = { name?: string | null; id?: string | number | null }
+
+export function conversionGoalEvents(conversion: HogFlow['conversion']): string[] {
+ return (conversion?.events ?? [])
+ .flatMap((goal) => [
+ ...((goal.filters?.events ?? []) as GoalEntity[]).map((event) => event.name || String(event.id ?? '')),
+ ...((goal.filters?.actions ?? []) as GoalEntity[]).map(
+ (action) => action.name || (action.id != null ? `Action ${action.id}` : '')
+ ),
+ ])
+ .filter(Boolean)
+}
diff --git a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts
index b197f606e9be..c1fe82489f79 100644
--- a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts
+++ b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts
@@ -1,4 +1,4 @@
-import { MakeLogicType, afterMount, connect, kea, key, listeners, path, props, selectors } from 'kea'
+import { MakeLogicType, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { combineUrl } from 'kea-router'
@@ -447,11 +447,17 @@ const EMAIL_METRICS: EmailMetricName[] = [
]
const PUSH_METRICS: PushMetric[] = ['push_sent', 'push_skipped', 'push_failed', 'push_opened']
+// Every (step, metric) pair of a large workflow; the query's default limit is 100 rows.
+const MESSAGE_TOTALS_LIMIT = 10_000
export interface WorkflowMetricsSummaryLogicProps {
logicKey: string
id: string
appSourceId?: string
+ /** The overview reads the live config, not a staged draft, and skips the loaders only the Metrics tab shows. */
+ overview?: boolean
+ /** The range the Metrics tab opened with, so completed runs start on it rather than the default. */
+ defaultRange?: Pick<AppMetricsCommonParams, 'dateFrom' | 'dateTo' | 'interval'>
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -469,12 +475,14 @@ export interface workflowMetricsSummaryLogicValues {
} // appMetricsLogic
getSingleTrendSeries: (name: string, previousPeriod?: boolean) => AppMetricsTimeSeriesResponse | null // appMetricsLogic
params: Partial<AppMetricsCommonParams> // appMetricsLogic
+ originalWorkflow: HogFlow | null // workflowLogic
workflow: HogFlow // workflowLogic
conversionRate: number
conversionStats: {
conversions: number
started: number
}
+ conversionStatsFailed: boolean
conversionStatsLoading: boolean
convertedUsersUrl: string
emailActions: ({
@@ -544,6 +552,7 @@ export interface workflowMetricsSummaryLogicValues {
inProgressTotal: number
inProgressTotalLoading: boolean
loading: boolean
+ messageTotalsFailed: boolean
messagingChannels: {
hasEmail: boolean
hasPush: boolean
@@ -601,6 +610,7 @@ export interface workflowMetricsSummaryLogicValues {
pushTotalsByActionId: Record<string, Partial<Record<PushMetric, number>>>
pushTotalsByActionIdLoading: boolean
sentSummaryLabel: string
+ sourceWorkflow: HogFlow
summaryMetricKeys: WorkflowSummaryMetric[]
workflowSummaryTrends: AppMetricsTimeSeriesResponse | null
}
@@ -710,8 +720,9 @@ export interface workflowMetricsSummaryLogicActions {
export interface workflowMetricsSummaryLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
+ sourceWorkflow: (workflow: HogFlow, originalWorkflow: HogFlow | null, arg: boolean | undefined) => HogFlow
loading: (appMetricsTrendsLoading: boolean, completedLoading: boolean) => boolean
- emailActions: (workflow: HogFlow) => ({
+ emailActions: (sourceWorkflow: HogFlow) => ({
config: {
inputs: Record<
string,
@@ -769,7 +780,7 @@ export interface workflowMetricsSummaryLogicMeta {
type: 'function_email'
updated_at?: number | undefined
} & Record<string, unknown>)[]
- pushActions: (workflow: HogFlow) => ({
+ pushActions: (sourceWorkflow: HogFlow) => ({
config: {
inputs: Record<
string,
@@ -818,7 +829,7 @@ export interface workflowMetricsSummaryLogicMeta {
updated_at?: number | undefined
} & Record<string, unknown>)[]
messagingChannels: (
- workflow: HogFlow,
+ sourceWorkflow: HogFlow,
appMetricsTrends: AppMetricsTimeSeriesResponse | null
) => {
hasEmail: boolean
@@ -829,13 +840,13 @@ export interface workflowMetricsSummaryLogicMeta {
appMetricsTrends: AppMetricsTimeSeriesResponse | null
) => Record<WorkflowSummaryMetric, string>
conversionRate: (conversionStats: { conversions: number; started: number }) => number
- hasConversionGoal: (workflow: HogFlow) => boolean
+ hasConversionGoal: (sourceWorkflow: HogFlow) => boolean
convertedUsersUrl: (
getDateRangeAbsolute: () => {
dateFrom: Dayjs
dateTo: Dayjs
diffMs: number
- },
+ }, // appMetricsLogic
arg: string
) => string
workflowSummaryTrends: (
@@ -845,7 +856,7 @@ export interface workflowMetricsSummaryLogicMeta {
getCompletedSingleTrendSeries: (
name: string,
previousPeriod?: boolean
- ) => AppMetricsTimeSeriesResponse | null,
+ ) => AppMetricsTimeSeriesResponse | null, // appMetricsLogic
messagingChannels: {
hasEmail: boolean
hasPush: boolean
@@ -981,7 +992,7 @@ export const workflowMetricsSummaryLogic = kea<workflowMetricsSummaryLogicType>(
connect((props: WorkflowMetricsSummaryLogicProps) => ({
values: [
workflowLogic,
- ['workflow'],
+ ['workflow', 'originalWorkflow'],
appMetricsLogic({ logicKey: props.logicKey }),
[
'appMetricsTrendsLoading',
@@ -992,9 +1003,10 @@ export const workflowMetricsSummaryLogic = kea<workflowMetricsSummaryLogicType>(
'getDateRangeAbsolute',
],
appMetricsLogic({
- logicKey: `workflow-completed-${props.appSourceId ?? props.id}`,
- loadOnMount: true,
- loadOnChanges: true,
+ logicKey: completedLogicKey(props),
+ loadOnMount: !props.overview,
+ loadOnChanges: !props.overview,
+ defaultParams: props.defaultRange,
forceParams: {
appSource: 'hog_flow',
appSourceId: props.appSourceId ?? props.id,
@@ -1023,6 +1035,7 @@ export const workflowMetricsSummaryLogic = kea<workflowMetricsSummaryLogicType>(
appSourceId: values.params.appSourceId,
breakdownBy: ['instance_id', 'metric_name'],
metricName: [...EMAIL_METRICS],
+ limit: MESSAGE_TOTALS_LIMIT,
dateFrom: dateRange.dateFrom.toISOString(),
dateTo: dateRange.dateTo.toISOString(),
}
@@ -1068,6 +1081,7 @@ export const workflowMetricsSummaryLogic = kea<workflowMetricsSummaryLogicType>(
appSourceId: values.params.appSourceId,
breakdownBy: ['instance_id', 'metric_name'],
metricName: [...PUSH_METRICS],
+ limit: MESSAGE_TOTALS_LIMIT,
dateFrom: dateRange.dateFrom.toISOString(),
dateTo: dateRange.dateTo.toISOString(),
}
@@ -1143,7 +1157,31 @@ export const workflowMetricsSummaryLogic = kea<workflowMetricsSummaryLogicType>(
},
],
})),
+ reducers({
+ messageTotalsFailed: [
+ false,
+ {
+ loadEmailTotalsFailure: () => true,
+ loadPushTotalsFailure: () => true,
+ loadEmailTotals: () => false,
+ loadPushTotals: () => false,
+ },
+ ],
+ conversionStatsFailed: [
+ false,
+ {
+ loadConversionStatsFailure: () => true,
+ loadConversionStats: () => false,
+ },
+ ],
+ }),
selectors({
+ sourceWorkflow: [
+ (s) => [s.workflow, s.originalWorkflow, (_, p: WorkflowMetricsSummaryLogicProps) => p.overview],
+ (workflow: HogFlow, originalWorkflow: HogFlow | null, overview: boolean | undefined): HogFlow =>
+ overview && originalWorkflow ? originalWorkflow : workflow,
+ ],
+
loading: [
(s) => [s.appMetricsTrendsLoading, s.completedLoading],
(appMetricsTrendsLoading: boolean, completedLoading: boolean) =>
@@ -1151,12 +1189,12 @@ export const workflowMetricsSummaryLogic = kea<workflowMetricsSummaryLogicType>(
],
emailActions: [
- (s) => [s.workflow],
+ (s) => [s.sourceWorkflow],
(workflow: import('./hogflows/types').HogFlow) => workflow.actions.filter(isEmailAction),
],
pushActions: [
- (s) => [s.workflow],
+ (s) => [s.sourceWorkflow],
(workflow: import('./hogflows/types').HogFlow) => workflow.actions.filter(isPushAction),
],
@@ -1165,7 +1203,7 @@ export const workflowMetricsSummaryLogic = kea<workflowMetricsSummaryLogicType>(
// date ranges (matching the step tables, which also key off configured actions), unioned with any
// channel that actually sent in the window so historical data from a since-deleted action still shows.
messagingChannels: [
- (s) => [s.workflow, s.appMetricsTrends],
+ (s) => [s.sourceWorkflow, s.appMetricsTrends],
(
workflow: import('./hogflows/types').HogFlow,
appMetricsTrends: AppMetricsTimeSeriesResponse | null
@@ -1210,7 +1248,7 @@ export const workflowMetricsSummaryLogic = kea<workflowMetricsSummaryLogicType>(
// Only surface the conversion tiles when a goal is actually configured — without one the
// backend never emits conversion metrics/events, so the tiles would always read empty.
hasConversionGoal: [
- (s) => [s.workflow],
+ (s) => [s.sourceWorkflow],
(workflow: import('./hogflows/types').HogFlow): boolean => {
const filters = workflow.conversion?.filters
const hasPropertyGoal = Array.isArray(filters) && filters.length > 0
@@ -1434,33 +1472,39 @@ export const workflowMetricsSummaryLogic = kea<workflowMetricsSummaryLogicType>(
],
}),
- afterMount(({ actions }) => {
+ afterMount(({ actions, props }) => {
actions.loadEmailTotals({})
- actions.loadEmailLinkTotals({})
actions.loadPushTotals({})
- actions.loadInProgressTotal({})
actions.loadConversionStats({})
+ if (!props.overview) {
+ actions.loadEmailLinkTotals({})
+ actions.loadInProgressTotal({})
+ }
}),
listeners(({ actions, values, props }) => ({
setParams: () => {
+ actions.loadEmailTotals({})
+ actions.loadPushTotals({})
+ actions.loadConversionStats({})
+ if (props.overview) {
+ return
+ }
// Sync date/interval params to the completed (run-level succeeded) logic
- const completedLogic = appMetricsLogic({
- logicKey: `workflow-completed-${props.appSourceId ?? props.id}`,
- })
- completedLogic.actions.setParams({
+ appMetricsLogic({ logicKey: completedLogicKey(props) }).actions.setParams({
interval: values.params.interval,
dateFrom: values.params.dateFrom,
dateTo: values.params.dateTo,
})
- actions.loadEmailTotals({})
actions.loadEmailLinkTotals({})
- actions.loadPushTotals({})
- actions.loadConversionStats({})
},
})),
])
+function completedLogicKey(props: WorkflowMetricsSummaryLogicProps): string {
+ return `workflow-completed-${props.overview ? 'overview-' : ''}${props.appSourceId ?? props.id}`
+}
+
function subtractSeriesValues(minuend: number[] | undefined, subtrahend: number[] | undefined, size: number): number[] {
return Array.from({ length: size }, (_, index) => Math.max(0, (minuend?.[index] ?? 0) - (subtrahend?.[index] ?? 0)))
}
diff --git a/products/workflows/frontend/Workflows/workflowSceneLogic.ts b/products/workflows/frontend/Workflows/workflowSceneLogic.ts
index a1e183739821..b4ab00bb0d27 100644
--- a/products/workflows/frontend/Workflows/workflowSceneLogic.ts
+++ b/products/workflows/frontend/Workflows/workflowSceneLogic.ts
@@ -8,7 +8,17 @@ import { urls } from 'scenes/urls'
import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'
import { ActivityScope, Breadcrumb } from '~/types'
-export const WorkflowTabs = ['workflow', 'invocations', 'metrics', 'self-driving', 'assets', 'history'] as const
+import { metricsRangeFromSearchParams } from './metricsDrillParams'
+
+export const WorkflowTabs = [
+ 'overview',
+ 'workflow',
+ 'invocations',
+ 'metrics',
+ 'self-driving',
+ 'assets',
+ 'history',
+] as const
export type WorkflowTab = (typeof WorkflowTabs)[number]
export interface WorkflowSceneLogicProps {
@@ -26,7 +36,7 @@ export interface workflowSceneLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface workflowSceneLogicActions {
setCurrentTab: (tab: WorkflowTab) => {
- tab: 'assets' | 'history' | 'invocations' | 'metrics' | 'self-driving' | 'workflow'
+ tab: 'assets' | 'history' | 'invocations' | 'metrics' | 'overview' | 'self-driving' | 'workflow'
}
}
@@ -117,9 +127,10 @@ export const workflowSceneLogic = kea<workflowSceneLogicType>([
// browser back/forward restore the selected step (its date range/interval stay untouched).
// Batch metrics render several per-job tables, so they keep their own local selection.
if (tab === 'metrics' && id && id !== 'new') {
- appMetricsLogic
- .findMounted({ logicKey: `hog-flow-metrics-${id}` })
- ?.actions.setParams({ instanceId: (searchParams.action as string) || undefined })
+ appMetricsLogic.findMounted({ logicKey: `hog-flow-metrics-${id}` })?.actions.setParams({
+ ...metricsRangeFromSearchParams(searchParams),
+ instanceId: (searchParams.action as string) || undefined,
+ })
}
},
})),
diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.ts
index 06afbd0dfee6..d324208aacc1 100644
--- a/products/workflows/frontend/generated/api.schemas.ts
+++ b/products/workflows/frontend/generated/api.schemas.ts
@@ -1151,6 +1151,30 @@ export interface PatchedHogFlowGraphUpdateApi {
operations?: HogFlowGraphOperationApi[]
}
+/**
+ * In-flight runs keyed by the id of the step they are on. Null when the count is unavailable.
+ * @nullable
+ */
+export type HogFlowInFlightApiByAction = { [key: string]: number } | null
+
+export interface HogFlowInFlightApi {
+ /**
+ * About how many runs are in flight (parked on a delay or wait, or executing). Null when the count is unavailable.
+ * @nullable
+ */
+ count: number | null
+ /**
+ * In-flight runs keyed by the id of the step they are on. Null when the count is unavailable.
+ * @nullable
+ */
+ by_action: HogFlowInFlightApiByAction
+ /**
+ * In-flight runs whose current step could not be read. Null when the count is unavailable.
+ * @nullable
+ */
+ position_unknown: number | null
+}
+
export interface HogInvocationResultApi {
invocation_id: string
status: string
diff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.ts
index 6c9afe80c772..1f9fb598fd3c 100644
--- a/products/workflows/frontend/generated/api.ts
+++ b/products/workflows/frontend/generated/api.ts
@@ -23,6 +23,7 @@ import type {
HogFlowApi,
HogFlowBatchJobApi,
HogFlowBatchJobCancelResponseApi,
+ HogFlowInFlightApi,
HogFlowInvocationApi,
HogFlowOptimizationApi,
HogFlowPublishRequestApi,
@@ -529,6 +530,21 @@ export const hogFlowsGraphPartialUpdate = async (
})
}
+export const getHogFlowsInFlightRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/hog_flows/${id}/in_flight/`
+}
+
+export const hogFlowsInFlightRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<HogFlowInFlightApi> => {
+ return apiMutator<HogFlowInFlightApi>(getHogFlowsInFlightRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getHogFlowsInvocationResultsRetrieveUrl = (
projectId: string,
id: string,
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 3daa5e5a701b..c7a955b4cead 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -55409,6 +55409,30 @@ export namespace Schemas {
edges?: HogFlowEdge[];
}
+ /**
+ * In-flight runs keyed by the id of the step they are on. Null when the count is unavailable.
+ * @nullable
+ */
+ export type HogFlowInFlightByAction = {[key: string]: number} | null;
+
+ export interface HogFlowInFlight {
+ /**
+ * About how many runs are in flight (parked on a delay or wait, or executing). Null when the count is unavailable.
+ * @nullable
+ */
+ count: number | null;
+ /**
+ * In-flight runs keyed by the id of the step they are on. Null when the count is unavailable.
+ * @nullable
+ */
+ by_action: HogFlowInFlightByAction;
+ /**
+ * In-flight runs whose current step could not be read. Null when the count is unavailable.
+ * @nullable
+ */
+ position_unknown: number | null;
+ }
+
/**
* Test trigger payload, typically {event, person, groups}. Shape it like the trigger's real payload: an event matching the trigger filters for event triggers, or for an internal-event trigger an event named in its filters.events (e.g. $slack_message_received with Slack properties like channel, user, text, ts) and no person.
*/