:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(workflows): email reputation API and flag-gated reputation tab (#68133)
Meikel Ratz2d6d98ed2055
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 5839fc1371a4..0aa3656ab257 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -538,6 +538,7 @@ export const FEATURE_FLAGS = {WEB_ANALYTICS_TILE_SKELETONS: 'web-analytics-tile-skeletons', // owner: @jordanm-posthog #team-web-analyticsWEB_ANALYTICS_TILE_TOGGLES: 'web-analytics-tile-toggles', // owner: @lricoy #team-web-analyticsWEB_ANALYTICS_TOOLTIP_COMPARISON_LABELS: 'web-analytics-tooltip-comparison-labels', // owner: @lricoy #team-web-analytics+ WORKFLOWS_EMAIL_REPUTATION: 'workflows-email-reputation', // owner: #team-workflowsWORKFLOWS_INTERNAL_EVENT_FILTERS: 'workflows-internal-event-filters', // owner: @haven #team-workflowsWORKFLOWS_PUSH_NOTIFICATIONS: 'workflows-push-notifications', // owner: #team-workflowsWORKFLOWS_SUPPRESSION_LIST: 'workflows-suppression-list', // owner: #team-workflowsdiff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex d18d708022a6..2d2a6b4b378e 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -584,6 +584,8 @@ SPECTACULAR_SETTINGS = {"products.ai_observability.backend.models.evaluation_reports.EvaluationReport.Frequency"),"HogFlowStatusEnum": "products.workflows.backend.models.hog_flow.hog_flow.HogFlow.State",+ "EmailReputationScopeEnum": "products.workflows.backend.models.email_reputation.EmailReputationSnapshot.Scope",+ "EmailReputationStateEnum": "products.workflows.backend.models.email_reputation.EmailReputationSnapshot.State","MCPAuthTypeEnum": "products.mcp_store.backend.models.AUTH_TYPE_CHOICES","MCPInstallationScopeEnum": ["personal", "shared"],"TaskRunStatusEnum": "products.tasks.backend.models.TaskRun.Status",diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex 578e08cb4bd2..14dc5726f0b6 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -83,6 +83,7 @@ from products.workflows.backend.api.message_assets import (fetch_message_asset_html,fetch_message_assets,)+from products.workflows.backend.models.email_reputation import EmailReputationSnapshotfrom products.workflows.backend.models.hog_flow.hog_flow import (BILLABLE_ACTION_TYPES,PERSON_DEPENDENT_ACTION_TYPES,@@ -837,6 +838,90 @@ class HogFlowScheduleSerializer(serializers.ModelSerializer):return super().update(instance, validated_data)+class EmailReputationSnapshotSerializer(serializers.ModelSerializer):+ """One email deliverability reputation snapshot (per workflow or per team, per daily evaluation run)."""++ scope = serializers.ChoiceField(+ choices=EmailReputationSnapshot.Scope.choices,+ read_only=True,+ help_text="'workflow' for a single workflow's reputation, 'team' for the project-wide aggregate.",+ )+ state = serializers.ChoiceField(+ choices=EmailReputationSnapshot.State.choices,+ read_only=True,+ help_text=(+ "'insufficient_data' (too few sends in the window to judge), 'healthy', 'warning' (over a "+ "warning threshold), or 'critical' (over a critical threshold)."+ ),+ )+ bounce_rate = serializers.FloatField(+ read_only=True,+ help_text="Hard (permanent) bounces / emails sent over the evaluated volume (0-1), matching AWS's account bounce rate — transient bounces are excluded.",+ )+ complaint_rate = serializers.FloatField(+ read_only=True, help_text="Spam complaints / emails sent over the evaluated volume (0-1)."+ )+ emails_sent = serializers.IntegerField(+ read_only=True,+ help_text=(+ "Emails in the evaluated window: at least the target's last day of sends and at least "+ "the configured representative volume (SES-style), whichever covers more. 0 means no "+ "recent sending."+ ),+ )+ evaluated_at = serializers.DateTimeField(+ read_only=True, help_text="When this snapshot was computed; one snapshot exists per target per run."+ )++ class Meta:+ model = EmailReputationSnapshot+ fields = [+ "scope",+ "state",+ "bounce_rate",+ "complaint_rate",+ "emails_sent",+ "evaluated_at",+ ]+ read_only_fields = fields+++class WorkflowEmailReputationSnapshotSerializer(EmailReputationSnapshotSerializer):+ """A workflow-scoped reputation snapshot, annotated with the workflow it belongs to."""++ hog_flow_id = serializers.UUIDField(read_only=True, help_text="The workflow this snapshot is for.")+ hog_flow_name = serializers.CharField(+ read_only=True, source="hog_flow.name", allow_null=True, help_text="Display name of the workflow."+ )+ history = serializers.SerializerMethodField(+ help_text="This workflow's snapshots from the last 7 days (oldest first, one per daily evaluation run), including the latest."+ )++ @extend_schema_field(EmailReputationSnapshotSerializer(many=True))+ def get_history(self, obj: EmailReputationSnapshot) -> list[dict]:+ rows = self.context.get("workflow_history", {}).get(obj.hog_flow_id, [])+ return list(EmailReputationSnapshotSerializer(rows, many=True).data)++ class Meta(EmailReputationSnapshotSerializer.Meta):+ fields = [*EmailReputationSnapshotSerializer.Meta.fields, "hog_flow_id", "hog_flow_name", "history"]+ read_only_fields = fields+++class TeamEmailReputationResponseSerializer(serializers.Serializer):+ reputation = EmailReputationSnapshotSerializer(+ allow_null=True,+ read_only=True,+ help_text="Latest project-wide email reputation snapshot across all workflows; null until first evaluated.",+ )+ workflows = WorkflowEmailReputationSnapshotSerializer(+ many=True,+ read_only=True,+ help_text=(+ "Latest snapshot per workflow, worst state and highest rates first, capped at the worst 50 workflows."+ ),+ )++class HogFlowMinimalSerializer(UserAccessControlSerializerMixin, serializers.ModelSerializer):created_by = UserBasicSerializer(read_only=True)@@ -1371,6 +1456,7 @@ class HogFlowViewSet("metrics","metrics_totals","metrics_global",+ "team_reputation","user_blast_radius","assets","asset_content",@@ -2187,6 +2273,103 @@ class HogFlowViewSet(return Response({"deleted": deleted_count})+ # Severity order for the worst-offender sort; complaint rate breaks ties first (it's the more+ # dangerous SES signal, with thresholds ~20x lower than bounce).+ _REPUTATION_STATE_SEVERITY = {+ EmailReputationSnapshot.State.CRITICAL: 0,+ EmailReputationSnapshot.State.WARNING: 1,+ EmailReputationSnapshot.State.HEALTHY: 2,+ EmailReputationSnapshot.State.INSUFFICIENT_DATA: 3,+ }++ # Cap the per-workflow breakdown: without it, hundreds of email workflows each carrying a+ # week of history make one unbounded response. Worst-first sorting means the cut tail is the+ # healthiest workflows.+ WORKFLOW_REPUTATION_LIMIT = 50+ # Workflows drop off the breakdown once the evaluator stops producing snapshots for them+ # (i.e. no sends within its lookback), so a long-dead sender's last bad rate isn't pinned+ # to the top of the list forever.+ WORKFLOW_REPUTATION_RECENCY_DAYS = 7+ # How far back each listed workflow's per-day history reaches. Deliberately short: history+ # ships inline on the reputation endpoint (workflows x days rows per response), so widening+ # this fans out the payload for every workflow listed.+ WORKFLOW_REPUTATION_HISTORY_DAYS = 7++ @extend_schema(responses={200: TeamEmailReputationResponseSerializer})+ @action(detail=False, methods=["GET"], pagination_class=None, filter_backends=[], url_path="reputation")+ def team_reputation(self, request: Request, **kwargs) -> Response:+ """+ Email deliverability reputation for this project: the latest project-wide snapshot and the+ latest recent snapshot per workflow (worst first, capped). Written daily by the Node+ evaluator; everything is null/empty until the first run.+ """+ # The project-wide aggregate pools ALL workflows' email (that's its point), so it can't be+ # filtered per object grant — only members with project-wide workflow read access get it.+ # Members holding just object-level grants still get their (filtered) per-workflow rows.+ can_read_all_workflows = self.user_access_control.check_access_level_for_resource("hog_flow", "viewer")++ # for_team(canonical=True): rows are keyed by the raw team_id the Node evaluator writes,+ # which may be a child environment id that canonical resolution would rewrite and miss.+ latest = (+ EmailReputationSnapshot.objects.for_team(self.team_id, canonical=True)+ .filter(hog_flow__isnull=True)+ .order_by("-evaluated_at")+ .first()+ if can_read_all_workflows+ else None+ )++ # One row per workflow per run over the history window, grouped in Python so each workflow+ # entry carries its recent history alongside the latest snapshot.+ now = timezone.now()+ workflow_rows = (+ EmailReputationSnapshot.objects.for_team(self.team_id, canonical=True)+ .filter(+ hog_flow__isnull=False,+ evaluated_at__gte=now - timedelta(days=self.WORKFLOW_REPUTATION_HISTORY_DAYS),+ )+ .order_by("hog_flow_id", "evaluated_at")+ .select_related("hog_flow")+ )+ history_by_flow: dict[uuid_mod.UUID, list[EmailReputationSnapshot]] = {}+ for row in workflow_rows:+ if row.hog_flow_id is None: # can't happen (hog_flow__isnull=False); narrows the nullable FK for mypy+ continue+ history_by_flow.setdefault(row.hog_flow_id, []).append(row)++ # Mirror metrics_global: only surface workflows the caller can see, so reputation doesn't+ # leak names/volumes of access-controlled workflows the list endpoint hides.+ accessible_ids = set(+ self.user_access_control.filter_queryset_by_access_level(self.get_queryset()).values_list("id", flat=True)+ )+ recency_cutoff = now - timedelta(days=self.WORKFLOW_REPUTATION_RECENCY_DAYS)+ workflow_snapshots = [+ rows[-1]+ for flow_id, rows in history_by_flow.items()+ if flow_id in accessible_ids and rows[-1].evaluated_at >= recency_cutoff+ ]+ # Sort by raw state string (not the State enum constructor, which raises on values a newer+ # evaluator may write before this code deploys); unknown states sort last.+ severity = {state.value: rank for state, rank in self._REPUTATION_STATE_SEVERITY.items()}+ workflow_snapshots.sort(+ key=lambda s: (+ severity.get(s.state, 99),+ -s.complaint_rate,+ -s.bounce_rate,+ )+ )+ workflow_snapshots = workflow_snapshots[: self.WORKFLOW_REPUTATION_LIMIT]++ return Response(+ TeamEmailReputationResponseSerializer(+ {+ "reputation": latest,+ "workflows": workflow_snapshots,+ },+ context={"workflow_history": history_by_flow},+ ).data+ )+@extend_schema(methods=["GET"], responses=HogFlowBatchJobSerializer(many=True))@extend_schema(methods=["POST"], request=HogFlowBatchJobSerializer, responses=HogFlowBatchJobSerializer)# GET returns a bare list (no pagination) and ignores the viewset's HogFlow filterset; disable both so thediff --git a/products/workflows/backend/api/test/test_email_reputation.py b/products/workflows/backend/api/test/test_email_reputation.pynew file mode 100644index 000000000000..2110650bf432--- /dev/null+++ b/products/workflows/backend/api/test/test_email_reputation.py@@ -0,0 +1,110 @@+from datetime import datetime, timedelta++from posthog.test.base import APIBaseTest++from django.utils import timezone++from rest_framework import status++from posthog.models import Team++from products.workflows.backend.models import EmailReputationSnapshot, HogFlow++RUN_2 = timezone.now().replace(microsecond=0) - timedelta(days=1)+RUN_1 = RUN_2 - timedelta(days=1)+STALE_RUN = RUN_2 - timedelta(days=30)+++class TestEmailReputationAPI(APIBaseTest):+ def _create_flow(self, name: str) -> HogFlow:+ return HogFlow.objects.create(+ team=self.team,+ name=name,+ status="active",+ trigger={"type": "event"},+ edges=[],+ actions=[],+ billable_action_types=["function_email"],+ )++ def _create_snapshot(self, hog_flow: HogFlow | None, evaluated_at: datetime, **kwargs) -> EmailReputationSnapshot:+ snapshot = EmailReputationSnapshot(+ team=self.team,+ hog_flow=hog_flow,+ scope=EmailReputationSnapshot.Scope.WORKFLOW if hog_flow else EmailReputationSnapshot.Scope.TEAM,+ evaluated_at=evaluated_at,+ **kwargs,+ )+ snapshot.save()+ return snapshot++ def test_reputation_endpoint_returns_empty_shape_before_first_evaluation(self):+ response = self.client.get(f"/api/projects/{self.team.id}/hog_flows/reputation")+ assert response.status_code == status.HTTP_200_OK+ assert response.json() == {"reputation": None, "workflows": []}++ def test_reputation_endpoint_returns_latest_history_and_worst_first_workflows(self):+ ok_flow = self._create_flow("Fine workflow")+ bad_flow = self._create_flow("Toxic workflow")+ stale_flow = self._create_flow("Long-dead workflow")++ # Two daily team runs: latest must win regardless of insertion order+ self._create_snapshot(None, RUN_2, state="warning", bounce_rate=0.03)+ self._create_snapshot(None, RUN_1, state="healthy", bounce_rate=0.01)++ # Per-workflow: only the latest run's snapshot per flow, sorted worst first+ self._create_snapshot(ok_flow, RUN_1, state="critical", bounce_rate=0.09)+ self._create_snapshot(ok_flow, RUN_2, state="healthy", bounce_rate=0.005)+ self._create_snapshot(bad_flow, RUN_2, state="critical", bounce_rate=0.08)+ # A workflow whose last snapshot predates the recency cutoff drops off the breakdown+ self._create_snapshot(stale_flow, STALE_RUN, state="critical", bounce_rate=0.5)++ response = self.client.get(f"/api/projects/{self.team.id}/hog_flows/reputation")+ assert response.status_code == status.HTTP_200_OK+ data = response.json()++ assert data["reputation"]["state"] == "warning"+ assert data["reputation"]["scope"] == "team"++ assert [(row["hog_flow_name"], row["state"]) for row in data["workflows"]] == [+ ("Toxic workflow", "critical"),+ ("Fine workflow", "healthy"),+ ]+ assert data["workflows"][0]["hog_flow_id"] == str(bad_flow.id)++ # Each workflow entry carries its own per-run history, oldest first+ assert [row["state"] for row in data["workflows"][1]["history"]] == ["critical", "healthy"]+ assert [row["state"] for row in data["workflows"][0]["history"]] == ["critical"]++ def test_reputation_endpoint_never_returns_other_teams_snapshots(self):+ other_team = Team.objects.create(organization=self.organization, name="other team")+ other_flow = HogFlow.objects.create(+ team=other_team,+ name="Other team workflow",+ status="active",+ trigger={"type": "event"},+ edges=[],+ actions=[],+ billable_action_types=["function_email"],+ )+ EmailReputationSnapshot(+ team=other_team,+ hog_flow=None,+ scope=EmailReputationSnapshot.Scope.TEAM,+ state="critical",+ bounce_rate=0.5,+ evaluated_at=RUN_2,+ ).save()+ EmailReputationSnapshot(+ team=other_team,+ hog_flow=other_flow,+ scope=EmailReputationSnapshot.Scope.WORKFLOW,+ state="critical",+ bounce_rate=0.5,+ evaluated_at=RUN_2,+ ).save()++ response = self.client.get(f"/api/projects/{self.team.id}/hog_flows/reputation")+ assert response.status_code == status.HTTP_200_OK+ # Nothing from the other team leaks: no aggregate, no workflow rows+ assert response.json() == {"reputation": None, "workflows": []}diff --git a/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.tsx b/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.tsxnew file mode 100644index 000000000000..951ad18dbcf8--- /dev/null+++ b/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.tsx@@ -0,0 +1,207 @@+import { useValues } from 'kea'++import { LemonTable, LemonTag, LemonTagType, Link, Tooltip } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'+import { urls } from 'scenes/urls'++import type {+ EmailReputationSnapshotApi,+ EmailReputationStateEnumApi,+ WorkflowEmailReputationSnapshotApi,+} from 'products/workflows/frontend/generated/api.schemas'++import { workflowsReputationLogic } from './workflowsReputationLogic'++// Descriptions must match the evaluator's default thresholds+// (nodejs/src/cdp/services/email-reputation/classifier.ts DEFAULT_THRESHOLDS).+const STATE_CONFIG: Record<EmailReputationStateEnumApi, { label: string; type: LemonTagType; tooltip: string }> = {+ healthy: {+ label: 'Healthy',+ type: 'success',+ tooltip:+ 'Hard bounce rate below 2% and spam complaint rate below 0.1%. Transient bounces (greylisting, mailbox full) are not counted.',+ },+ warning: {+ label: 'Warning',+ type: 'warning',+ tooltip:+ 'Hard bounce rate at or above 2%, or spam complaint rate at or above 0.1%. Review your recipient list before rates climb further.',+ },+ critical: {+ label: 'Critical',+ type: 'danger',+ tooltip:+ 'Hard bounce rate at or above 5%, or spam complaint rate at or above 0.5%. Sending at these rates puts email deliverability at risk.',+ },+ insufficient_data: {+ label: 'Not enough data',+ type: 'muted',+ tooltip: 'Fewer than 100 emails in the evaluated window, which is too few to judge reliably.',+ },+}++function StateTag({ state }: { state: EmailReputationStateEnumApi }): JSX.Element {+ const config = STATE_CONFIG[state] ?? STATE_CONFIG.insufficient_data+ return (+ <Tooltip title={config.tooltip}>+ <LemonTag type={config.type}>{config.label}</LemonTag>+ </Tooltip>+ )+}++function formatRate(rate: number): string {+ return percentage(rate, 2, true)+}++function TeamReputationCard({ reputation }: { reputation: EmailReputationSnapshotApi }): JSX.Element {+ return (+ <div className="border rounded p-4 bg-surface-primary">+ <div className="flex items-center gap-2">+ <h3 className="mb-0">Project email reputation</h3>+ <StateTag state={reputation.state} />+ </div>+ <div className="flex flex-wrap gap-8 mt-3">+ <div>+ <div className="text-secondary text-xs">Bounce rate</div>+ <div className="text-lg font-semibold">{formatRate(reputation.bounce_rate)}</div>+ </div>+ <div>+ <div className="text-secondary text-xs">Spam complaint rate</div>+ <div className="text-lg font-semibold">{formatRate(reputation.complaint_rate)}</div>+ </div>+ <div>+ <div className="text-secondary text-xs">Emails evaluated (recent volume)</div>+ <div className="text-lg font-semibold">{humanFriendlyNumber(reputation.emails_sent)}</div>+ </div>+ <div>+ <div className="text-secondary text-xs">Last evaluated</div>+ <div className="text-lg font-semibold">+ <TZLabel time={reputation.evaluated_at} />+ </div>+ </div>+ </div>+ </div>+ )+}++function WorkflowHistoryTable({ history }: { history: readonly EmailReputationSnapshotApi[] }): JSX.Element {+ return (+ <div className="py-1">+ <div className="text-secondary text-xs mb-1">Daily scores from the last 7 days</div>+ <LemonTable+ size="small"+ embedded+ dataSource={[...history].reverse()}+ rowKey={(snapshot) => snapshot.evaluated_at}+ columns={[+ {+ title: 'Evaluated',+ key: 'evaluated_at',+ render: (_, snapshot: EmailReputationSnapshotApi) => <TZLabel time={snapshot.evaluated_at} />,+ },+ {+ title: 'State',+ key: 'state',+ render: (_, snapshot: EmailReputationSnapshotApi) => <StateTag state={snapshot.state} />,+ },+ {+ title: 'Bounce rate',+ key: 'bounce_rate',+ align: 'right',+ render: (_, snapshot: EmailReputationSnapshotApi) => formatRate(snapshot.bounce_rate),+ },+ {+ title: 'Complaint rate',+ key: 'complaint_rate',+ align: 'right',+ render: (_, snapshot: EmailReputationSnapshotApi) => formatRate(snapshot.complaint_rate),+ },+ {+ title: 'Emails sent',+ key: 'emails_sent',+ align: 'right',+ render: (_, snapshot: EmailReputationSnapshotApi) => humanFriendlyNumber(snapshot.emails_sent),+ },+ ]}+ />+ </div>+ )+}++export function WorkflowsReputation(): JSX.Element {+ const { teamReputation, workflowSnapshots, reputationResponseLoading } = useValues(workflowsReputationLogic)++ return (+ <div className="space-y-4" data-attr="workflows-reputation">+ {teamReputation ? (+ <TeamReputationCard reputation={teamReputation} />+ ) : (+ !reputationResponseLoading && (+ <div className="border rounded p-4 text-secondary">+ No reputation data yet. Reputation is calculated daily from email bounces and spam complaints+ once your workflows start sending email.+ </div>+ )+ )}+ <LemonTable+ dataSource={[...workflowSnapshots]}+ loading={reputationResponseLoading}+ rowKey={(snapshot) => snapshot.hog_flow_id}+ emptyState="No workflows have sent enough email to be evaluated yet."+ columns={[+ {+ title: 'Workflow',+ key: 'workflow',+ render: (_, snapshot: WorkflowEmailReputationSnapshotApi) => (+ <Link to={urls.workflow(snapshot.hog_flow_id, 'workflow')} className="font-semibold">+ {snapshot.hog_flow_name || snapshot.hog_flow_id}+ </Link>+ ),+ },+ {+ title: 'State',+ key: 'state',+ render: (_, snapshot: WorkflowEmailReputationSnapshotApi) => (+ <StateTag state={snapshot.state} />+ ),+ },+ {+ title: 'Bounce rate',+ key: 'bounce_rate',+ align: 'right',+ render: (_, snapshot: WorkflowEmailReputationSnapshotApi) => formatRate(snapshot.bounce_rate),+ },+ {+ title: 'Complaint rate',+ key: 'complaint_rate',+ align: 'right',+ render: (_, snapshot: WorkflowEmailReputationSnapshotApi) =>+ formatRate(snapshot.complaint_rate),+ },+ {+ title: 'Emails sent',+ key: 'emails_sent',+ align: 'right',+ render: (_, snapshot: WorkflowEmailReputationSnapshotApi) =>+ humanFriendlyNumber(snapshot.emails_sent),+ },+ {+ title: 'Evaluated',+ key: 'evaluated_at',+ render: (_, snapshot: WorkflowEmailReputationSnapshotApi) => (+ <TZLabel time={snapshot.evaluated_at} />+ ),+ },+ ]}+ expandable={{+ rowExpandable: (snapshot: WorkflowEmailReputationSnapshotApi) => snapshot.history.length > 1,+ expandedRowRender: (snapshot: WorkflowEmailReputationSnapshotApi) => (+ <WorkflowHistoryTable history={snapshot.history} />+ ),+ }}+ />+ </div>+ )+}diff --git a/products/workflows/frontend/Workflows/Reputation/workflowsReputationLogic.ts b/products/workflows/frontend/Workflows/Reputation/workflowsReputationLogic.tsnew file mode 100644index 000000000000..2d5acf127a06--- /dev/null+++ b/products/workflows/frontend/Workflows/Reputation/workflowsReputationLogic.ts@@ -0,0 +1,91 @@+import { MakeLogicType, afterMount, connect, kea, path, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { projectLogic } from 'scenes/projectLogic'++import { hogFlowsReputationRetrieve } from 'products/workflows/frontend/generated/api'+import type {+ EmailReputationSnapshotApi,+ TeamEmailReputationResponseApi,+ WorkflowEmailReputationSnapshotApi,+} from 'products/workflows/frontend/generated/api.schemas'++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface workflowsReputationLogicValues {+ currentProjectId: number | null // projectLogic+ reputationResponse: TeamEmailReputationResponseApi | null+ reputationResponseLoading: boolean+ teamReputation: EmailReputationSnapshotApi | null+ workflowSnapshots: readonly WorkflowEmailReputationSnapshotApi[]+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface workflowsReputationLogicActions {+ loadReputation: () => any+ loadReputationFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadReputationSuccess: (+ reputationResponse: TeamEmailReputationResponseApi | null,+ payload?: any+ ) => {+ reputationResponse: TeamEmailReputationResponseApi | null+ payload?: any+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface workflowsReputationLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ teamReputation: (reputationResponse: TeamEmailReputationResponseApi | null) => EmailReputationSnapshotApi | null+ workflowSnapshots: (+ reputationResponse: TeamEmailReputationResponseApi | null+ ) => readonly WorkflowEmailReputationSnapshotApi[]+ }+}++export type workflowsReputationLogicType = MakeLogicType<+ workflowsReputationLogicValues,+ workflowsReputationLogicActions,+ Record<string, any>,+ workflowsReputationLogicMeta+>++export const workflowsReputationLogic = kea<workflowsReputationLogicType>([+ path(['products', 'workflows', 'frontend', 'Workflows', 'Reputation', 'workflowsReputationLogic']),+ connect(() => ({+ values: [projectLogic, ['currentProjectId']],+ })),+ loaders(({ values }) => ({+ reputationResponse: [+ null as TeamEmailReputationResponseApi | null,+ {+ loadReputation: async () => {+ if (!values.currentProjectId) {+ return null+ }+ return await hogFlowsReputationRetrieve(String(values.currentProjectId))+ },+ },+ ],+ })),+ selectors({+ teamReputation: [+ (s) => [s.reputationResponse],+ (response: TeamEmailReputationResponseApi | null): EmailReputationSnapshotApi | null =>+ response?.reputation ?? null,+ ],+ workflowSnapshots: [+ (s) => [s.reputationResponse],+ (response: TeamEmailReputationResponseApi | null): readonly WorkflowEmailReputationSnapshotApi[] =>+ response?.workflows ?? [],+ ],+ }),+ afterMount(({ actions }) => {+ actions.loadReputation()+ }),+])diff --git a/products/workflows/frontend/WorkflowsScene.tsx b/products/workflows/frontend/WorkflowsScene.tsxindex 69fa0c466f9f..a98d86309145 100644--- a/products/workflows/frontend/WorkflowsScene.tsx+++ b/products/workflows/frontend/WorkflowsScene.tsx@@ -8,6 +8,7 @@ import api from 'lib/api'import { AccessControlAction } from 'lib/components/AccessControlAction'import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'import { FEATURE_FLAGS, TeamMembershipLevel } from 'lib/constants'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { integrationsLogic } from 'lib/integrations/integrationsLogic'import { IconSlack, IconTwilio } from 'lib/lemon-ui/icons'import { LemonTab, LemonTabs } from 'lib/lemon-ui/LemonTabs'@@ -32,9 +33,10 @@ import { SuppressionScene } from './Suppression/SuppressionScene'import { MessageTemplatesTable } from './TemplateLibrary/MessageTemplatesTable'import { newWorkflowLogic } from './Workflows/newWorkflowLogic'import { NewWorkflowModal } from './Workflows/NewWorkflowModal'+import { WorkflowsReputation } from './Workflows/Reputation/WorkflowsReputation'import { WorkflowsTable } from './Workflows/WorkflowsTable'-const WORKFLOW_SCENE_TABS = ['workflows', 'library', 'channels', 'opt-outs', 'suppression'] as const+const WORKFLOW_SCENE_TABS = ['workflows', 'library', 'channels', 'opt-outs', 'suppression', 'reputation'] as constexport type WorkflowsSceneTab = (typeof WORKFLOW_SCENE_TABS)[number]export type WorkflowsSceneProps = {@@ -52,7 +54,7 @@ export interface workflowsSceneLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface workflowsSceneLogicActions {setCurrentTab: (tab: WorkflowsSceneTab) => {- tab: 'channels' | 'library' | 'opt-outs' | 'suppression' | 'workflows'+ tab: 'channels' | 'library' | 'opt-outs' | 'reputation' | 'suppression' | 'workflows'}}@@ -60,7 +62,9 @@ export interface workflowsSceneLogicActions {export interface workflowsSceneLogicMeta {__keaTypeGenInternalSelectorTypes: {logicProps: (arg: any) => any- breadcrumbs: (currentTab: 'channels' | 'library' | 'opt-outs' | 'suppression' | 'workflows') => Breadcrumb[]+ breadcrumbs: (+ currentTab: 'channels' | 'library' | 'opt-outs' | 'reputation' | 'suppression' | 'workflows'+ ) => Breadcrumb[]}}@@ -124,6 +128,9 @@ export const workflowsSceneLogic = kea<workflowsSceneLogicType>([if (possibleTab === 'suppression' && !values.featureFlags[FEATURE_FLAGS.WORKFLOWS_SUPPRESSION_LIST]) {possibleTab = 'workflows'}+ if (possibleTab === 'reputation' && !values.featureFlags[FEATURE_FLAGS.WORKFLOWS_EMAIL_REPUTATION]) {+ possibleTab = 'workflows'+ }if (possibleTab !== values.currentTab) {actions.setCurrentTab(possibleTab)@@ -146,6 +153,7 @@ export function WorkflowsScene(props: WorkflowsSceneProps = {}): JSX.Element {const { openSetupModal } = useActions(integrationsLogic)const { openNewCategoryModal } = useActions(optOutCategoriesLogic)const { showNewWorkflowModal } = useActions(newWorkflowLogic)+ const emailReputationEnabled = useFeatureFlag('WORKFLOWS_EMAIL_REPUTATION')const newChannelRestrictedReason = useRestrictedArea({scope: RestrictionScope.Project,minimumAccessLevel: TeamMembershipLevel.Admin,@@ -251,6 +259,16 @@ export function WorkflowsScene(props: WorkflowsSceneProps = {}): JSX.Element {},]: []),+ ...(emailReputationEnabled+ ? [+ {+ label: 'Reputation',+ key: 'reputation' as const,+ content: <WorkflowsReputation />,+ link: urls.workflows('reputation'),+ },+ ]+ : []),]return (diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.tsindex e0ebb03ca83f..9d57045572a4 100644--- a/products/workflows/frontend/generated/api.schemas.ts+++ b/products/workflows/frontend/generated/api.schemas.ts@@ -947,6 +947,100 @@ export interface WorkflowStatsRowApi {failed: number}+/**+ * * `workflow` - Workflow+ * * `team` - Team+ */+export type EmailReputationScopeEnumApi = (typeof EmailReputationScopeEnumApi)[keyof typeof EmailReputationScopeEnumApi]++export const EmailReputationScopeEnumApi = {+ Workflow: 'workflow',+ Team: 'team',+} as const++/**+ * * `insufficient_data` - Insufficient Data+ * * `healthy` - Healthy+ * * `warning` - Warning+ * * `critical` - Critical+ */+export type EmailReputationStateEnumApi = (typeof EmailReputationStateEnumApi)[keyof typeof EmailReputationStateEnumApi]++export const EmailReputationStateEnumApi = {+ InsufficientData: 'insufficient_data',+ Healthy: 'healthy',+ Warning: 'warning',+ Critical: 'critical',+} as const++/**+ * One email deliverability reputation snapshot (per workflow or per team, per daily evaluation run).+ */+export interface EmailReputationSnapshotApi {+ /** 'workflow' for a single workflow's reputation, 'team' for the project-wide aggregate.+ *+ * * `workflow` - Workflow+ * * `team` - Team */+ readonly scope: EmailReputationScopeEnumApi+ /** 'insufficient_data' (too few sends in the window to judge), 'healthy', 'warning' (over a warning threshold), or 'critical' (over a critical threshold).+ *+ * * `insufficient_data` - Insufficient Data+ * * `healthy` - Healthy+ * * `warning` - Warning+ * * `critical` - Critical */+ readonly state: EmailReputationStateEnumApi+ /** Hard (permanent) bounces / emails sent over the evaluated volume (0-1), matching AWS's account bounce rate — transient bounces are excluded. */+ readonly bounce_rate: number+ /** Spam complaints / emails sent over the evaluated volume (0-1). */+ readonly complaint_rate: number+ /** Emails in the evaluated window: at least the target's last day of sends and at least the configured representative volume (SES-style), whichever covers more. 0 means no recent sending. */+ readonly emails_sent: number+ /** When this snapshot was computed; one snapshot exists per target per run. */+ readonly evaluated_at: string+}++/**+ * A workflow-scoped reputation snapshot, annotated with the workflow it belongs to.+ */+export interface WorkflowEmailReputationSnapshotApi {+ /** 'workflow' for a single workflow's reputation, 'team' for the project-wide aggregate.+ *+ * * `workflow` - Workflow+ * * `team` - Team */+ readonly scope: EmailReputationScopeEnumApi+ /** 'insufficient_data' (too few sends in the window to judge), 'healthy', 'warning' (over a warning threshold), or 'critical' (over a critical threshold).+ *+ * * `insufficient_data` - Insufficient Data+ * * `healthy` - Healthy+ * * `warning` - Warning+ * * `critical` - Critical */+ readonly state: EmailReputationStateEnumApi+ /** Hard (permanent) bounces / emails sent over the evaluated volume (0-1), matching AWS's account bounce rate — transient bounces are excluded. */+ readonly bounce_rate: number+ /** Spam complaints / emails sent over the evaluated volume (0-1). */+ readonly complaint_rate: number+ /** Emails in the evaluated window: at least the target's last day of sends and at least the configured representative volume (SES-style), whichever covers more. 0 means no recent sending. */+ readonly emails_sent: number+ /** When this snapshot was computed; one snapshot exists per target per run. */+ readonly evaluated_at: string+ /** The workflow this snapshot is for. */+ readonly hog_flow_id: string+ /**+ * Display name of the workflow.+ * @nullable+ */+ readonly hog_flow_name: string | null+ /** This workflow's snapshots from the last 7 days (oldest first, one per daily evaluation run), including the latest. */+ readonly history: readonly EmailReputationSnapshotApi[]+}++export interface TeamEmailReputationResponseApi {+ /** Latest project-wide email reputation snapshot across all workflows; null until first evaluated. */+ readonly reputation: EmailReputationSnapshotApi | null+ /** Latest snapshot per workflow, worst state and highest rates first, capped at the worst 50 workflows. */+ readonly workflows: readonly WorkflowEmailReputationSnapshotApi[]+}+/*** Property filters to apply*/diff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.tsindex ed111d9229f1..9a4012c98ea4 100644--- a/products/workflows/frontend/generated/api.ts+++ b/products/workflows/frontend/generated/api.ts@@ -41,6 +41,7 @@ import type {PatchedHogFlowGraphUpdateApi,PatchedHogFlowScheduleApi,PatchedHogFlowTemplateApi,+ TeamEmailReputationResponseApi,WorkflowStatsRowApi,} from './api.schemas'@@ -772,6 +773,25 @@ export const hogFlowsMetricsGlobalRetrieve = async (})}+export const getHogFlowsReputationRetrieveUrl = (projectId: string) => {+ return `/api/projects/${projectId}/hog_flows/reputation/`+}++/**+ * Email deliverability reputation for this project: the latest project-wide snapshot and the+ * latest recent snapshot per workflow (worst first, capped). Written daily by the Node+ * evaluator; everything is null/empty until the first run.+ */+export const hogFlowsReputationRetrieve = async (+ projectId: string,+ options?: RequestInit+): Promise<TeamEmailReputationResponseApi> => {+ return apiMutator<TeamEmailReputationResponseApi>(getHogFlowsReputationRetrieveUrl(projectId), {+ ...options,+ method: 'GET',+ })+}+export const getHogFlowsUserBlastRadiusCreateUrl = (projectId: string) => {return `/api/projects/${projectId}/hog_flows/user_blast_radius/`}diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yamlindex b0e8d09e2ff3..42db81d5189d 100644--- a/products/workflows/mcp/tools.yaml+++ b/products/workflows/mcp/tools.yaml@@ -69,6 +69,9 @@ tools:hog-flows-publish-create:operation: hog_flows_publish_createenabled: false+ hog-flows-reputation-retrieve:+ operation: hog_flows_reputation_retrieve+ enabled: falsehog-flows-rerun-create:operation: hog_flows_rerun_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 4abf736a06e0..f2a1de383e95 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -22693,6 +22693,60 @@ export namespace Schemas {name: string;}+ /**+ * * `workflow` - Workflow+ * * `team` - Team+ */+ export type EmailReputationScopeEnum = typeof EmailReputationScopeEnum[keyof typeof EmailReputationScopeEnum];+++ export const EmailReputationScopeEnum = {+ Workflow: 'workflow',+ Team: 'team',+ } as const;++ /**+ * * `insufficient_data` - Insufficient Data+ * * `healthy` - Healthy+ * * `warning` - Warning+ * * `critical` - Critical+ */+ export type EmailReputationStateEnum = typeof EmailReputationStateEnum[keyof typeof EmailReputationStateEnum];+++ export const EmailReputationStateEnum = {+ InsufficientData: 'insufficient_data',+ Healthy: 'healthy',+ Warning: 'warning',+ Critical: 'critical',+ } as const;++ /**+ * One email deliverability reputation snapshot (per workflow or per team, per daily evaluation run).+ */+ export interface EmailReputationSnapshot {+ /** 'workflow' for a single workflow's reputation, 'team' for the project-wide aggregate.+ *+ * * `workflow` - Workflow+ * * `team` - Team */+ readonly scope: EmailReputationScopeEnum;+ /** 'insufficient_data' (too few sends in the window to judge), 'healthy', 'warning' (over a warning threshold), or 'critical' (over a critical threshold).+ *+ * * `insufficient_data` - Insufficient Data+ * * `healthy` - Healthy+ * * `warning` - Warning+ * * `critical` - Critical */+ readonly state: EmailReputationStateEnum;+ /** Hard (permanent) bounces / emails sent over the evaluated volume (0-1), matching AWS's account bounce rate — transient bounces are excluded. */+ readonly bounce_rate: number;+ /** Spam complaints / emails sent over the evaluated volume (0-1). */+ readonly complaint_rate: number;+ /** Emails in the evaluated window: at least the target's last day of sends and at least the configured representative volume (SES-style), whichever covers more. 0 means no recent sending. */+ readonly emails_sent: number;+ /** When this snapshot was computed; one snapshot exists per target per run. */+ readonly evaluated_at: string;+ }+/*** Highest htmlID suffix per element type, e.g. {"u_row": 1, "u_content_text": 2}.*/@@ -67658,6 +67712,48 @@ export namespace Schemas {limit: number;}+ /**+ * A workflow-scoped reputation snapshot, annotated with the workflow it belongs to.+ */+ export interface WorkflowEmailReputationSnapshot {+ /** 'workflow' for a single workflow's reputation, 'team' for the project-wide aggregate.+ *+ * * `workflow` - Workflow+ * * `team` - Team */+ readonly scope: EmailReputationScopeEnum;+ /** 'insufficient_data' (too few sends in the window to judge), 'healthy', 'warning' (over a warning threshold), or 'critical' (over a critical threshold).+ *+ * * `insufficient_data` - Insufficient Data+ * * `healthy` - Healthy+ * * `warning` - Warning+ * * `critical` - Critical */+ readonly state: EmailReputationStateEnum;+ /** Hard (permanent) bounces / emails sent over the evaluated volume (0-1), matching AWS's account bounce rate — transient bounces are excluded. */+ readonly bounce_rate: number;+ /** Spam complaints / emails sent over the evaluated volume (0-1). */+ readonly complaint_rate: number;+ /** Emails in the evaluated window: at least the target's last day of sends and at least the configured representative volume (SES-style), whichever covers more. 0 means no recent sending. */+ readonly emails_sent: number;+ /** When this snapshot was computed; one snapshot exists per target per run. */+ readonly evaluated_at: string;+ /** The workflow this snapshot is for. */+ readonly hog_flow_id: string;+ /**+ * Display name of the workflow.+ * @nullable+ */+ readonly hog_flow_name: string | null;+ /** This workflow's snapshots from the last 7 days (oldest first, one per daily evaluation run), including the latest. */+ readonly history: readonly EmailReputationSnapshot[];+ }++ export interface TeamEmailReputationResponse {+ /** Latest project-wide email reputation snapshot across all workflows; null until first evaluated. */+ readonly reputation: EmailReputationSnapshot | null;+ /** Latest snapshot per workflow, worst state and highest rates first, capped at the worst 50 workflows. */+ readonly workflows: readonly WorkflowEmailReputationSnapshot[];+ }+export interface TeamMergeTrendPoint {/** Start of the day bucket (team timezone), keyed on merged_at. */day: string;