: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): require an email step to turn on self-driving (#117232)
Daniel Marchuk855263bc7846
diff --git a/products/workflows/backend/facade/contracts.py b/products/workflows/backend/facade/contracts.pyindex bcd83b487f24..b1a75272c732 100644--- a/products/workflows/backend/facade/contracts.py+++ b/products/workflows/backend/facade/contracts.py@@ -469,6 +469,8 @@ class WorkflowRef:trigger_type: str | Nonetrigger_filters: dict[str, Any]variables: list[dict[str, Any]] | None+ # Read from the published steps, not the draft.+ has_email_step: boolclass WorkflowNotFound(Exception):diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.pyindex d300f2e83166..dfc8449ac95e 100644--- a/products/workflows/backend/presentation/views/hog_flow.py+++ b/products/workflows/backend/presentation/views/hog_flow.py@@ -4022,6 +4022,15 @@ class WorkflowNotLiveError(exceptions.APIException):default_code = "workflow_not_live"+class WorkflowHasNoEmailStepError(exceptions.APIException):+ status_code = status.HTTP_409_CONFLICT+ default_detail = (+ "Self-driving only works on workflows that send email for now. "+ "Add an email step and publish the workflow to turn it on."+ )+ default_code = "workflow_has_no_email_step"++class WorkflowNotOptimisedError(exceptions.APIException):status_code = status.HTTP_409_CONFLICTdefault_detail = (@@ -5645,6 +5654,10 @@ class HogFlowViewSet(enabled = param_serializer.validated_data["enabled"]if enabled and instance.status != HogFlowState.ACTIVE:raise WorkflowNotLiveError()+ # Suggestions judge email opens and clicks. Turning it off stays open, so a workflow already+ # on can still be switched off after it loses its email step.+ if enabled and not instance.has_email_step:+ raise WorkflowHasNoEmailStepError()if enabled and not is_optimization_enabled(instance.id):refusal = suggestions_scout_refusal(self.team, acting_user=cast(User, request.user), may_grant=self._may_grant_scout(request)diff --git a/products/workflows/backend/services/hog_flow_reads.py b/products/workflows/backend/services/hog_flow_reads.pyindex a5456b394222..c9b11f77e960 100644--- a/products/workflows/backend/services/hog_flow_reads.py+++ b/products/workflows/backend/services/hog_flow_reads.py@@ -73,6 +73,9 @@ def get_workflow_ref(trigger_type=trigger.get("type"),trigger_filters=trigger.get("filters") or {},variables=flow.variables,+ has_email_step=any(+ isinstance(action, dict) and action.get("type") == "function_email" for action in flow.actions or []+ ),)diff --git a/products/workflows/backend/tests/api/test_workflow_proposals.py b/products/workflows/backend/tests/api/test_workflow_proposals.pyindex 033776c9be13..6da5822a387f 100644--- a/products/workflows/backend/tests/api/test_workflow_proposals.py+++ b/products/workflows/backend/tests/api/test_workflow_proposals.py@@ -1,4 +1,5 @@import json+from copy import deepcopyfrom datetime import UTC, datetimefrom types import SimpleNamespacefrom typing import Any@@ -45,6 +46,38 @@ def _trigger_action() -> dict:}+def _email_template() -> dict:+ template = deepcopy(webhook_template)+ template["id"] = "template-email"+ template["name"] = "Email"+ template["inputs_schema"] = [+ {"key": "email", "type": "native_email", "label": "Email", "required": True, "templating": "liquid"}+ ]+ return template+++def _email_action() -> dict:+ return {+ "id": "email_1",+ "name": "email_1",+ "type": "function_email",+ "config": {+ "template_id": "template-email",+ "inputs": {+ "email": {+ "value": {+ "to": "{{ person.properties.email }}",+ "from": "[email protected]",+ "subject": "Hello",+ "html": "<p>Hello</p>",+ },+ "templating": "liquid",+ }+ },+ },+ }++def _webhook_action(action_id: str = "action_1", url: str = "https://example.com") -> dict:return {"id": action_id,@@ -59,6 +92,7 @@ class TestWorkflowProposals(APIBaseTest):def setUp(self):super().setUp()sync_template_to_db(webhook_template)+ sync_template_to_db(_email_template())# Filing needs the scout's own scope, which no session carries.self.producer_key = generate_random_token_personal()PersonalAPIKey.objects.create(@@ -78,7 +112,8 @@ class TestWorkflowProposals(APIBaseTest):team_id = team_id or self.team.idcreate = self.client.post(f"/api/projects/{team_id}/hog_flows",- {"name": "Proposal Flow", "actions": [_trigger_action(), _webhook_action()]},+ {"name": "Proposal Flow", "actions": [_trigger_action(), _webhook_action(), _email_action()]},+ format="json",)assert create.status_code == 201, create.json()flow_id = create.json()["id"]@@ -558,6 +593,23 @@ class TestWorkflowProposals(APIBaseTest):assert turned_on.status_code == 409, turned_on.json()assert turned_on.json()["code"] == "workflow_not_live"+ def test_a_workflow_with_no_published_email_step_can_be_opted_out_but_not_back_in(self, _mock_flag):+ flow_id = self._create_active_flow()+ HogFlow.objects.filter(id=flow_id).update(+ actions=[_trigger_action(), _webhook_action()],+ draft={"actions": [_trigger_action(), _webhook_action(), _email_action()]},+ )+ url = f"/api/projects/{self.team.id}/hog_flows/{flow_id}/optimization"++ turned_off = self.client.post(url, {"enabled": False}, format="json")+ assert turned_off.status_code == 200, turned_off.json()+ assert turned_off.json()["enabled"] is False++ turned_on = self.client.post(url, {"enabled": True}, format="json")+ assert turned_on.status_code == 409, turned_on.json()+ assert turned_on.json()["code"] == "workflow_has_no_email_step"+ assert HogFlowOptimization.objects.for_team(self.team.id).get(hog_flow_id=flow_id).enabled is False+def test_a_workflow_nobody_opted_in_is_not_suggested_against(self, _mock_flag):flow_id = self._create_active_flow()self.client.post(@@ -1394,7 +1446,7 @@ class TestWorkflowProposals(APIBaseTest):assert approve.status_code == 200, approve.json()draft = HogFlow.objects.get(id=flow_id).draftassert draft is not None- assert [action["id"] for action in draft["actions"]] == ["trigger_node", "action_1"]+ assert [action["id"] for action in draft["actions"]] == ["trigger_node", "action_1", "email_1"]assert draft["actions"][1]["config"]["inputs"]["url"]["value"] == "https://proposed.example.com"def test_a_step_carries_only_the_fields_it_changes(self, _mock_flag):diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsMenuItem.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsMenuItem.tsxindex bd90935e5af2..8680bc1490d1 100644--- a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsMenuItem.tsx+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsMenuItem.tsx@@ -9,14 +9,11 @@ import { workflowLogic } from '../workflowLogic'import { workflowProposalsLogic } from './workflowProposalsLogic'export function WorkflowSuggestionsMenuItem({ id }: { id: string }): JSX.Element {- const { optimizationEnabled, optimizationLoading, optimizationUnreadable } = useValues(+ const { optimizationEnabled, optimizationLoading, optimizationUnreadable, turnOnDisabledReason } = useValues(workflowProposalsLogic({ id }))const { setOptimizationEnabled } = useActions(workflowProposalsLogic({ id }))- const { workflowUserAccessLevel, workflow } = useValues(workflowLogic({ id }))- // Only turning it on needs a live workflow; the server takes `enabled: false` either way. Blocking- // both would strand an opted-in workflow opted in the moment it is archived.- const notLive = !!workflow && workflow.status !== 'active' && !optimizationEnabled+ const { workflowUserAccessLevel } = useValues(workflowLogic({ id }))// A viewer cannot flip it, so the item is inert instead of a request that ends in an error toast.const accessDisabledReason = getAccessControlDisabledReason(@@ -28,7 +25,7 @@ export function WorkflowSuggestionsMenuItem({ id }: { id: string }): JSX.Elementreturn (<SceneMenuBarCheckboxItemchecked={optimizationEnabled}- disabled={optimizationLoading || optimizationUnreadable || !!accessDisabledReason || notLive}+ disabled={optimizationLoading || optimizationUnreadable || !!accessDisabledReason || !!turnOnDisabledReason}onCheckedChange={(checked) => setOptimizationEnabled(checked)}data-attr="workflow-menubar-suggest-improvements">diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsPanelToggle.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsPanelToggle.tsxindex ee24b12fe578..3b270a6f41ff 100644--- a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsPanelToggle.tsx+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsPanelToggle.tsx@@ -10,16 +10,11 @@ import { workflowLogic } from '../workflowLogic'import { workflowProposalsLogic } from './workflowProposalsLogic'export function WorkflowSuggestionsPanelToggle({ id }: { id: string }): JSX.Element {- const { optimizationEnabled, optimizationLoading, optimizationUnreadable } = useValues(+ const { optimizationEnabled, optimizationLoading, optimizationUnreadable, turnOnDisabledReason } = useValues(workflowProposalsLogic({ id }))const { setOptimizationEnabled } = useActions(workflowProposalsLogic({ id }))- const { workflowUserAccessLevel, workflow } = useValues(workflowLogic({ id }))- // Only turning it on needs a live workflow, so an archived workflow can still be switched off.- const notLiveReason =- !!workflow && workflow.status !== 'active' && !optimizationEnabled- ? 'Suggestions need a live workflow. Enable it first.'- : undefined+ const { workflowUserAccessLevel } = useValues(workflowLogic({ id }))return (<AccessControlAction@@ -35,10 +30,12 @@ export function WorkflowSuggestionsPanelToggle({ id }: { id: string }): JSX.Elemchecked={optimizationEnabled}onChange={(checked) => setOptimizationEnabled(checked)}// A failed read must not show "off" for a workflow that may be on.- disabled={optimizationLoading || optimizationUnreadable || !!disabledReason || !!notLiveReason}+ disabled={+ optimizationLoading || optimizationUnreadable || !!disabledReason || !!turnOnDisabledReason+ }tooltip={disabledReason ??- notLiveReason ??+ turnOnDisabledReason ??(optimizationUnreadable? 'Could not read whether suggestions are on for this workflow. Reload the page to try again.': 'PostHog reads how this workflow performs and suggests changes for you to review. Nothing reaches anyone until you approve a suggestion and publish it.')diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsSwitch.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsSwitch.tsxindex 5dfd62c5f468..af05da2d1bc6 100644--- a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsSwitch.tsx+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionsSwitch.tsx@@ -10,17 +10,11 @@ import { workflowLogic } from '../workflowLogic'import { workflowProposalsLogic } from './workflowProposalsLogic'export function WorkflowSuggestionsSwitch({ id }: { id: string }): JSX.Element {- const { optimizationEnabled, optimizationLoading, optimizationUnreadable } = useValues(+ const { optimizationEnabled, optimizationLoading, optimizationUnreadable, turnOnDisabledReason } = useValues(workflowProposalsLogic({ id }))const { setOptimizationEnabled } = useActions(workflowProposalsLogic({ id }))- const { workflowUserAccessLevel, originalWorkflow } = useValues(workflowLogic({ id }))- // A draft or archived workflow cannot be opted in; the switch stays visible and says why. Turning- // it off stays available, or archiving a workflow would strand it opted in.- const notLiveReason =- originalWorkflow && originalWorkflow.status !== 'active' && !optimizationEnabled- ? 'Suggestions need a live workflow. Enable it first.'- : undefined+ const { workflowUserAccessLevel } = useValues(workflowLogic({ id }))return (<AccessControlAction@@ -34,7 +28,7 @@ export function WorkflowSuggestionsSwitch({ id }: { id: string }): JSX.Element {const unreadableReason = optimizationUnreadable? 'Could not read whether suggestions are on for this workflow. Reload the page to try again.': undefined- const reason = disabledReason ?? notLiveReason ?? unreadableReason+ const reason = disabledReason ?? turnOnDisabledReason ?? unreadableReason// LemonSwitch's own tooltip covers only the knob, so the reason wraps the whole control.return (<Tooltip title={reason}>diff --git a/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.test.ts b/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.test.tsindex ae02e01dc167..a662ff2c5e93 100644--- a/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.test.ts+++ b/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.test.ts@@ -30,6 +30,8 @@ describe('workflowProposalsLogic', () => {let workflowStatus: stringlet workflowDraft: Record<string, any> | nulllet workflowDraftStamp: string | null+ let workflowActions: Record<string, any>[]+ let optimizationEnabled: booleanconst proposal = {id: PROPOSAL_ID,@@ -57,6 +59,8 @@ describe('workflowProposalsLogic', () => {workflowStatus = 'active'workflowDraft = { actions: [] }workflowDraftStamp = DRAFT_STAMP+ workflowActions = []+ optimizationEnabled = false;(LemonDialog.open as jest.Mock).mockClear()useMocks({get: {@@ -67,7 +71,7 @@ describe('workflowProposalsLogic', () => {name: 'Test',version: workflowVersion,status: workflowStatus,- actions: [],+ actions: workflowActions,edges: [],draft: workflowDraft,draft_updated_at: workflowDraftStamp,@@ -82,9 +86,14 @@ describe('workflowProposalsLogic', () => {? [200, { count: 1, results: [proposal] }]: [proposalsListStatus, { detail: 'nope' }]},+ '/api/projects/:team_id/hog_flows/:id/optimization/': () => [200, { enabled: optimizationEnabled }],'/api/projects/:team_id/hog_function_templates/': { results: [], count: 0 },},post: {+ '/api/projects/:team_id/hog_flows/:id/optimization/': () => [+ 409,+ { code: 'workflow_has_no_email_step', detail: 'Add an email step.' },+ ],'/api/projects/:team_id/hog_flows/:id/proposals/:proposal_id/approve/': async ({ request }) => {approveBodies.push((await request.json()) as Record<string, any>)return [approveStatus, approveStatus === 200 ? proposal : { code: 'stale_update' }]@@ -140,6 +149,72 @@ describe('workflowProposalsLogic', () => {expect(logic.values.pendingProposals).toEqual([])})+ it.each([+ {+ case: 'a live workflow with no email step',+ status: 'active',+ actions: [{ id: 'hook', type: 'function' }],+ enabled: false,+ reason: 'Self-driving only works on workflows that send email for now. Add an email step and publish the workflow to turn it on.',+ },+ {+ case: 'a workflow that is not live',+ status: 'draft',+ actions: [{ id: 'hook', type: 'function' }],+ enabled: false,+ reason: 'Suggestions need a live workflow. Enable it first.',+ },+ {+ case: 'a live workflow with an email step',+ status: 'active',+ actions: [{ id: 'mail', type: 'function_email' }],+ enabled: false,+ reason: undefined,+ },+ {+ case: 'a workflow already on with no email step',+ status: 'active',+ actions: [{ id: 'hook', type: 'function' }],+ enabled: true,+ reason: undefined,+ },+ ])('turning suggestions on for $case', async ({ status, actions, enabled, reason }) => {+ workflowStatus = status+ workflowActions = actions+ optimizationEnabled = enabled+ await expectLogic(logic, () => {+ logic.actions.loadOptimization()+ workflowLogic({ id: WORKFLOW_ID }).actions.loadWorkflow()+ }).toFinishAllListeners()++ expect(logic.values.turnOnDisabledReason).toBe(reason)+ })++ it('a 409 on turning suggestions on shows the reason and keeps unsaved edits until the workflow reloads', async () => {+ const flowLogic = workflowLogic({ id: WORKFLOW_ID })+ workflowActions = [{ id: 'mail', type: 'function_email' }]+ await expectLogic(logic, () => {+ flowLogic.actions.loadWorkflow()+ }).toFinishAllListeners()+ expect(logic.values.turnOnDisabledReason).toBeUndefined()++ flowLogic.actions.setAutoSaveEnabled(false)+ flowLogic.actions.setWorkflowValue('name', 'Unsaved edit')+ workflowActions = [{ id: 'hook', type: 'function' }]+ await expectLogic(logic, () => {+ logic.actions.setOptimizationEnabled(true)+ }).toFinishAllListeners()++ expect(flowLogic.values.workflow.name).toBe('Unsaved edit')+ expect(logic.values.optimizationEnabled).toBe(false)+ expect(logic.values.turnOnDisabledReason).toBe('Add an email step.')++ await expectLogic(logic, () => {+ flowLogic.actions.loadWorkflow()+ }).toFinishAllListeners()+ expect(logic.values.turnOnDisabledReason).toContain('Self-driving only works on workflows that send email')+ })+it('reloads the queue when the workflow version moves', async () => {const flowLogic = workflowLogic({ id: WORKFLOW_ID })flowLogic.mount()diff --git a/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.tsx b/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.tsxindex 184c4dba6fee..97a639b3c16e 100644--- a/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.tsx+++ b/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.tsx@@ -22,6 +22,7 @@ import type {WorkflowProposalApi,WorkflowProposalOutcomeApi,} from '../../generated/api.schemas'+import { isEmailAction } from '../hogflows/steps/types'import type { HogFlow } from '../hogflows/types'import { workflowLogic } from '../workflowLogic'@@ -68,6 +69,8 @@ export interface workflowProposalsLogicValues {rejectedResponseLoading: booleanresolvingAction: 'approve' | 'reject' | nullresolvingId: string | null+ turnOnDisabledReason: string | undefined+ turnOnRefusal: string | null}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -226,6 +229,9 @@ export interface workflowProposalsLogicActions {action: 'approve' | 'reject' | nullproposalId: string | null}+ setTurnOnRefusal: (reason: string) => {+ reason: string+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -238,6 +244,11 @@ export interface workflowProposalsLogicMeta {optimizationEnabled: (optimization: HogFlowOptimizationApi | null) => booleanpendingProposals: (proposalsResponse: PaginatedWorkflowProposalListApi | null) => WorkflowProposalApi[]approveDisabledReason: (hasUnsavedChanges: boolean, showDraftActions: boolean) => string | undefined+ turnOnDisabledReason: (+ originalWorkflow: HogFlow | null,+ optimizationEnabled: boolean,+ turnOnRefusal: string | null+ ) => string | undefined}}@@ -277,11 +288,22 @@ export const workflowProposalsLogic = kea<workflowProposalsLogicType>([clearOutcomes: () => ({}),setLastSeen: (version: number | null, draftStamp: string | null) => ({ version, draftStamp }),setOptimizationUnreadable: (unreadable: boolean) => ({ unreadable }),+ setTurnOnRefusal: (reason: string) => ({ reason }),reloadLists: true,setOptimizationEnabled: (enabled: boolean) => ({ enabled }),setOutcome: (proposalId: string, outcome: WorkflowProposalOutcomeApi) => ({ proposalId, outcome }),}),- reducers({+ reducers(({ props }) => ({+ // The server's reason for refusing to turn suggestions on, held until a fresh copy of the+ // workflow arrives. Reloading the workflow here would reset the form and drop unsaved edits.+ turnOnRefusal: [+ null as string | null,+ {+ setTurnOnRefusal: (_, { reason }) => reason,+ [workflowLogic({ id: props.id }).actionTypes.loadWorkflowSuccess]: () => null,+ [workflowLogic({ id: props.id }).actionTypes.saveWorkflowSuccess]: () => null,+ },+ ],// The server has resolved this one. Dropping it here means a reload that fails afterwards// cannot leave a resolved suggestion in the queue with live buttons.proposalsResponse: {@@ -353,7 +375,7 @@ export const workflowProposalsLogic = kea<workflowProposalsLogicType>([clearOutcomes: () => ({}),},],- }),+ })),loaders(({ actions, props, values }) => ({approvedResponse: [null as PaginatedWorkflowProposalListApi | null,@@ -436,6 +458,13 @@ export const workflowProposalsLogic = kea<workflowProposalsLogicType>([lemonToast.error(error.detail)return values.optimization}+ // A 409 means the published workflow changed since this page loaded (archived, or its+ // email step removed), so the toggles show the server's reason until the workflow reloads.+ if (error instanceof ApiError && error.status === 409 && error.detail) {+ lemonToast.error(error.detail)+ actions.setTurnOnRefusal(error.detail)+ return values.optimization+ }throw error}},@@ -498,6 +527,31 @@ export const workflowProposalsLogic = kea<workflowProposalsLogicType>([return undefined},],+ turnOnDisabledReason: [+ (s) => [s.originalWorkflow, s.optimizationEnabled, s.turnOnRefusal],+ (+ originalWorkflow: HogFlow | null,+ optimizationEnabled: boolean,+ turnOnRefusal: string | null+ ): string | undefined => {+ // Only turning it on is gated: the server always accepts turning it off, so a workflow that+ // is archived or loses its email step can still be switched off.+ if (!originalWorkflow || optimizationEnabled) {+ return undefined+ }+ if (turnOnRefusal) {+ return turnOnRefusal+ }+ if (originalWorkflow.status !== 'active') {+ return 'Suggestions need a live workflow. Enable it first.'+ }+ // The server judges the published steps, so an email step only in the draft does not count.+ if (!originalWorkflow.actions.some(isEmailAction)) {+ return 'Self-driving only works on workflows that send email for now. Add an email step and publish the workflow to turn it on.'+ }+ return undefined+ },+ ],}),listeners(({ actions, props, values }) => ({reloadLists: () => {