: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): notify the workflow owner when a suggestion is filed (#116301)
Daniel Marchuk2e5393b86372
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex f9bfb7ecccfc..29c70944cc53 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -14295,9 +14295,9 @@ snapshots:scenes-app-settings-user--settings-user-navigation--light:hash: v1.k794b7964.a9dd8af9b416c2d8a1c70913c7ea232609ea0c1fc9f779402d8de6a78ffb1b5d.9yi1ULCkJCmYLH3hyYurF9MvWWVxabq4mQIN2ImI99oscenes-app-settings-user--settings-user-notifications--dark:- hash: v1.k794b7964.a879ca34ca0f02a82248ebf06bb6e2deeddc9bd075aed7a167c490ea661556e8.ZvHpr0yE1xjI_TSlTDytUUlT_X_szD4fojRGLxXaexs+ hash: v1.k794b7964.7ff881d5b3744cbe47fb402143301668b5fb624da10619a6b4c47eedf8c548b9.s75CAbF-SofJ_Af38F2iWb2VNc6XC73HtkIywqwqqHUscenes-app-settings-user--settings-user-notifications--light:- hash: v1.k794b7964.38fd0147097c11565c4ad7b363389759beef2f6973dbd8f100b29e067a633870.-DOy75hrnAVx6r9X776lVtFOabtJjpN3kFLtevy-uNU+ hash: v1.k794b7964.feb24cb91db6c323d5a8c9345968902be65a5cb6402b1882f655bac4e686632a.R-oUf-04-vBEEfIfdQlD641zJ23aBwDb2k12ETd-HV4scenes-app-settings-user--settings-user-profile--dark:hash: v1.k794b7964.e6aaa0fcadda4d366236c5c09d88fbcd6c5265ece7e0c24ec20227fbf42255cd.N5Vql8vhkVuOvXkNPT7nBCKGz-87ty2a-cu9Vwrfdqwscenes-app-settings-user--settings-user-profile--light:diff --git a/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsx b/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsxindex 9dbc8b347d9e..a3e509d42f9f 100644--- a/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsx+++ b/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsx@@ -77,6 +77,10 @@ export const REALTIME_NOTIFICATION_TYPE_META: Record<string, { label: string; delabel: 'Data quality check failures',description: 'When a data quality check on a warehouse table or view starts failing',},+ workflow_suggestion: {+ label: 'Workflow suggestions',+ description: 'When PostHog suggests a change to a workflow you set up',+ },}export function NotificationTitle({diff --git a/frontend/src/lib/components/NotificationsMenu/notificationToasts.tsx b/frontend/src/lib/components/NotificationsMenu/notificationToasts.tsxindex 4983c7dda22e..8a3d8efacda3 100644--- a/frontend/src/lib/components/NotificationsMenu/notificationToasts.tsx+++ b/frontend/src/lib/components/NotificationsMenu/notificationToasts.tsx@@ -12,6 +12,7 @@ import {IconNotification,IconPieChart,IconPlug,+ IconSparkles,IconStar,IconTrending,IconWarning,@@ -38,6 +39,7 @@ const NOTIFICATION_TYPE_ICONS: Record<string, { Icon: ComponentType<{ className?achievement_unlocked: { Icon: IconStar, color: 'text-warning' },subscription_nudge: { Icon: IconBell, color: 'text-primary' },data_quality_check_failure: { Icon: IconWarning, color: 'text-danger' },+ workflow_suggestion: { Icon: IconSparkles, color: 'text-primary' },}export function getNotificationIcon(notificationType: string, className: string = 'size-5'): JSX.Element {diff --git a/frontend/src/scenes/settings/user/UpdateEmailPreferences.tsx b/frontend/src/scenes/settings/user/UpdateEmailPreferences.tsxindex 02dc76d12b2b..14f7e064aad8 100644--- a/frontend/src/scenes/settings/user/UpdateEmailPreferences.tsx+++ b/frontend/src/scenes/settings/user/UpdateEmailPreferences.tsx@@ -14,6 +14,7 @@ import {Tooltip,} from '@posthog/lemon-ui'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { organizationLogic } from 'scenes/organizationLogic'import { userLogic } from 'scenes/userLogic'@@ -36,6 +37,7 @@ enum NotificationBlock {ApiKeyExposure = 'api-key-exposure',MaterializedViewSync = 'materialized-view-sync',AiEvaluationDisabled = 'ai-evaluation-disabled',+ WorkflowSuggestions = 'workflow-suggestions',}const NOTIFICATION_BLOCK_ORDER = Object.values(NotificationBlock)@@ -56,6 +58,7 @@ const NOTIFICATION_DEFAULTS: BooleanNotificationSettings = {all_weekly_digest_disabled: false,project_api_key_exposed: true,ai_evaluation_disabled: true,+ workflow_suggestions: true,materialized_view_sync_failed: false,materialized_view_sync_failed_daily: true,materialized_view_sync_failed_immediate: false,@@ -371,6 +374,7 @@ export function UpdateEmailPreferences(): JSX.Element {} = useActions(userLogic)const { currentOrganization, currentOrganizationLoading } = useValues(organizationLogic)const { searchParams } = useValues(router)+ const workflowSuggestionsEnabled = useFeatureFlag('SELF_OPTIMISING_WORKFLOWS')const highlight = searchParams.highlight as NotificationBlock | undefinedconst dataLoaded = !userLoading && !currentOrganizationLoading && !!user && !!currentOrganization@@ -621,6 +625,16 @@ export function UpdateEmailPreferences(): JSX.Element {/></div>),+ [NotificationBlock.WorkflowSuggestions]: (+ <div className="border rounded p-4">+ <SimpleSwitch+ setting="workflow_suggestions"+ label="Workflow suggestions"+ description="Get an email when PostHog suggests a change to a workflow you set up"+ dataAttr="workflow_suggestions_enabled"+ />+ </div>+ ),[NotificationBlock.MaterializedViewSync]: (<div className="border rounded p-4 space-y-3"><SimpleSwitch@@ -635,7 +649,9 @@ export function UpdateEmailPreferences(): JSX.Element {}const visibleBlocks = NOTIFICATION_BLOCK_ORDER.filter(- (block) => block !== NotificationBlock.Approvals || hasAvailableFeature(AvailableFeature.APPROVALS)+ (block) =>+ (block !== NotificationBlock.Approvals || hasAvailableFeature(AvailableFeature.APPROVALS)) &&+ (block !== NotificationBlock.WorkflowSuggestions || workflowSuggestionsEnabled))const highlightedBlock = highlight && visibleBlocks.includes(highlight) ? highlight : nullconst highlightRef = useRef<HTMLDivElement>(null)diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 562031f298b8..eafaff1395df 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -487,6 +487,7 @@ export interface NotificationSettings {data_pipeline_error_threshold?: numberproject_api_key_exposed?: booleanai_evaluation_disabled?: boolean+ workflow_suggestions?: booleanmaterialized_view_sync_failed?: booleanmaterialized_view_sync_failed_daily?: booleanmaterialized_view_sync_failed_immediate?: booleandiff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.pyindex 9887d72ba50b..50695e13fa29 100644--- a/posthog/api/test/test_user.py+++ b/posthog/api/test/test_user.py@@ -2495,6 +2495,7 @@ class TestUserAPI(APIBaseTest):"data_pipeline_error_threshold": 0.1,"project_api_key_exposed": True,"ai_evaluation_disabled": True,+ "workflow_suggestions": True,"materialized_view_sync_failed": True,"materialized_view_sync_failed_daily": True,"materialized_view_sync_failed_immediate": False,@@ -2522,6 +2523,7 @@ class TestUserAPI(APIBaseTest):"data_pipeline_error_threshold": 0.1,"project_api_key_exposed": True,"ai_evaluation_disabled": True,+ "workflow_suggestions": True,"materialized_view_sync_failed": True,"materialized_view_sync_failed_daily": True,"materialized_view_sync_failed_immediate": False,@@ -2797,6 +2799,7 @@ class TestUserAPI(APIBaseTest):"data_pipeline_error_threshold": 0.01, # Default value"project_api_key_exposed": True, # Default value"ai_evaluation_disabled": True, # Default value+ "workflow_suggestions": True, # Default value"materialized_view_sync_failed": False, # Default value"materialized_view_sync_failed_daily": True, # Default value"materialized_view_sync_failed_immediate": False, # Default valuediff --git a/posthog/models/user.py b/posthog/models/user.pyindex bca5559e0d07..c6fb978a7be6 100644--- a/posthog/models/user.py+++ b/posthog/models/user.py@@ -59,6 +59,7 @@ class Notifications(TypedDict, total=False):)project_api_key_exposed: boolai_evaluation_disabled: bool # One email each time an AI observability evaluation is auto-disabled+ workflow_suggestions: bool # Email when PostHog suggests a change to a workflow the user opted in or createdmaterialized_view_sync_failed: boolmaterialized_view_sync_failed_daily: bool # One digest a day summarizing failing viewsmaterialized_view_sync_failed_immediate: bool # One email each time a view starts failing@@ -89,6 +90,7 @@ NOTIFICATION_DEFAULTS: Notifications = {"data_pipeline_error_threshold": 0.01, # Default: notify when failure rate exceeds 1%"project_api_key_exposed": True, # Private project API key (secure API key) exposure alerts enabled by default"ai_evaluation_disabled": True, # Auto-disabled evaluation emails enabled by default+ "workflow_suggestions": True,"materialized_view_sync_failed": False, # Materialized view failure disabled by default"materialized_view_sync_failed_daily": True, # Digest is the default delivery once failures are turned on"materialized_view_sync_failed_immediate": False,diff --git a/posthog/templates/email/workflow_suggestion_filed.html b/posthog/templates/email/workflow_suggestion_filed.htmlnew file mode 100644index 000000000000..62c830592bd3--- /dev/null+++ b/posthog/templates/email/workflow_suggestion_filed.html@@ -0,0 +1,26 @@+{% extends "email/base.html" %}+{% block heading %}PostHog suggested a change to your workflow{% endblock %}+{% block section %}+ <!-- prettier-ignore -->+ <p>+ PostHog suggested a change to <b>{{ workflow_name }}</b> in project <b>{{ team_name }}</b>.+ </p>+ <p><b>{{ suggestion_title }}</b></p>+ <p>{{ suggestion_rationale }}</p>+ <p>Nothing changes until someone approves the suggestion and publishes the workflow.</p>+ <div class="mb mt text-center">+ <a class="button" href="{% absolute_uri suggestion_path %}">Review suggestion</a>+ </div>+ <div class="mt">+ <p>+ If the button above doesn't work, paste this link into your browser:+ <br />+ <a href="{% absolute_uri suggestion_path %}">{% absolute_uri suggestion_path %}</a>+ </p>+ </div>+{% endblock %}+{% block footer %}+ You get this email because suggestions are on for this workflow. You can turn these emails off in your+ <a href="{% absolute_uri '/settings/user-notifications' %}"+ target="_blank"><b>notification settings</b></a>.+{% endblock %}diff --git a/products/notifications/backend/facade/enums.py b/products/notifications/backend/facade/enums.pyindex 3acf216d718b..d68a14c001fe 100644--- a/products/notifications/backend/facade/enums.py+++ b/products/notifications/backend/facade/enums.py@@ -22,6 +22,7 @@ class NotificationType(str, Enum):MATERIALIZATION_FAILURE = "materialization_failure"NOTIFICATION_SETTINGS_CHANGED = "notification_settings_changed"DATA_QUALITY_CHECK_FAILURE = "data_quality_check_failure"+ WORKFLOW_SUGGESTION = "workflow_suggestion"class Priority(str, Enum):diff --git a/products/workflows/backend/facade/proposals.py b/products/workflows/backend/facade/proposals.pyindex 3599f90fd22e..c44995ef2ef6 100644--- a/products/workflows/backend/facade/proposals.py+++ b/products/workflows/backend/facade/proposals.py@@ -2,6 +2,7 @@from products.workflows.backend.metrics import HOG_FLOW_VERSION_APP_SOURCEfrom products.workflows.backend.services.proposal_approval import approve_proposal+from products.workflows.backend.services.proposal_notifications import notify_proposal_filedfrom products.workflows.backend.services.workflow_proposals import (PROPOSAL_MERGE_BY_ID_FIELDS,as_the_serializer_stores_it,@@ -36,6 +37,7 @@ __all__ = ["list_proposals","lock_proposal","merge_proposal_content",+ "notify_proposal_filed","proposal_conflicts","proposal_outcome","resolve_proposal",diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.pyindex afe8c3080914..55be1654e6b6 100644--- a/products/workflows/backend/presentation/views/hog_flow.py+++ b/products/workflows/backend/presentation/views/hog_flow.py@@ -216,6 +216,7 @@ from products.workflows.backend.facade.proposals import (list_proposals,lock_proposal,merge_proposal_content,+ notify_proposal_filed,proposal_conflicts,proposal_outcome,resolve_proposal,@@ -5394,6 +5395,7 @@ class HogFlowViewSet(# A retry names the suggestion it already made, which is still in someone's queue whatever the switch says now.retry_of = get_proposal_by_source_id(hog_flow_id=instance.id, source_id=source_id) if source_id else Noneif retry_of:+ self._notify_proposal_filed(retry_of.id)return Response(WorkflowProposalSerializer(retry_of, context={"hog_flow": instance}).data, status=status.HTTP_200_OK)@@ -5475,6 +5477,7 @@ class HogFlowViewSet()proposal = created.proposalif not created.created:+ self._notify_proposal_filed(proposal.id)return Response(WorkflowProposalSerializer(proposal, context={"hog_flow": instance}).data, status=status.HTTP_200_OK)@@ -5483,10 +5486,19 @@ class HogFlowViewSet(instance,{"proposal_id": str(proposal.id)},)+ self._notify_proposal_filed(proposal.id)return Response(WorkflowProposalSerializer(proposal, context={"hog_flow": instance}).data, status=status.HTTP_201_CREATED)+ def _notify_proposal_filed(self, proposal_id: uuid_mod.UUID) -> None:+ # Retries call this too, so a failed delivery is repaired; per-proposal keys stop a second send.+ try:+ notify_proposal_filed(team_id=self.team_id, proposal_id=proposal_id, filed_by_user_id=self._actor_id())+ except Exception as error:+ # A failed notification must not fail the filing: the suggestion is already stored and listed.+ capture_exception(error)+@extend_schema(parameters=[OpenApiParameter("proposal_id", OpenApiTypes.UUID, OpenApiParameter.PATH, description="Proposal to fetch.")diff --git a/products/workflows/backend/services/proposal_notifications.py b/products/workflows/backend/services/proposal_notifications.pynew file mode 100644index 000000000000..ad75ab42678a--- /dev/null+++ b/products/workflows/backend/services/proposal_notifications.py@@ -0,0 +1,144 @@+"""Tells one person when PostHog files a suggestion on a workflow, in the app and by email."""++import html+from uuid import UUID++import structlog++from posthog.email import EmailMessage, get_email_team_and_org_context, is_email_available+from posthog.helpers.email_utils import sanitize_display_name, sanitize_email_string+from posthog.models import Team, User+from posthog.models.activity_logging.activity_log import ActivityLog+from posthog.models.messaging import MessagingRecord+from posthog.models.organization_notification_lock import effective_notification_settings, notification_locks_for_users++from products.access_control.backend.facade.user_access_control import UserAccessControl+from products.notifications.backend.facade.api import (+ NotificationData,+ NotificationType,+ RecipientsResolver,+ TargetType,+ create_notification,+)+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow+from products.workflows.backend.models.workflow_proposal import WorkflowProposal++logger = structlog.get_logger(__name__)++EMAIL_SETTING = "workflow_suggestions"+++def _candidate_user_ids(hog_flow: HogFlow, filed_by_user_id: int | None) -> list[int]:+ # The opt-in has no column of its own; the workflow's activity log is where it records who turned it on.+ opted_in_by = (+ ActivityLog.objects.filter(+ team_id=hog_flow.team_id,+ scope="HogFlow",+ item_id=str(hog_flow.id),+ activity="optimization_enabled",+ user__isnull=False,+ was_impersonated=False,+ )+ .order_by("-created_at")+ .values_list("user_id", flat=True)+ .first()+ )+ # Last comes the person the scout files as: turning suggestions on for any workflow in the project made them that.+ candidates = [opted_in_by, hog_flow.created_by_id, filed_by_user_id]+ return list(dict.fromkeys(user_id for user_id in candidates if user_id is not None))+++def _recipient(team: Team, hog_flow: HogFlow, filed_by_user_id: int | None) -> User | None:+ for user_id in _candidate_user_ids(hog_flow, filed_by_user_id):+ user = team.all_users_with_access().filter(id=user_id, is_active=True).first()+ if user is None or not UserAccessControl(user=user, team=team).check_access_level_for_object(+ hog_flow, "viewer"+ ):+ continue+ # The in-app notification drops anyone without resource-level access, so a person who can see only+ # this workflow would get nothing; pass over them to the next candidate.+ if RecipientsResolver().filter_by_access_control([user.id], "hog_flow", team):+ return user+ return None+++def _defanged(text: str) -> str:+ # sanitize_email_string also HTML-escapes. Undo only that step, so the template escapes the text once+ # and the URLs in it stay broken for mail-client auto-linking.+ return html.unescape(sanitize_email_string(text))+++def _send_email(user: User, team: Team, hog_flow: HogFlow, proposal: WorkflowProposal, path: str) -> None:+ if not is_email_available(with_absolute_urls=True):+ return+ campaign_key = f"workflow_suggestion_{proposal.id}"+ # The transport dedupes per address, so a retry that resolves a different person would email them too.+ if MessagingRecord.objects.filter(campaign_key=campaign_key, sent_at__isnull=False).exists():+ return+ locks = notification_locks_for_users([user.id], organization_id=team.organization_id).get(user.id, {})+ if not effective_notification_settings(user, locks=locks).get(EMAIL_SETTING, True):+ return+ workflow_name = _defanged(+ sanitize_display_name(+ hog_flow.name or "",+ fallback="your workflow",+ context={"helper": "workflow_suggestion_email", "field": "workflow_name"},+ )+ )+ team_context = get_email_team_and_org_context(team=team)+ if "team_name" in team_context:+ team_context["team_name"] = _defanged(team_context["team_name"])+ message = EmailMessage(+ campaign_key=campaign_key,+ template_name="workflow_suggestion_filed",+ subject=f"PostHog suggested a change to {workflow_name}",+ template_context={+ "workflow_name": workflow_name,+ "suggestion_title": _defanged(proposal.title),+ "suggestion_rationale": _defanged(proposal.rationale),+ "suggestion_path": path,+ **team_context,+ },+ )+ message.add_user_recipient(user)+ message.send(send_async=True)+++def notify_proposal_filed(*, team_id: int, proposal_id: UUID, filed_by_user_id: int | None) -> None:+ proposal = (+ WorkflowProposal.objects.for_team(team_id)+ .select_related("hog_flow")+ .filter(id=proposal_id, status=WorkflowProposal.Status.SUGGESTED)+ .first()+ )+ if proposal is None:+ return+ hog_flow = proposal.hog_flow+ team = Team.objects.get(id=team_id)+ recipient = _recipient(team, hog_flow, filed_by_user_id)+ if recipient is None:+ logger.info("workflow_suggestion_notification.no_recipient", team_id=team_id, proposal_id=str(proposal_id))+ return++ path = f"/project/{team_id}/workflows/{hog_flow.id}/self-driving"+ try:+ create_notification(+ NotificationData(+ team_id=team_id,+ notification_type=NotificationType.WORKFLOW_SUGGESTION,+ title=f"New suggestion for {hog_flow.name or 'your workflow'}"[:100],+ body=proposal.title,+ target_type=TargetType.USER,+ target_id=str(recipient.id),+ resource_type="hog_flow",+ resource_id=str(hog_flow.id),+ source_url=path,+ idempotency_key=f"workflow_proposal:{proposal.id}",+ )+ )+ except Exception:+ logger.exception("workflow_suggestion_notification.in_app_failed", proposal_id=str(proposal_id))+ try:+ _send_email(recipient, team, hog_flow, proposal, path)+ except Exception:+ logger.exception("workflow_suggestion_notification.email_failed", proposal_id=str(proposal_id))diff --git a/products/workflows/backend/tests/api/test_workflow_proposals.py b/products/workflows/backend/tests/api/test_workflow_proposals.pyindex b821b6f5c6d4..a6dddc608f30 100644--- a/products/workflows/backend/tests/api/test_workflow_proposals.py+++ b/products/workflows/backend/tests/api/test_workflow_proposals.py@@ -6,17 +6,23 @@ from typing import Anyfrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch+from django.utils import timezone+from parameterized import parameterized+from posthog.constants import AvailableFeaturefrom posthog.models import Team, Userfrom posthog.models.activity_logging.activity_log import ActivityLog+from posthog.models.messaging import MessagingRecord, get_email_hashfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom products.access_control.backend.facade.user_access_control import UserAccessControl+from products.access_control.backend.models.access_control import AccessControlfrom products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATESfrom products.cdp.backend.templates.hog_function_template import sync_template_to_db+from products.notifications.backend.facade.testing import stored_notification_for_resourcefrom products.signals.backend.models import SignalScoutConfigfrom products.skills.backend.models.skills import LLMSkillfrom products.workflows.backend.models.hog_flow.hog_flow import HogFlow@@ -920,23 +926,136 @@ class TestWorkflowProposals(APIBaseTest):def test_repeat_source_id_returns_the_same_proposal(self, _mock_flag):flow_id = self._create_active_flow()- first = self._propose(flow_id, source_id="run:1:finding:webhook-url")+ with patch(+ "products.workflows.backend.services.proposal_notifications.create_notification",+ side_effect=RuntimeError("notification store unavailable"),+ ):+ first = self._propose(flow_id, source_id="run:1:finding:webhook-url")- again = self.client.post(+ for _ in range(2):+ again = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/",+ {+ "title": "Retry of the same finding",+ "rationale": "A retried agent run must not queue a second copy for the human.",+ "content": {"actions": [_trigger_action(), _webhook_action()]},+ "base_version": 1,+ "source_id": "run:1:finding:webhook-url",+ },+ format="json",+ headers={"authorization": f"Bearer {self.producer_key}"},+ )+ assert again.status_code == 200, again.json()+ assert again.json()["id"] == first["id"]+ assert WorkflowProposal.objects.for_team(self.team.id).filter(hog_flow_id=flow_id).count() == 1+ assert stored_notification_for_resource(resource_type="hog_flow", resource_id=flow_id).resolved_user_ids == [+ self.user.id+ ]++ def _member_who_opts_in(self, flow_id: str) -> User:+ member = User.objects.create_and_join(self.organization, "[email protected]", None)+ self.client.force_login(member)+ self._optimize(flow_id)+ self.client.force_login(self.user)+ return member++ @parameterized.expand(+ [+ ("the person who turned suggestions on", None, "[email protected]"),+ ("the creator once that person is deactivated", "deactivate", None),+ ("the creator once that person leaves the organization", "remove", None),+ ("the creator when that person can see only this workflow", "object_grant_only", None),+ ]+ )+ @patch("products.workflows.backend.services.proposal_notifications.is_email_available", return_value=True)+ @patch("products.workflows.backend.services.proposal_notifications.EmailMessage")+ def test_a_new_suggestion_notifies(+ self, _name: str, change: str | None, expected_email: str | None, mock_email, _mock_available, _mock_flag+ ):+ flow_id = self._create_active_flow(optimize=False)+ member = self._member_who_opts_in(flow_id)+ if change == "deactivate":+ member.is_active = False+ member.save()+ elif change == "remove":+ OrganizationMembership.objects.filter(user=member).delete()+ elif change == "object_grant_only":+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save()+ OrganizationMembership.objects.filter(user=self.user).update(level=OrganizationMembership.Level.ADMIN)+ AccessControl.objects.create(team=self.team, resource="hog_flow", resource_id=None, access_level="none")+ AccessControl.objects.create(+ team=self.team,+ resource="hog_flow",+ resource_id=flow_id,+ access_level="viewer",+ organization_member=OrganizationMembership.objects.get(user=member),+ )+ recipient = User.objects.get(email=expected_email) if expected_email else self.user+ HogFlow.objects.filter(id=flow_id).update(name="Verify at attacker.example.com")+ Team.objects.filter(id=self.team.id).update(name="Team at attacker.example.com")++ self._propose(flow_id, rationale="The open rate on https://evil.example.com/landing dropped.")++ notification = stored_notification_for_resource(resource_type="hog_flow", resource_id=flow_id)+ assert notification.resolved_user_ids == [recipient.id]+ assert notification.source_url == f"/project/{self.team.id}/workflows/{flow_id}/self-driving"+ mock_email.return_value.add_user_recipient.assert_called_once_with(recipient)+ context = mock_email.call_args.kwargs["template_context"]+ assert "https://evil.example.com" not in context["suggestion_rationale"]+ assert "attacker.example.com" not in context["workflow_name"]+ assert "attacker.example.com" not in context["team_name"]++ @patch("products.workflows.backend.services.proposal_notifications.is_email_available", return_value=True)+ @patch("products.workflows.backend.services.proposal_notifications.EmailMessage")+ def test_a_retry_after_the_recipient_changes_does_not_notify_someone_else(+ self, mock_email, _mock_available, _mock_flag+ ):+ flow_id = self._create_active_flow(optimize=False)+ member = self._member_who_opts_in(flow_id)+ proposal = self._propose(flow_id, source_id="run:1:finding:retry-identity")+ MessagingRecord.objects.create(+ email_hash=get_email_hash(member.email),+ campaign_key=f"workflow_suggestion_{proposal['id']}",+ sent_at=timezone.now(),+ )+ member.is_active = False+ member.save()+ mock_email.reset_mock()++ retry = self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/",{"title": "Retry of the same finding",- "rationale": "A retried agent run must not queue a second copy for the human.",+ "rationale": "The producer retried after a timeout.","content": {"actions": [_trigger_action(), _webhook_action()]},"base_version": 1,- "source_id": "run:1:finding:webhook-url",+ "source_id": "run:1:finding:retry-identity",},format="json",headers={"authorization": f"Bearer {self.producer_key}"},)- assert again.status_code == 200, again.json()- assert again.json()["id"] == first["id"]- assert WorkflowProposal.objects.for_team(self.team.id).filter(hog_flow_id=flow_id).count() == 1+ assert retry.status_code == 200, retry.json()++ mock_email.assert_not_called()+ notification = stored_notification_for_resource(resource_type="hog_flow", resource_id=flow_id)+ assert notification.resolved_user_ids == [member.id]++ @patch("products.workflows.backend.services.proposal_notifications.is_email_available", return_value=True)+ @patch("products.workflows.backend.services.proposal_notifications.EmailMessage")+ def test_turning_the_email_off_keeps_the_in_app_notification(self, mock_email, _mock_available, _mock_flag):+ self.user.partial_notification_settings = {"workflow_suggestions": False}+ self.user.save()+ flow_id = self._create_active_flow()++ self._propose(flow_id)++ assert stored_notification_for_resource(resource_type="hog_flow", resource_id=flow_id).resolved_user_ids == [+ self.user.id+ ]+ mock_email.assert_not_called()@parameterized.expand([