: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): add search to the email reputation endpoint and tab (#73437)
Meikel Ratzc9b27f471412
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex cd5cb0bc5604..5d962bda3246 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -3199,7 +3199,20 @@ class HogFlowViewSet(# this fans out the payload for every workflow listed.WORKFLOW_REPUTATION_HISTORY_DAYS = 7- @extend_schema(responses={200: TeamEmailReputationResponseSerializer})+ @extend_schema(+ parameters=[+ OpenApiParameter(+ "search",+ str,+ OpenApiParameter.QUERY,+ description=(+ "Case-insensitive workflow name filter. Applied before the worst-50 cap, so it "+ "finds workflows the unfiltered response cuts off."+ ),+ )+ ],+ responses={200: TeamEmailReputationResponseSerializer},+ )@action(detail=False, methods=["GET"], pagination_class=None, filter_backends=[], url_path="reputation")def team_reputation(self, request: Request, **kwargs) -> Response:"""@@ -3235,6 +3248,11 @@ class HogFlowViewSet(.order_by("hog_flow_id", "evaluated_at").select_related("hog_flow"))+ # Server-side by necessity: the response is capped to the worst 50 workflows, so filtering+ # client-side could never find a healthy workflow beyond the cap.+ search = (request.query_params.get("search") or "").strip()+ if search:+ workflow_rows = workflow_rows.filter(hog_flow__name__icontains=search)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 mypydiff --git a/products/workflows/backend/api/test/test_email_reputation.py b/products/workflows/backend/api/test/test_email_reputation.pyindex 2110650bf432..ccbd60833c09 100644--- a/products/workflows/backend/api/test/test_email_reputation.py+++ b/products/workflows/backend/api/test/test_email_reputation.py@@ -43,6 +43,22 @@ class TestEmailReputationAPI(APIBaseTest):assert response.status_code == status.HTTP_200_OKassert response.json() == {"reputation": None, "workflows": []}+ def test_reputation_endpoint_search_filters_before_the_cap(self):+ # A healthy workflow pushed past the worst-50 cap must still be findable by name+ needle = self._create_flow("Quarterly newsletter")+ self._create_snapshot(needle, RUN_2, state="healthy", bounce_rate=0.001)+ for i in range(55):+ noisy = self._create_flow(f"Blast {i}")+ self._create_snapshot(noisy, RUN_2, state="critical", bounce_rate=0.2)++ unfiltered = self.client.get(f"/api/projects/{self.team.id}/hog_flows/reputation").json()+ assert all(row["hog_flow_name"] != "Quarterly newsletter" for row in unfiltered["workflows"])++ searched = self.client.get(f"/api/projects/{self.team.id}/hog_flows/reputation?search=newsLETTER").json()+ assert [row["hog_flow_name"] for row in searched["workflows"]] == ["Quarterly newsletter"]+ # The team aggregate is unaffected by workflow search+ assert searched["reputation"] is None+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")diff --git a/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.tsx b/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.tsxindex 951ad18dbcf8..608fedfedf66 100644--- a/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.tsx+++ b/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.tsx@@ -1,6 +1,6 @@-import { useValues } from 'kea'+import { useActions, useValues } from 'kea'-import { LemonTable, LemonTag, LemonTagType, Link, Tooltip } from '@posthog/lemon-ui'+import { LemonInput, LemonTable, LemonTag, LemonTagType, Link, Tooltip } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'@@ -55,6 +55,23 @@ function formatRate(rate: number): string {return percentage(rate, 2, true)}+// Must match the evaluator's window config (nodejs/src/cdp/services/email-reputation: representative+// volume = max(1,000, 3× the biggest sending day), min window 24h, 30d lookback) and the endpoint's+// cap (HogFlowViewSet.WORKFLOW_REPUTATION_LIMIT).+const EVALUATION_WINDOW_TOOLTIP =+ 'Rates are calculated over your most recent sending: roughly 3 times your biggest sending day of the last 30 days (at least 1,000 emails, and at least the last 24 hours), so a single campaign never dominates the score. The window looks back up to 30 days.'+const WORKFLOW_LIMIT = 50++function MetricLabel({ label, tooltip }: { label: string; tooltip: string }): JSX.Element {+ return (+ <Tooltip title={tooltip}>+ <div className="text-secondary text-xs border-b border-dotted border-current inline-block cursor-default">+ {label}+ </div>+ </Tooltip>+ )+}+function TeamReputationCard({ reputation }: { reputation: EmailReputationSnapshotApi }): JSX.Element {return (<div className="border rounded p-4 bg-surface-primary">@@ -64,15 +81,18 @@ function TeamReputationCard({ reputation }: { reputation: EmailReputationSnapsho</div><div className="flex flex-wrap gap-8 mt-3"><div>- <div className="text-secondary text-xs">Bounce rate</div>+ <MetricLabel+ label="Bounce rate"+ tooltip="Hard (permanent) bounces divided by emails evaluated. Transient bounces like a full mailbox are not counted."+ /><div className="text-lg font-semibold">{formatRate(reputation.bounce_rate)}</div></div><div>- <div className="text-secondary text-xs">Spam complaint rate</div>+ <MetricLabel label="Spam complaint rate" tooltip="Spam complaints divided by emails evaluated." /><div className="text-lg font-semibold">{formatRate(reputation.complaint_rate)}</div></div><div>- <div className="text-secondary text-xs">Emails evaluated (recent volume)</div>+ <MetricLabel label="Emails evaluated (recent volume)" tooltip={EVALUATION_WINDOW_TOOLTIP} /><div className="text-lg font-semibold">{humanFriendlyNumber(reputation.emails_sent)}</div></div><div>@@ -131,7 +151,8 @@ function WorkflowHistoryTable({ history }: { history: readonly EmailReputationSn}export function WorkflowsReputation(): JSX.Element {- const { teamReputation, workflowSnapshots, reputationResponseLoading } = useValues(workflowsReputationLogic)+ const { teamReputation, workflowSnapshots, reputationResponseLoading, search } = useValues(workflowsReputationLogic)+ const { setSearch } = useActions(workflowsReputationLogic)return (<div className="space-y-4" data-attr="workflows-reputation">@@ -145,11 +166,31 @@ export function WorkflowsReputation(): JSX.Element {</div>))}+ <div className="flex items-center gap-3">+ <LemonInput+ type="search"+ placeholder="Search workflows"+ value={search}+ onChange={setSearch}+ className="max-w-80"+ data-attr="workflows-reputation-search"+ />+ {!search.trim() && workflowSnapshots.length >= WORKFLOW_LIMIT && (+ <span className="text-secondary text-xs">+ Showing the {WORKFLOW_LIMIT} workflows with the worst reputation. Search to find any other+ evaluated workflow.+ </span>+ )}+ </div><LemonTabledataSource={[...workflowSnapshots]}loading={reputationResponseLoading}rowKey={(snapshot) => snapshot.hog_flow_id}- emptyState="No workflows have sent enough email to be evaluated yet."+ emptyState={+ search.trim()+ ? 'No evaluated workflows match your search.'+ : 'No workflows have sent enough email to be evaluated yet.'+ }columns={[{title: 'Workflow',diff --git a/products/workflows/frontend/Workflows/Reputation/workflowsReputationLogic.ts b/products/workflows/frontend/Workflows/Reputation/workflowsReputationLogic.tsindex 2d5acf127a06..d40da570d7c2 100644--- a/products/workflows/frontend/Workflows/Reputation/workflowsReputationLogic.ts+++ b/products/workflows/frontend/Workflows/Reputation/workflowsReputationLogic.ts@@ -1,4 +1,4 @@-import { MakeLogicType, afterMount, connect, kea, path, selectors } from 'kea'+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'import { projectLogic } from 'scenes/projectLogic'@@ -15,13 +15,16 @@ export interface workflowsReputationLogicValues {currentProjectId: number | null // projectLogicreputationResponse: TeamEmailReputationResponseApi | nullreputationResponseLoading: boolean+ search: stringteamReputation: EmailReputationSnapshotApi | nullworkflowSnapshots: readonly WorkflowEmailReputationSnapshotApi[]}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface workflowsReputationLogicActions {- loadReputation: () => any+ loadReputation: () => {+ value: true+ }loadReputationFailure: (error: string,errorObject?: any@@ -31,10 +34,17 @@ export interface workflowsReputationLogicActions {}loadReputationSuccess: (reputationResponse: TeamEmailReputationResponseApi | null,- payload?: any+ payload?: {+ value: true+ }) => {reputationResponse: TeamEmailReputationResponseApi | null- payload?: any+ payload?: {+ value: true+ }+ }+ setSearch: (search: string) => {+ search: string}}@@ -60,19 +70,47 @@ export const workflowsReputationLogic = kea<workflowsReputationLogicType>([connect(() => ({values: [projectLogic, ['currentProjectId']],})),+ actions({+ // Declared here (as well as auto-created by the loader) so kea-typegen sees a payload-less+ // action; without this, TS types the first loader arg as required and callers fail typecheck.+ loadReputation: true,+ setSearch: (search: string) => ({ search }),+ }),+ reducers({+ search: [+ '',+ {+ setSearch: (_, { search }) => search,+ },+ ],+ }),loaders(({ values }) => ({reputationResponse: [null as TeamEmailReputationResponseApi | null,{- loadReputation: async () => {+ loadReputation: async (_, breakpoint) => {if (!values.currentProjectId) {return null}- return await hogFlowsReputationRetrieve(String(values.currentProjectId))+ const search = values.search.trim()+ const response = await hogFlowsReputationRetrieve(+ String(values.currentProjectId),+ search ? { search } : undefined+ )+ breakpoint() // a newer load superseded this one; discard the stale response+ return response},},],})),+ listeners(({ actions }) => ({+ // Search filters server-side (the response is capped to the worst 50 workflows), so each+ // keystroke needs a reload — debounced via the loader's own breakpoint on rapid typing.+ setSearch: async (_, breakpoint) => {+ await breakpoint(250)+ actions.loadReputation()+ },+ })),selectors({teamReputation: [(s) => [s.reputationResponse],diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.tsindex c3166b7f9c7f..ef4014719e91 100644--- a/products/workflows/frontend/generated/api.schemas.ts+++ b/products/workflows/frontend/generated/api.schemas.ts@@ -1526,3 +1526,10 @@ export type HogFlowsMetricsGlobalRetrieveParams = {*/before?: string}++export type HogFlowsReputationRetrieveParams = {+ /**+ * Case-insensitive workflow name filter. Applied before the worst-50 cap, so it finds workflows the unfiltered response cuts off.+ */+ search?: string+}diff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.tsindex 67842f01c263..06ef293a5a94 100644--- a/products/workflows/frontend/generated/api.ts+++ b/products/workflows/frontend/generated/api.ts@@ -32,6 +32,7 @@ import type {HogFlowsMetricsGlobalRetrieveParams,HogFlowsMetricsRetrieveParams,HogFlowsMetricsTotalsRetrieveParams,+ HogFlowsReputationRetrieveParams,HogFlowsRevisionsListParams,HogInvocationRerunRequestApi,HogInvocationRerunResponseApi,@@ -840,8 +841,20 @@ export const hogFlowsMetricsGlobalRetrieve = async (})}-export const getHogFlowsReputationRetrieveUrl = (projectId: string) => {- return `/api/projects/${projectId}/hog_flows/reputation/`+export const getHogFlowsReputationRetrieveUrl = (projectId: string, params?: HogFlowsReputationRetrieveParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/hog_flows/reputation/?${stringifiedParams}`+ : `/api/projects/${projectId}/hog_flows/reputation/`}/**@@ -851,9 +864,10 @@ export const getHogFlowsReputationRetrieveUrl = (projectId: string) => {*/export const hogFlowsReputationRetrieve = async (projectId: string,+ params?: HogFlowsReputationRetrieveParams,options?: RequestInit): Promise<TeamEmailReputationResponseApi> => {- return apiMutator<TeamEmailReputationResponseApi>(getHogFlowsReputationRetrieveUrl(projectId), {+ return apiMutator<TeamEmailReputationResponseApi>(getHogFlowsReputationRetrieveUrl(projectId, params), {...options,method: 'GET',})diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 993922fff5a2..6888be2e5084 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -75259,6 +75259,13 @@ export namespace Schemas {before?: string;};+ export type HogFlowsReputationRetrieveParams = {+ /**+ * Case-insensitive workflow name filter. Applied before the worst-50 cap, so it finds workflows the unfiltered response cuts off.+ */+ search?: string;+ };+export type HogFunctionTemplatesListParams = {/*** Number of results to return per page.