: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): suggest onboarding workflows from project events on the empty state (#114369)
Meikel Ratz5c2cb1f88742
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 727cda8222b3..d176fe261ce1 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -644,6 +644,7 @@ export const FEATURE_FLAGS = {WORKFLOWS_AI_FIRST_NEW: 'workflows-ai-first-new', // owner: @mayteio #team-workflowsWORKFLOWS_BROADCAST_RECIPIENT_LISTS: 'workflows-broadcast-recipient-lists', // owner: @mayteio #team-workflowsWORKFLOWS_COHORT_CONDITIONS: 'workflows-cohort-conditions', // owner: @meikelmosby #team-workflows+ WORKFLOWS_DATA_SUGGESTIONS: 'workflows-data-suggestions', // owner: #team-workflows, suggests workflows built from the project's events on the empty stateWORKFLOWS_DELAY_UNTIL_DATE: 'workflows-delay-until-date', // owner: @dmarchuk #team-workflowsWORKFLOWS_EMAIL_MEDIA_LIBRARY: 'workflows-email-media-library', // owner: @mayteio #team-workflows, backs the email editor's Uploads tab with the media libraryWORKFLOWS_EMAIL_SENDER_ROTATION: 'workflows-email-sender-rotation', // owner: @arthurdedeus #team-workflowsdiff --git a/products/messaging/backend/facade/api.py b/products/messaging/backend/facade/api.pyindex bf2d377f12a0..703ae408106a 100644--- a/products/messaging/backend/facade/api.py+++ b/products/messaging/backend/facade/api.py@@ -2,7 +2,12 @@ from collections.abc import Callablefrom typing import Anyfrom uuid import UUID-from products.messaging.backend.facade.contracts import UnlayerNotConfiguredError, UnlayerRenderError+from products.messaging.backend.facade.contracts import (+ EmailTemplateContent,+ EmailTemplateSummary,+ UnlayerNotConfiguredError,+ UnlayerRenderError,+)from products.messaging.backend.remote_config import (PUSH_APP_ID_CONFIG_KEYS,build_push_config as build_push_app_ids,@@ -11,6 +16,8 @@ from products.messaging.backend.services import design_operations, design_validafrom products.messaging.backend.unlayer import render_design_html as render_unlayer_design__all__ = [+ "EmailTemplateContent",+ "EmailTemplateSummary","UnlayerNotConfiguredError","UnlayerRenderError","apply_design_operations",@@ -18,6 +25,7 @@ __all__ = ["find_template_ids_containing","get_template_email_content","is_push_integration_kind",+ "list_email_templates","render_design_html","rewrite_template_content","validate_design",@@ -51,6 +59,10 @@ def get_template_email_content(team_id: int, template_id: UUID) -> dict | None:return message_templates.get_email_content(team_id, template_id)+def list_email_templates(team_id: int, *, limit: int) -> list[EmailTemplateSummary]:+ return message_templates.list_email_summaries(team_id, limit=limit)++def find_template_ids_containing(text: str, *, team_ids: list[int] | None, template_id: str | None) -> list[UUID]:return message_templates.find_ids_containing(text, team_ids=team_ids, template_id=template_id)diff --git a/products/messaging/backend/facade/contracts.py b/products/messaging/backend/facade/contracts.pyindex 9e84ab7c192d..38ef926574ec 100644--- a/products/messaging/backend/facade/contracts.py+++ b/products/messaging/backend/facade/contracts.py@@ -1,3 +1,8 @@+from dataclasses import dataclass+from typing import Any+from uuid import UUID++class UnlayerError(Exception):pass@@ -8,3 +13,18 @@ class UnlayerNotConfiguredError(UnlayerError):class UnlayerRenderError(UnlayerError):pass+++@dataclass(frozen=True)+class EmailTemplateSummary:+ id: UUID+ name: str+ subject: str+++@dataclass(frozen=True)+class EmailTemplateContent:+ id: UUID+ name: str+ # The template's email body: subject, html, text and the editor design.+ email: dict[str, Any]diff --git a/products/messaging/backend/services/message_templates.py b/products/messaging/backend/services/message_templates.pyindex 696000e0fe39..885b66f760e5 100644--- a/products/messaging/backend/services/message_templates.py+++ b/products/messaging/backend/services/message_templates.py@@ -4,8 +4,10 @@ from typing import Anyfrom uuid import UUIDfrom django.db import models, transaction+from django.db.models.fields.json import KTfrom django.db.models.functions import Cast+from products.messaging.backend.facade.contracts import EmailTemplateSummaryfrom products.messaging.backend.models import MessageCategory, MessageTemplate@@ -15,6 +17,22 @@ def get_email_content(team_id: int, template_id: UUID) -> dict | None:return email_content if isinstance(email_content, dict) else None+def list_email_summaries(team_id: int, *, limit: int) -> list[EmailTemplateSummary]:+ """The team's newest email templates that have a subject and a body. Only the subject leaves the database, so a+ large saved design is never loaded for a listing."""+ rows = (+ MessageTemplate.objects.filter(team_id=team_id, deleted=False, type="email")+ .annotate(subject=KT("content__email__subject"), html=KT("content__email__html"))+ .exclude(subject__isnull=True)+ .exclude(subject="")+ .exclude(html__isnull=True)+ .exclude(html="")+ .order_by("-created_at")+ .values_list("id", "name", "subject")[:limit]+ )+ return [EmailTemplateSummary(id=id, name=name or "", subject=subject) for id, name, subject in rows]++def _templates(team_ids: list[int] | None) -> models.QuerySet[MessageTemplate]:queryset = MessageTemplate.objects.all()return queryset.filter(team_id__in=team_ids) if team_ids else querysetdiff --git a/products/workflows/backend/facade/contracts.py b/products/workflows/backend/facade/contracts.pyindex b1a75272c732..4338bcb6aac2 100644--- a/products/workflows/backend/facade/contracts.py+++ b/products/workflows/backend/facade/contracts.py@@ -656,6 +656,48 @@ class EmailDesignRenderFailed(Exception):pass+# pinned: analytics property values for the `workflows data suggestion*` events - renaming breaks dashboards+LifecycleStage = Literal["signup", "onboarding", "trial", "purchase", "churn_risk", "failure", "support", "other"]+# The step chips a suggestion card shows.+OutlineKind = Literal["email", "sms", "push", "slack", "webhook", "delay", "wait_until", "branch", "split", "action"]+DataSuggestionsStatus = Literal["ready", "generating", "ai_not_approved", "unavailable"]+++@frozen+class DataSuggestion:+ id: str+ name: str+ description: str+ reason: str+ trigger_event: str+ weekly_count: int+ stage: LifecycleStage+ step_outline: tuple[OutlineKind, ...]+++@frozen+class DataSuggestionsResult:+ status: DataSuggestionsStatus+ suggestions: tuple[DataSuggestion, ...]+ # The project's events that a build can wait on. Kept with the cards, so a build does not count events again.+ events: tuple[str, ...] = ()+++DataSuggestionBuildStatus = Literal["ready", "building", "failed"]+++@frozen+class BuiltSuggestion:+ status: DataSuggestionBuildStatus+ # Set only when the status is ready.+ workflow: dict[str, Any] | None = None+ uses_saved_template: bool = False+++class DataSuggestionNotFound(Exception):+ """The suggestion id is unknown, usually because the cached suggestions expired."""++class EmailDraftSourceNotFound(Exception):"""The project has no entity with that ID for the requested source."""diff --git a/products/workflows/backend/facade/data_suggestions.py b/products/workflows/backend/facade/data_suggestions.pynew file mode 100644index 000000000000..cd303cf8e04c--- /dev/null+++ b/products/workflows/backend/facade/data_suggestions.py@@ -0,0 +1,43 @@+"""Workflow ideas written by AI from a project's own events, and building one into a draft workflow."""++from posthog.event_usage import EventSource+from posthog.models import Team, User++from products.workflows.backend.facade.contracts import BuiltSuggestion, DataSuggestionsResult+from products.workflows.backend.services.data_suggestions import service+from products.workflows.backend.services.data_suggestions.service import (+ get_data_suggestions,+ needs_new_build,+ needs_new_generation,+)+from products.workflows.backend.tasks.data_suggestions import build_data_suggestion, generate_data_suggestions++__all__ = [+ "get_data_suggestions",+ "needs_new_build",+ "needs_new_generation",+ "start_build",+ "start_data_suggestions",+]+++def start_data_suggestions(*, team: Team, user: User, refresh: bool) -> DataSuggestionsResult:+ return service.start_data_suggestions(+ team=team,+ refresh=refresh,+ enqueue=lambda lock_token: generate_data_suggestions.delay(team.id, user.id, lock_token),+ )+++def start_build(+ *, team: Team, user: User, suggestion_id: str, retry: bool, event_source: EventSource+) -> BuiltSuggestion:+ return service.start_build(+ team=team,+ suggestion_id=suggestion_id,+ caller=event_source.value,+ retry=retry,+ enqueue=lambda lock_token: build_data_suggestion.delay(+ team.id, user.id, suggestion_id, lock_token, event_source.value+ ),+ )diff --git a/products/workflows/backend/presentation/views/data_suggestion_drafts.py b/products/workflows/backend/presentation/views/data_suggestion_drafts.pynew file mode 100644index 000000000000..a8f507aedd26--- /dev/null+++ b/products/workflows/backend/presentation/views/data_suggestion_drafts.py@@ -0,0 +1,30 @@+"""The check a built suggestion passes before anyone can save it as a draft."""++from typing import Any++import structlog+from rest_framework.exceptions import ValidationError++from posthog.event_usage import EventSource+from posthog.models import Team++from products.workflows.backend.presentation.views.graph_validation import validate_graph+from products.workflows.backend.presentation.views.hog_flow import HogFlowSerializer++logger = structlog.get_logger(__name__)+++def is_valid_draft(team: Team, workflow: dict[str, Any], event_source: EventSource) -> bool:+ # Checked the way the caller's own create request will be: the web editor saves drafts with blank inputs, an API+ # client's draft must be complete. The graph wiring is checked in full either way.+ serializer = HogFlowSerializer(+ data={**workflow, "status": "draft"},+ context={"team_id": team.id, "get_team": lambda: team, "is_draft": True, "event_source": event_source},+ )+ try:+ validate_graph(workflow["actions"], workflow["edges"])+ serializer.is_valid(raise_exception=True)+ except ValidationError as error:+ logger.info("workflows.data_suggestions.invalid_workflow", team_id=team.id, errors=str(error.detail)[:500])+ return False+ return Truediff --git a/products/workflows/backend/presentation/views/workflow_data_suggestions.py b/products/workflows/backend/presentation/views/workflow_data_suggestions.pynew file mode 100644index 000000000000..55238e3f40e7--- /dev/null+++ b/products/workflows/backend/presentation/views/workflow_data_suggestions.py@@ -0,0 +1,221 @@+from typing import Any++from django.db import models++import posthoganalytics+from drf_spectacular.utils import extend_schema+from rest_framework import serializers, viewsets+from rest_framework.decorators import action+from rest_framework.exceptions import NotFound, PermissionDenied+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.event_usage import get_event_source+from posthog.models import User+from posthog.rate_limit import AIBurstRateThrottle, AISustainedRateThrottle++from products.workflows.backend.facade.contracts import DataSuggestionNotFound+from products.workflows.backend.facade.data_suggestions import (+ get_data_suggestions,+ needs_new_build,+ needs_new_generation,+ start_build,+ start_data_suggestions,+)++# pinned: feature flag key - the frontend gates the same surfaces on it+FEATURE_FLAG_KEY = "workflows-data-suggestions"+++class DataSuggestionStepKind(models.TextChoices):+ EMAIL = "email"+ SMS = "sms"+ PUSH = "push"+ SLACK = "slack"+ WEBHOOK = "webhook"+ DELAY = "delay"+ WAIT_UNTIL = "wait_until"+ BRANCH = "branch"+ SPLIT = "split"+ ACTION = "action"+++class DataSuggestionStage(models.TextChoices):+ SIGNUP = "signup"+ ONBOARDING = "onboarding"+ TRIAL = "trial"+ PURCHASE = "purchase"+ CHURN_RISK = "churn_risk"+ FAILURE = "failure"+ SUPPORT = "support"+ OTHER = "other"+++class DataSuggestionsStatus(models.TextChoices):+ READY = "ready"+ GENERATING = "generating"+ AI_NOT_APPROVED = "ai_not_approved"+ UNAVAILABLE = "unavailable"+++class DataSuggestionSerializer(serializers.Serializer):+ id = serializers.CharField(help_text="Opaque id of this suggestion, valid while the suggestions stay cached.")+ name = serializers.CharField(help_text="Suggested workflow name, written by AI from the project's events.")+ description = serializers.CharField(help_text="One sentence on what the workflow does.")+ reason = serializers.CharField(help_text="One sentence on why the workflow fits this project.")+ trigger_event = serializers.CharField(help_text="The project event that starts the workflow.")+ weekly_count = serializers.IntegerField(help_text="How often the trigger event fired in the last 7 days.")+ stage = serializers.ChoiceField(+ choices=DataSuggestionStage.choices,+ help_text="The customer lifecycle stage the trigger event marks. Suggestions are ranked by stage first, "+ "so welcome and onboarding flows come before busier events.",+ )+ step_outline = serializers.ListField(+ child=serializers.ChoiceField(choices=DataSuggestionStepKind.choices),+ help_text="The main planned step kinds after the trigger, in order.",+ )+++class DataSuggestionsResponseSerializer(serializers.Serializer):+ status = serializers.ChoiceField(+ choices=DataSuggestionsStatus.choices,+ help_text="ready when suggestions were made (the list can still be empty), generating while a background "+ "run makes them (poll current until it ends), ai_not_approved when the organization has not approved AI "+ "data processing, unavailable when nothing was made or the run failed.",+ )+ suggestions = DataSuggestionSerializer(+ many=True, help_text="Up to 3 suggested workflows, ranked by lifecycle stage and then by weekly volume."+ )+++class DataSuggestionGenerateRequestSerializer(serializers.Serializer):+ refresh = serializers.BooleanField(+ default=False, help_text="Make new suggestions even when the cached ones are still valid."+ )+++class DataSuggestionBuildRequestSerializer(serializers.Serializer):+ suggestion_id = serializers.CharField(help_text="The id of a suggestion from the list endpoint.")+ retry = serializers.BooleanField(+ default=False,+ help_text="Start a new build when the last one failed. Leave it false when asking for a running build's status.",+ )+++class DataSuggestionBuildStatus(models.TextChoices):+ READY = "ready"+ BUILDING = "building"+ FAILED = "failed"+++class DataSuggestionBuildResponseSerializer(serializers.Serializer):+ status = serializers.ChoiceField(+ choices=DataSuggestionBuildStatus.choices,+ help_text="ready when the draft is built, building while a background build runs (call build again to "+ "check), failed when the plan did not produce a valid workflow. A failed result is reported once, so the "+ "next call starts a new build.",+ )+ workflow = serializers.JSONField(+ allow_null=True,+ help_text="With status ready: a validated draft workflow (name, description, trigger, actions, edges, "+ "conversion, exit_condition) that the workflow create endpoint accepts from this caller. Nothing is saved "+ "by this call. Null otherwise.",+ )+ uses_saved_template = serializers.BooleanField(help_text="Whether an email step reuses a saved email template.")+++class WorkflowDataSuggestionsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):+ """Workflow ideas written by AI from the project's own events. Both calls are free for the customer."""++ scope_object = "hog_flow"+ # These actions read the whole project and create drafts, so access to a single workflow is not enough.+ requires_resource_level_access = True+ scope_object_read_actions = ["current"]+ # Both calls can run ClickHouse and the models, so a read-only key cannot cause that spend.+ scope_object_write_actions = ["generate", "build"]++ def dangerously_get_required_scopes(self, request: Request, view: Any) -> list[str] | None:+ # The cards carry the project's event names and weekly counts, so a key also needs the scope that reads them.+ access = "read" if self.action in self.scope_object_read_actions else "write"+ return [f"hog_flow:{access}", "query:read"]++ def get_throttles(self):+ # The AI budget is per user and shared with other AI features, so only a call that can run the LLM counts+ # against it. A generate call answered from the cache does not.+ if (self.action == "build" and self._starts_build()) or (+ self.action == "generate" and self._starts_generation()+ ):+ return [AIBurstRateThrottle(), AISustainedRateThrottle()]+ return super().get_throttles()++ def _starts_build(self) -> bool:+ # Asking again while a build runs, or for a finished build, costs no model time, so only a new build counts.+ payload = DataSuggestionBuildRequestSerializer(data=self.request.data)+ return not payload.is_valid() or needs_new_build(+ team=self.team,+ suggestion_id=payload.validated_data["suggestion_id"],+ caller=get_event_source(self.request).value,+ retry=payload.validated_data["retry"],+ )++ def _starts_generation(self) -> bool:+ # Joining a run that is already going costs no model time, so it is not throttled. Invalid input is throttled.+ payload = DataSuggestionGenerateRequestSerializer(data=self.request.data)+ return not payload.is_valid() or needs_new_generation(team=self.team, refresh=payload.validated_data["refresh"])++ @extend_schema(operation_id="workflow_data_suggestions_current", responses={200: DataSuggestionsResponseSerializer})+ @action(detail=False, methods=["get"])+ def current(self, request: Request, **kwargs: Any) -> Response:+ self._user_with_feature(request)+ return Response(DataSuggestionsResponseSerializer(get_data_suggestions(team=self.team)).data)++ @extend_schema(+ operation_id="workflow_data_suggestions_generate",+ request=DataSuggestionGenerateRequestSerializer,+ responses={200: DataSuggestionsResponseSerializer},+ )+ @action(detail=False, methods=["post"])+ def generate(self, request: Request, **kwargs: Any) -> Response:+ user = self._user_with_feature(request)+ payload = DataSuggestionGenerateRequestSerializer(data=request.data)+ payload.is_valid(raise_exception=True)+ result = start_data_suggestions(team=self.team, user=user, refresh=payload.validated_data["refresh"])+ return Response(DataSuggestionsResponseSerializer(result).data)++ @extend_schema(+ operation_id="workflow_data_suggestions_build",+ request=DataSuggestionBuildRequestSerializer,+ responses={200: DataSuggestionBuildResponseSerializer},+ )+ @action(detail=False, methods=["post"])+ def build(self, request: Request, **kwargs: Any) -> Response:+ user = self._user_with_feature(request)+ payload = DataSuggestionBuildRequestSerializer(data=request.data)+ payload.is_valid(raise_exception=True)+ try:+ built = start_build(+ team=self.team,+ user=user,+ suggestion_id=payload.validated_data["suggestion_id"],+ retry=payload.validated_data["retry"],+ event_source=get_event_source(request),+ )+ except DataSuggestionNotFound:+ raise NotFound("This suggestion has expired. Refresh the page to get new ones.")+ return Response(DataSuggestionBuildResponseSerializer(built).data)++ def _user_with_feature(self, request: Request) -> User:+ user = request.user+ if (+ not isinstance(user, User)+ or not user.distinct_id+ or not posthoganalytics.feature_enabled(+ FEATURE_FLAG_KEY,+ user.distinct_id,+ groups={"organization": str(self.organization.id)},+ group_properties={"organization": {"id": str(self.organization.id)}},+ )+ ):+ raise PermissionDenied("This feature is not available.")+ return userdiff --git a/products/workflows/backend/routes.py b/products/workflows/backend/routes.pyindex 438ae2c2698d..10bc49281094 100644--- a/products/workflows/backend/routes.py+++ b/products/workflows/backend/routes.py@@ -11,6 +11,7 @@ from products.workflows.backend.presentation.views import (hog_flow_template,people_imports,workflow_classifications,+ workflow_data_suggestions,workflow_scout_runs,workflow_tasks,)@@ -30,6 +31,12 @@ def register_routes(routers: RouterRegistry) -> None:routers.projects.register(r"workflow_tasks", workflow_tasks.WorkflowTaskViewSet, "project_workflow_tasks", ["team_id"])+ routers.projects.register(+ r"workflow_data_suggestions",+ workflow_data_suggestions.WorkflowDataSuggestionsViewSet,+ "project_workflow_data_suggestions",+ ["team_id"],+ )routers.projects.register(r"workflow_scout_runs",workflow_scout_runs.WorkflowScoutRunViewSet,diff --git a/products/workflows/backend/services/data_suggestions/README.md b/products/workflows/backend/services/data_suggestions/README.mdnew file mode 100644index 000000000000..98c0b350957a--- /dev/null+++ b/products/workflows/backend/services/data_suggestions/README.md@@ -0,0 +1,76 @@+# Data suggestions++Suggests workflows built from a project's own events, on the Workflows empty state.+Everything is behind the `workflows-data-suggestions` feature flag.++## How it works++Two background jobs do the work: one makes the cards, one builds a draft when someone clicks a card.+Both run as Celery tasks on the long-running queue, because a run can take minutes and must not hold a web request.++```text+page API (presentation/views) Celery task Redis+---- ------------------------ ----------- -----+generate ----------------> start_data_suggestions -------> run_data_suggestions -----> cards (7 days)+poll current every 2 s --> get_data_suggestions <-------------------------------------- cards++"Create workflow" --------> start_build ------------------> run_build ----------------> draft (1 hour)+poll build every 2 s ----> start_build <-------------------------------------------- draft+save draft through the normal hog flows create endpoint, then open the editor+```++Making the cards (`_suggest` in `service.py`):++1. Count the last 7 days of the project's events in ClickHouse.+2. Drop events a workflow already triggers on.+3. Ask Jev which lifecycle stage each event marks.+4. Rank by stage weight and volume, then ask Claude Sonnet for ideas.+5. Keep the best card per stage, up to 3, and cache them per team.++Building a draft (`_plan_and_build` in `service.py`):++1. Claude Opus plans a graph of up to 20 steps from the card, the step catalog, saved email templates and connected channels.+2. The builder turns the plan into a workflow and rejects plans that do not hold up.+3. The draft is checked the way the caller's own create request checks it.++## Files++| File | What it does |+| ----------------- | ------------------------------------------------------------------------------------------------------ |+| `service.py` | Runs both jobs: caching, locks, consent checks, and the order of the steps above. Start here. |+| `event_volume.py` | Counts events in ClickHouse. Samples large teams and recounts what the sample missed. |+| `stages.py` | Asks Jev for each event's lifecycle stage, with confidence rules. |+| `ranking.py` | Stage weights, scoring, and which events reach Jev and Claude. |+| `planner.py` | The two Claude prompts and the schemas Claude answers in. |+| `llm.py` | The shared Claude client: strict JSON schema output, free for the customer, reported to LLM analytics. |+| `builder.py` | Turns a plan into a workflow: graph checks, step configs, waits between emails, copy cleanup. |+| `email_design.py` | Renders a plain email (heading, paragraphs, unsubscribe link) with an editor design. |+| `team_context.py` | What the team already has: used triggers, channels, Slack, email sender, saved templates. |++Outside this folder:++| File | What it does |+| ------------------------------------------------- | ------------------------------------------------------------------------- |+| `facade/data_suggestions.py` | Connects the service to the Celery tasks. |+| `tasks/data_suggestions.py` | The two Celery tasks. |+| `presentation/views/workflow_data_suggestions.py` | The `current`, `generate` and `build` endpoints, scopes and AI throttles. |+| `presentation/views/data_suggestion_drafts.py` | The draft check, using the real workflow serializer. |+| `services/hog_flow_templates.py` | `list_step_templates`, the step catalog the planner may use. |+| `frontend/setupGuide/suggestions/` | The cards and the logic that polls and builds. |++## Things to know++- One run per team and one build per card and caller run at a time, through token locks in Redis.+ A run only skips writing its result when a newer run holds the lock, because reads can come from a replica.+- Failures show nothing, with no rules-based fallback.+ A failed run is cached as unavailable for 5 minutes, so an outage does not rerun the queries on every visit.+- Only calls that can start model spend count against the user's PostHog AI rate limit.+- No AI data processing consent, privacy mode, or no Jev configured means no cards.+- SMS and push are only offered when a provider is connected.+ Settings the model cannot know, like API keys and URLs, stay blank in the draft.++## Tests++- `test/test_data_suggestions.py`: the pure parts, with no endpoint calls (builder, email rendering, schema, ranking, Jev rules).+- `tests/api/test_workflow_data_suggestions.py`: the endpoints with real ClickHouse events and inline Celery. Jev and Claude are mocked.+- `frontend/setupGuide/suggestions/workflowDataSuggestionsLogic.test.ts`: polling and the build flow.diff --git a/products/workflows/backend/services/data_suggestions/__init__.py b/products/workflows/backend/services/data_suggestions/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/workflows/backend/services/data_suggestions/builder.py b/products/workflows/backend/services/data_suggestions/builder.pynew file mode 100644index 000000000000..0219d218af3d--- /dev/null+++ b/products/workflows/backend/services/data_suggestions/builder.py@@ -0,0 +1,363 @@+import re+from collections import deque+from typing import Any++import structlog++from posthog.dataclasses import frozen++from products.messaging.backend.facade.api import EmailTemplateContent+from products.workflows.backend.services.data_suggestions.email_design import EmailCopy, render_email+from products.workflows.backend.services.data_suggestions.planner import (+ MAX_PLANNED_STEPS,+ Channel,+ PlannedStep,+ PlannedWorkflow,+ WorkflowIdea,+)++logger = structlog.get_logger(__name__)++# Liquid and Hog tags in model-written copy would render against the recipient's person data.+_TEMPLATE_TAGS = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{[^{}]*\}", re.DOTALL)+_EXIT_ID = "exit_node"+_DEFAULT_MAX_WAIT = "3d"+++@frozen+class EmailSender:+ integration_id: int+ email: str+ name: str+++@frozen+class BuildContext:+ allowed_events: frozenset[str]+ step_template_ids: frozenset[str]+ channels: frozenset[Channel]+ email_templates: dict[str, EmailTemplateContent]+ sender: EmailSender | None+ slack_integration_id: int | None+ once_per_person: bool = False+++@frozen+class BuiltWorkflow:+ uses_saved_template: bool+ workflow: dict[str, Any]+++@frozen+class _Link:+ target: str | None+ type: str+ index: int | None = None+++def build_workflow(idea: WorkflowIdea, plan: PlannedWorkflow, context: BuildContext) -> BuiltWorkflow | None:+ """Turns a model-written plan into a draft workflow, or None when the plan does not hold up.++ Settings the model cannot know, like credentials, channels and filters, stay blank for the team to fill in.+ The draft cannot be enabled until they do, because enabling validates every step in full.+ """+ if idea.trigger_event not in context.allowed_events:+ _log_rejection("trigger event the project does not send", trigger_event=idea.trigger_event)+ return None+ if not plan.steps or len(plan.steps) > MAX_PLANNED_STEPS:+ _log_rejection("no steps or too many steps", step_count=len(plan.steps))+ return None+ steps = _with_waits_between_emails(plan.steps)+ steps_by_id = {step.id: step for step in steps}+ if len(steps_by_id) != len(steps) or plan.first_step not in steps_by_id:+ _log_rejection("duplicate step ids or unknown first step", first_step=plan.first_step)+ return None+ action_ids = {step.id: f"action_{index}_{step.type}" for index, step in enumerate(steps)}++ links: dict[str, list[_Link]] = {}+ for step in steps:+ step_links = _links(step)+ if step_links is None or any(link.target is not None and link.target not in steps_by_id for link in step_links):+ _log_rejection("step links to an unknown step", step_id=step.id, step_type=step.type)+ return None+ links[step.id] = step_links+ if not _is_acyclic_and_connected(plan.first_step, links):+ _log_rejection("loop or unreachable step")+ return None++ trigger_config = {+ "type": "event",+ "filters": {"events": [{"id": idea.trigger_event, "name": idea.trigger_event, "type": "events", "order": 0}]},+ }+ actions: list[dict[str, Any]] = [+ {"id": "trigger_node", "name": "Trigger", "description": "", "type": "trigger", "config": trigger_config}+ ]+ edges: list[dict[str, Any]] = [{"from": "trigger_node", "to": action_ids[plan.first_step], "type": "continue"}]+ uses_saved_template = False+ for step in steps:+ action = _build_step(step, action_ids[step.id], context)+ if action is None:+ _log_rejection(+ "step the builder cannot use", step_id=step.id, step_type=step.type, template_id=step.template_id+ )+ return None+ uses_saved_template = uses_saved_template or (step.type == "email" and bool(step.email_template_id))+ actions.append(action)+ for link in links[step.id]:+ edge: dict[str, Any] = {+ "from": action_ids[step.id],+ "to": action_ids[link.target] if link.target else _EXIT_ID,+ "type": link.type,+ }+ if link.index is not None:+ edge["index"] = link.index+ edges.append(edge)+ actions.append(+ {"id": _EXIT_ID, "name": "Exit", "description": "", "type": "exit", "config": {"reason": "Default exit"}}+ )++ return BuiltWorkflow(+ uses_saved_template=uses_saved_template,+ workflow={+ "name": clean_copy(idea.name)[:50],+ "description": clean_copy(idea.description),+ "trigger": trigger_config,+ "actions": actions,+ "edges": edges,+ "conversion": {"filters": [], "window_minutes": None},+ "exit_condition": "exit_only_at_end",+ # A person who repeats a welcome or onboarding event would otherwise start the whole sequence again.+ **(+ {"trigger_masking": {"hash": "{person.id}", "ttl": None, "threshold": None}}+ if context.once_per_person+ else {}+ ),+ },+ )+++def _log_rejection(reason: str, **details: Any) -> None:+ # A rejected plan turns into a 422 for the user, so the reason is only visible here.+ logger.info("workflows.data_suggestions.plan_rejected", reason=reason, **details)+++def _links(step: PlannedStep) -> list[_Link] | None:+ """The outgoing edges of a step, in the shape the workflow graph expects."""+ if step.type == "exit":+ return []+ if step.type in ("conditional_branch", "random_split"):+ if not step.branches:+ return None+ branches = [_Link(target=branch.next, type="branch", index=index) for index, branch in enumerate(step.branches)]+ # A split always takes one of its paths, so its continue edge never runs. It points at the exit, and a step+ # reachable only through it fails the reachability check.+ fall_through = step.next if step.type == "conditional_branch" else None+ return [*branches, _Link(target=fall_through, type="continue")]+ if step.type == "wait_until_event":+ return [_Link(target=step.wait_event_next, type="branch", index=0), _Link(target=step.next, type="continue")]+ return [_Link(target=step.next, type="continue")]+++def _is_acyclic_and_connected(first_step: str, links: dict[str, list[_Link]]) -> bool:+ # A workflow runs forward only, and a step no path reaches would sit on the canvas doing nothing.+ incoming = dict.fromkeys(links, 0)+ for step_links in links.values():+ for link in step_links:+ if link.target is not None:+ incoming[link.target] += 1+ if incoming[first_step] != 0:+ return False+ queue = deque([first_step])+ visited: set[str] = set()+ while queue:+ step_id = queue.popleft()+ visited.add(step_id)+ for link in links[step_id]:+ if link.target is None:+ continue+ incoming[link.target] -= 1+ if incoming[link.target] == 0:+ queue.append(link.target)+ # Kahn's walk visits every step only when the graph from first_step has no cycle and reaches all steps.+ return visited == set(links)+++def _with_waits_between_emails(steps: list[PlannedStep]) -> list[PlannedStep]:+ # Two emails in a row reach the person at the same moment, so a missing wait gets the default one.+ steps_by_id = {step.id: step for step in steps}+ result: list[PlannedStep] = []+ for step in steps:+ following = steps_by_id.get(step.next) if step.next else None+ if step.type == "email" and following is not None and following.type == "email":+ wait_id = f"{step.id}__wait"+ result.append(step.model_copy(update={"next": wait_id}))+ result.append(_wait_step(wait_id, following.id))+ else:+ result.append(step)+ return result+++def _wait_step(step_id: str, next_id: str) -> PlannedStep:+ return PlannedStep(+ id=step_id,+ type="delay",+ name="Wait",+ setup_note="",+ next=next_id,+ branches=None,+ template_id=None,+ wait_event=None,+ wait_event_next=None,+ duration="1d",+ email_template_id=None,+ email_subject=None,+ email_heading=None,+ email_paragraphs=None,+ slack_message=None,+ )+++def _setup_note(step: PlannedStep) -> str:+ return clean_copy(step.setup_note)[:200] if step.setup_note else ""+++def _action(step: PlannedStep, action_id: str, action_type: str, config: dict[str, Any]) -> dict[str, Any]:+ return {+ "id": action_id,+ "name": clean_copy(step.name)[:60] or "Step",+ "description": _setup_note(step),+ "type": action_type,+ "config": config,+ }+++def _build_step(step: PlannedStep, action_id: str, context: BuildContext) -> dict[str, Any] | None:+ match step.type:+ case "email":+ return _build_email_step(step, action_id, context)+ case "sms" | "push" if step.type not in context.channels:+ return None+ case "sms":+ return _action(step, action_id, "function_sms", {"template_id": "template-twilio", "inputs": {}})+ case "push":+ return _action(step, action_id, "function_push", {"template_id": "template-native-push", "inputs": {}})+ case "slack":+ return _action(step, action_id, "function", _slack_config(step, context))+ case "function":+ if step.template_id not in context.step_template_ids:+ return None+ return _action(step, action_id, "function", {"template_id": step.template_id, "inputs": {}})+ case "delay":+ if not step.duration:+ return None+ return _action(step, action_id, "delay", {"delay_duration": step.duration})+ case "wait_until_time_window":+ # A window of any day and any time is always open, so the step would not wait at all.+ return _action(+ step,+ action_id,+ "wait_until_time_window",+ {"timezone": None, "day": "weekday", "time": ["09:00", "17:00"]},+ )+ case "wait_until_event":+ # A wait with no event never resolves and acts as a plain delay, and enabling does not catch it.+ # An event the project does not send is a made-up name.+ if not step.wait_event or step.wait_event not in context.allowed_events:+ return None+ return _action(step, action_id, "wait_until_condition", _wait_config(step))+ case "conditional_branch":+ # Empty filters, like a branch added in the editor, which rejects null filters. The step's note asks the+ # team to set each condition.+ conditions = [{"filters": {}, "name": clean_copy(branch.label)[:60]} for branch in step.branches or []]+ return _action(step, action_id, "conditional_branch", {"conditions": conditions})+ case "random_split":+ branches = step.branches or []+ # A share outside 1 to 100 still sums to 100 but leaves a path that nobody reaches.+ shares = [branch.percentage or 0 for branch in branches]+ if sum(shares) != 100 or any(not 0 < share <= 100 for share in shares):+ return None+ cohorts = [+ {"percentage": branch.percentage or 0, "name": clean_copy(branch.label)[:60]} for branch in branches+ ]+ return _action(step, action_id, "random_cohort_branch", {"cohorts": cohorts})+ case "exit":+ return _action(step, action_id, "exit", {"reason": clean_copy(step.name)[:100] or "Exit"})+++def _slack_config(step: PlannedStep, context: BuildContext) -> dict[str, Any]:+ inputs: dict[str, Any] = {"channel": {"templating": "hog"}}+ if context.slack_integration_id is not None:+ inputs["slack_workspace"] = {"value": context.slack_integration_id, "templating": "hog"}+ if step.slack_message:+ inputs["text"] = {"value": clean_copy(step.slack_message), "templating": "hog"}+ return {"template_id": "template-slack", "inputs": inputs}+++def _wait_config(step: PlannedStep) -> dict[str, Any]:+ event = {"id": step.wait_event, "name": step.wait_event, "type": "events", "order": 0}+ return {+ "condition": {"filters": None},+ "events": [{"name": step.wait_event, "filters": {"events": [event]}}],+ "max_wait_duration": step.duration or _DEFAULT_MAX_WAIT,+ }+++def _build_email_step(step: PlannedStep, action_id: str, context: BuildContext) -> dict[str, Any] | None:+ if step.email_template_id:+ template = context.email_templates.get(step.email_template_id)+ if template is None:+ return None+ # The email sender rejects a null field, so a field the template does not have stays out.+ body = {+ key: template.email[key]+ for key in ("subject", "html", "text", "design")+ if template.email.get(key) is not None+ }+ name = template.email.get("subject") or "Email"+ else:+ if not (step.email_subject and step.email_heading and step.email_paragraphs):+ return None+ rendered = render_email(+ EmailCopy(+ subject=clean_copy(step.email_subject),+ heading=clean_copy(step.email_heading),+ paragraphs=tuple(clean_copy(paragraph) for paragraph in step.email_paragraphs[:3]),+ )+ )+ body = {"subject": rendered.subject, "html": rendered.html, "text": rendered.text, "design": rendered.design}+ name = rendered.subject++ sender = context.sender+ return {+ "id": action_id,+ "name": name[:60],+ "description": _setup_note(step),+ "type": "function_email",+ "config": {+ "template_id": "template-email",+ "inputs": {+ "email": {+ "templating": "liquid",+ "value": {+ "to": {"email": "{{ person.properties.email }}", "name": ""},+ "from": (+ {"integrationId": sender.integration_id, "email": sender.email, "name": sender.name}+ if sender+ else {"email": "", "name": ""}+ ),+ "replyTo": "",+ "preheader": "",+ **body,+ },+ }+ },+ },+ }+++def clean_copy(text: str) -> str:+ cleaned = re.sub(r"\s*—\s*", ", ", _TEMPLATE_TAGS.sub("", text))+ # Removing one tag can join the braces around it into a new one, so no brace may remain at all.+ cleaned = cleaned.replace("{", "").replace("}", "").strip()+ # Sentence case starts with a capital, which the model does not always write.+ return cleaned[:1].upper() + cleaned[1:]diff --git a/products/workflows/backend/services/data_suggestions/email_design.py b/products/workflows/backend/services/data_suggestions/email_design.pynew file mode 100644index 000000000000..d46047859b99--- /dev/null+++ b/products/workflows/backend/services/data_suggestions/email_design.py@@ -0,0 +1,42 @@+from html import escape++from posthog.dataclasses import frozen++from products.cdp.backend.validation import build_html_wrap_design+++@frozen+class EmailCopy:+ subject: str+ heading: str+ paragraphs: tuple[str, ...]+++@frozen+class RenderedEmail:+ subject: str+ html: str+ text: str+ design: dict+++def render_email(copy: EmailCopy) -> RenderedEmail:+ paragraphs = "".join(+ f'<p style="margin:0 0 16px;font-size:16px;line-height:24px;color:#3b3d45">{escape(paragraph)}</p>'+ for paragraph in copy.paragraphs+ )+ html = (+ '<!DOCTYPE html><html><body style="margin:0;padding:24px 0;background:#f5f5f2;'+ 'font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif">'+ '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" '+ 'style="max-width:560px;margin:0 auto;background:#ffffff;border-radius:8px">'+ '<tr><td style="padding:32px">'+ f'<h1 style="margin:0 0 16px;font-size:24px;line-height:32px;color:#1d1f27">{escape(copy.heading)}</h1>'+ f"{paragraphs}"+ "</td></tr>"+ '<tr><td style="padding:16px 32px 32px;font-size:12px;color:#6b6e76">'+ '<a href="{{ unsubscribe_url }}" style="color:#6b6e76">Unsubscribe</a></td></tr>'+ "</table></body></html>"+ )+ text = "\n\n".join([copy.heading, *copy.paragraphs])+ return RenderedEmail(subject=copy.subject, html=html, text=text, design=build_html_wrap_design(html))diff --git a/products/workflows/backend/services/data_suggestions/event_volume.py b/products/workflows/backend/services/data_suggestions/event_volume.pynew file mode 100644index 000000000000..3f136e7750cf--- /dev/null+++ b/products/workflows/backend/services/data_suggestions/event_volume.py@@ -0,0 +1,95 @@+"""How often each of the project's events fired in the last week, sampled for large teams."""++import math+from collections.abc import Iterable++from posthog.schema import HogQLQueryResponse, ProductKey++from posthog.hogql import ast+from posthog.hogql.constants import HogQLGlobalSettings+from posthog.hogql.parser import parse_select+from posthog.hogql.query import execute_hogql_query++from posthog.clickhouse.query_tagging import Feature, tag_queries+from posthog.models import Team++# Above this many events a week the counts are sampled. The estimate itself reads 1 in 100 events.+FULL_SCAN_MAX_WEEKLY_EVENTS = 20_000_000+_ESTIMATE_SAMPLE_DENOMINATOR = 100+_COUNT_TIMEOUT_SECONDS = 30+# Sampling is by distinct ID, so the volume estimate misses a busy event that a few sampled-out IDs send, like a+# server-side event, and an exact count can then hit it. Past this many bytes a count stops and keeps the partial+# result, which still ranks the events and clears the minimum weekly count.+_COUNT_MAX_BYTES = 2_000_000_000+MAX_EVENTS = 5000+# PostHog's own events that mark a real moment, unlike the generic `$` events the planner must skip.+ALLOWED_POSTHOG_EVENTS = frozenset({"$conversation_ticket_created"})+++def weekly_counts(team: Team) -> dict[str, int]:+ """How often each of the project's own events fired in the last week. PostHog's generic `$` events are left out,+ except the few that mark a real moment."""+ # Small teams get exact counts, since a quiet event could vanish from a sample. Large teams only need the+ # ranking, so a sample keeps the scan at about the size of a small team's.+ sample_denominator = max(1, math.ceil(estimated_weekly_events(team) / FULL_SCAN_MAX_WEEKLY_EVENTS))+ counts = _count_events(team, sample_denominator, skip=frozenset())+ if sample_denominator > 1:+ # A sample can miss a quiet event, like a weekly sign-up, entirely. The events table is sorted by event name+ # within a day, so an exact count that skips the events the sample found reads few rows.+ counts.update(_count_events(team, 1, skip=frozenset(counts)))+ return counts+++def estimated_weekly_events(team: Team) -> int:+ query = parse_select("SELECT count() FROM events WHERE timestamp >= now() - INTERVAL 7 DAY")+ if isinstance(query, ast.SelectQuery) and query.select_from is not None:+ query.select_from.sample = _sample(_ESTIMATE_SAMPLE_DENOMINATOR)+ response = _run_count(team, query, "workflows_data_suggestions_volume")+ rows = response.results or []+ return int(rows[0][0]) * _ESTIMATE_SAMPLE_DENOMINATOR if rows else 0+++def _count_events(team: Team, sample_denominator: int, *, skip: frozenset[str]) -> dict[str, int]:+ query = parse_select(+ """+ SELECT event, count() AS weekly_count+ FROM events+ WHERE timestamp >= now() - INTERVAL 7 DAY+ AND (NOT startsWith(event, '$') OR event IN {allowed})+ AND event NOT IN {skip}+ GROUP BY event+ ORDER BY weekly_count DESC+ LIMIT {limit}+ """,+ placeholders={+ "allowed": _strings(ALLOWED_POSTHOG_EVENTS),+ # An empty tuple is not valid HogQL, so an empty skip list holds a name no event has.+ "skip": _strings(skip or {""}),+ # Without an explicit limit HogQL returns 100 rows. Events with dynamic names can reach many thousands.+ "limit": ast.Constant(value=MAX_EVENTS),+ },+ )+ if sample_denominator > 1 and isinstance(query, ast.SelectQuery) and query.select_from is not None:+ query.select_from.sample = _sample(sample_denominator)+ response = _run_count(team, query, "workflows_data_suggestions_counts")+ return {str(row[0]): int(row[1]) * sample_denominator for row in response.results or [] if int(row[1]) > 0}+++def _strings(values: Iterable[str]) -> ast.Tuple:+ return ast.Tuple(exprs=[ast.Constant(value=value) for value in sorted(values)])+++def _sample(denominator: int) -> ast.SampleExpr:+ return ast.SampleExpr(sample_value=ast.RatioExpr(left=ast.Constant(value=1), right=ast.Constant(value=denominator)))+++def _run_count(team: Team, query: ast.SelectQuery | ast.SelectSetQuery, query_type: str) -> HogQLQueryResponse:+ tag_queries(product=ProductKey.WORKFLOWS, feature=Feature.QUERY)+ settings = HogQLGlobalSettings(+ max_execution_time=_COUNT_TIMEOUT_SECONDS,+ # A timeout must fail the run. A profile set to break would return a partial count that is cached for a week.+ timeout_overflow_mode="throw",+ max_bytes_to_read=_COUNT_MAX_BYTES,+ read_overflow_mode="break",+ )+ return execute_hogql_query(query=query, team=team, query_type=query_type, settings=settings)diff --git a/products/workflows/backend/services/data_suggestions/llm.py b/products/workflows/backend/services/data_suggestions/llm.pynew file mode 100644index 000000000000..e2292b53198e--- /dev/null+++ b/products/workflows/backend/services/data_suggestions/llm.py@@ -0,0 +1,153 @@+import uuid+from collections.abc import Mapping, Sequence+from typing import Any, Literal, TypeVar++import structlog+from langchain_core.callbacks import BaseCallbackHandler+from langchain_core.runnables import RunnableConfig+from posthoganalytics.ai.langchain.callbacks import CallbackHandler+from pydantic import BaseModel, ValidationError++from posthog.exceptions_capture import capture_exception+from posthog.models import Team, User++from ee.hogai.llm import MaxChatAnthropic+from ee.hogai.utils.feature_flags import is_privacy_mode_enabled++logger = structlog.get_logger(__name__)++_TIMEOUT_SECONDS = 120+_MAX_OUTPUT_TOKENS = 16000++Schema = TypeVar("Schema", bound=BaseModel)+++def invoke_structured(+ *,+ team: Team,+ user: User,+ model: str,+ effort: Literal["low", "medium", "high"],+ feature: str,+ schema: type[Schema],+ system: str,+ human: str,+ excluded_values: frozenset[str],+ allowed_values: Mapping[str, Sequence[str]] | None = None,+ analytics_client: Any = None,+) -> Schema | None:+ """One Claude call that answers in `schema`, or None when the call fails or the answer does not fit.++ The generation goes to LLM analytics through `analytics_client`, failed calls included, so a bad rollout+ shows up there with the model's input and output.+ """+ properties = {"ai_product": "workflows", "ai_feature": feature, "team_id": team.id}+ callbacks: list[BaseCallbackHandler] = []+ if analytics_client is not None:+ callbacks.append(+ CallbackHandler(+ analytics_client,+ distinct_id=user.distinct_id,+ trace_id=f"workflows-{feature}-{uuid.uuid4()}",+ properties=properties,+ privacy_mode=is_privacy_mode_enabled(team),+ )+ )+ try:+ llm = MaxChatAnthropic(+ model=model,+ user=user,+ team=team,+ # PostHog covers these calls, so suggestions never draw on the customer's AI credits.+ billable=False,+ inject_context=False,+ streaming=False,+ disable_streaming=True,+ stream_usage=False,+ max_tokens=_MAX_OUTPUT_TOKENS,+ # Current Claude models only think adaptively, and a forced tool call (langchain's structured output)+ # does not work with thinking. The API's own JSON schema output does.+ thinking={"type": "adaptive"},+ model_kwargs={+ "output_config": {+ "effort": effort,+ "format": {+ "type": "json_schema",+ "schema": strict_schema(schema, excluded_values, allowed_values or {}),+ },+ }+ },+ default_request_timeout=_TIMEOUT_SECONDS,+ # Retries would outlast the three minutes the frontend polls for, so a failed call fails the run.+ max_retries=0,+ posthog_properties=properties,+ )+ response = llm.invoke([("system", system), ("human", human)], config=RunnableConfig(callbacks=callbacks))+ return schema.model_validate_json(_response_text(response.content))+ except ValidationError as error:+ # The error's input holds model output, which can carry project content, so only types and paths are logged.+ logger.warning(+ "workflows.data_suggestions.llm_malformed",+ team_id=team.id,+ feature=feature,+ errors=[{"type": item["type"], "loc": item["loc"]} for item in error.errors(include_input=False)],+ )+ return None+ except Exception as error:+ logger.warning("workflows.data_suggestions.llm_failed", team_id=team.id, feature=feature, exc_info=True)+ capture_exception(error, {"team_id": team.id, "ai_feature": feature})+ return None+++def strict_schema(+ schema: type[BaseModel], excluded_values: frozenset[str], allowed_values: Mapping[str, Sequence[str]]+) -> dict[str, Any]:+ # The API's JSON schema output requires every object to forbid properties the schema does not list.+ # Removing a value from every enum means the model cannot pick a channel the team has not connected.+ # A property in `allowed_values` only accepts those strings, so the model cannot make up an event name. It is+ # restricted after the exclusions, so an event named like a channel stays available.+ def close_objects(node: Any) -> None:+ if isinstance(node, dict):+ if node.get("type") == "object":+ node["additionalProperties"] = False+ if isinstance(node.get("enum"), list):+ node["enum"] = [value for value in node["enum"] if value not in excluded_values]+ for value in node.values():+ close_objects(value)+ elif isinstance(node, list):+ for value in node:+ close_objects(value)++ def restrict(node: Any) -> None:+ if isinstance(node, dict):+ if node.get("type") == "object":+ for name, values in allowed_values.items():+ if name in node.get("properties", {}):+ _restrict_strings(node["properties"][name], list(values))+ for value in node.values():+ restrict(value)+ elif isinstance(node, list):+ for value in node:+ restrict(value)++ json_schema = schema.model_json_schema()+ close_objects(json_schema)+ restrict(json_schema)+ return json_schema+++def _restrict_strings(property_schema: dict[str, Any], values: list[str]) -> None:+ # A nullable string is `anyOf: [{type: string}, {type: null}]`, so the enum goes on the string branch.+ branches = property_schema.get("anyOf", [property_schema])+ for branch in branches:+ if branch.get("type") == "string":+ branch["enum"] = values+++def _response_text(content: str | list[Any]) -> str:+ # With thinking on, the answer is the text blocks after the thinking blocks.+ if isinstance(content, str):+ return content+ return "".join(+ block.get("text", "") for block in content if isinstance(block, dict) and block.get("type") == "text"+ )diff --git a/products/workflows/backend/services/data_suggestions/planner.py b/products/workflows/backend/services/data_suggestions/planner.pynew file mode 100644index 000000000000..f47d45d62d9f--- /dev/null+++ b/products/workflows/backend/services/data_suggestions/planner.py@@ -0,0 +1,277 @@+from typing import Any, Literal++from pydantic import BaseModel, Field++from posthog.dataclasses import frozen+from posthog.models import Team, User++from products.messaging.backend.facade.api import EmailTemplateSummary+from products.workflows.backend.facade.contracts import LifecycleStage, OutlineKind+from products.workflows.backend.services.data_suggestions.llm import invoke_structured+from products.workflows.backend.services.hog_flow_templates import StepTemplate++from ee.hogai.utils.untrusted import as_untrusted_data++MAX_PLANNED_STEPS = 20++# Ideas are short copy over an event list. The step plan is a graph of up to 20 steps with branches and email copy,+# which needs the stronger model. It runs once per click, so its cost stays small.+IDEAS_MODEL = "claude-sonnet-5-5"+PLANNER_MODEL = "claude-opus-5-5"++# The planner's step types. "function" covers every other step from the template catalog.+StepType = Literal[+ "email",+ "sms",+ "push",+ "slack",+ "function",+ "delay",+ "wait_until_time_window",+ "wait_until_event",+ "conditional_branch",+ "random_split",+ "exit",+]+DelayDuration = Literal["1h", "1d", "2d", "3d", "7d"]+# Message channels that need a provider the team connects. Email is always offered.+Channel = Literal["sms", "push"]+++class WorkflowIdea(BaseModel):+ name: str = Field(description="Short workflow name in sentence case, at most 50 characters.")+ description: str = Field(description="One sentence on what the workflow does, at most 90 characters.")+ reason: str = Field(description="One sentence on why it fits this project, naming the trigger event.")+ trigger_event: str = Field(description="Exactly one event name from the project's event list.")+ step_outline: list[OutlineKind] = Field(+ description="The main steps after the trigger, in order, at most 20. webhook is a call to an external "+ "endpoint, action is any other step such as updating a person or sending to a CRM."+ )+++class WorkflowIdeas(BaseModel):+ ideas: list[WorkflowIdea]+++class PlannedBranch(BaseModel):+ label: str = Field(description="Short name of this path, like 'Finished onboarding' or 'Group A'.")+ percentage: int | None = Field(description="For a random_split: this path's share in percent, else null.")+ next: str | None = Field(description="The id of the first step on this path, or null to end the workflow.")+++class PlannedStep(BaseModel):+ id: str = Field(description="A short id that is unique in this workflow, like 'welcome_email'.")+ type: StepType+ name: str = Field(description="Short display name of the step in sentence case, at most 40 characters.")+ setup_note: str = Field(+ description="What the team still has to fill in on this step, like 'Pick the Slack channel'. "+ "Empty when nothing is left."+ )+ next: str | None = Field(+ description="The id of the step that follows. For wait_until_event it is the path when the wait times out, "+ "for conditional_branch the path when no condition matches. Null ends the workflow."+ )+ branches: list[PlannedBranch] | None = Field(+ description="conditional_branch: one path per condition, the label says what the condition checks. "+ "random_split: two or more paths whose percentages add up to 100. Null for every other type."+ )+ template_id: str | None = Field(+ description="For a function step: one template_id from the step catalog, else null."+ )+ wait_event: str | None = Field(+ description="For wait_until_event: one event name copied exactly from the project's events, else null."+ )+ wait_event_next: str | None = Field(+ description="For wait_until_event: the id of the step to run when the event happens, or null to end the workflow."+ )+ duration: DelayDuration | None = Field(+ description="For delay: how long to wait. For wait_until_event: the longest time to wait. Else null."+ )+ email_template_id: str | None = Field(+ description="For an email step: the id of one of the team's saved email templates that fits, else null."+ )+ email_subject: str | None = Field(description="For an email step without a saved template: the subject line.")+ email_heading: str | None = Field(description="For an email step without a saved template: the headline.")+ email_paragraphs: list[str] | None = Field(+ description="For an email step without a saved template: 1 to 3 short paragraphs of body copy."+ )+ slack_message: str | None = Field(description="For a slack step: the message to post, else null.")+++class PlannedWorkflow(BaseModel):+ first_step: str = Field(description="The id of the step that runs right after the trigger.")+ steps: list[PlannedStep]+++@frozen+class IdeaContext:+ events: tuple[tuple[str, int], ...]+ stages: dict[str, LifecycleStage]+ channels: frozenset[Channel]+ has_slack: bool+++@frozen+class StepsContext:+ idea: WorkflowIdea+ email_templates: tuple[EmailTemplateSummary, ...]+ step_templates: tuple[StepTemplate, ...]+ events: tuple[str, ...]+ channels: frozenset[Channel]+ has_slack: bool+++_SIMPLE_RULE = (+ "Keep the workflow as simple as its goal allows. Every step must do something for the person or the team. "+ "Do not add steps that only record state, like setting a person property, unless a later step depends on it."+)++_ONBOARDING_RULE = (+ "This team has no workflows yet, and welcome and onboarding workflows convert best. When the list has an "+ "event for a new sign-up or for onboarding, make one of the ideas a welcome or onboarding workflow on it, "+ "even when other events fire more often. Then prefer other meaningful moments."+)++_COPY_RULES = "Write plain, friendly copy in sentence case. No emojis, no em dashes, no placeholders like [Name], no template tags."++_IDEAS_PROMPT = f"""You suggest marketing and automation workflows for a product team using PostHog Workflows.+Suggest up to 6 workflows the project does not have yet. Each one starts when one of the project's events happens.++Rules:+- trigger_event must be copied exactly from the event list.+- {_ONBOARDING_RULE}+- Each idea must use a different trigger_event.+- Email is the main way to reach people. {{channel_rule}} {{slack_rule}}+- Use the steps the workflow needs, including waits for an event and branches. {_SIMPLE_RULE}+- Put a delay between two emails.+- {_COPY_RULES}+"""++_STEPS_PROMPT = f"""You plan the steps of one PostHog workflow. The workflow and its outline are given below.+Follow the outline unless a step cannot work. Use at most {{max_steps}} steps, as many as the workflow needs.++Step types:+- email: a message to the person, and the main channel. Write the copy.+- sms, push: a message to the person, only when the team has that provider connected.+- slack: a message to the team's Slack channel. Write the message.+- function: any step from the step catalog, such as a webhook, a CRM update or a PostHog action. Set template_id.+- delay: wait a fixed time.+- wait_until_time_window: wait for a time of day or day of the week the team picks.+- wait_until_event: wait until the person does one of the project's events, at most duration.+- conditional_branch: split on conditions the team defines, such as a person property.+- random_split: split people at random into paths, such as for an A/B test.+- exit: end the workflow early with a reason.++Rules:+- Steps form a graph: next, branches and wait_event_next point at step ids. Never point back at an earlier step.+- Leave settings you cannot know blank: API keys, URLs, channels, phone numbers, property filters and \+recipients. The team fills them in. Say what is left in setup_note.+- {{email_rule}}+- {{channel_rule}}+- {{slack_rule}}+- {_SIMPLE_RULE}+- Put a delay between two emails.+- {_COPY_RULES}+"""+++def suggest_ideas(*, team: Team, user: User, context: IdeaContext, analytics_client: Any = None) -> list[WorkflowIdea]:+ slack_rule = "" if context.has_slack else "The team has not connected Slack yet, so prefer other steps."+ lines = [+ f"{name} ({count} in the last 7 days, stage: {context.stages[name]})"+ if name in context.stages+ else f"{name} ({count} in the last 7 days)"+ for name, count in context.events+ ]+ result = invoke_structured(+ team=team,+ user=user,+ model=IDEAS_MODEL,+ effort="low",+ feature="data_suggestion_ideas",+ schema=WorkflowIdeas,+ system=_IDEAS_PROMPT.format(channel_rule=_channel_rule(context.channels), slack_rule=slack_rule),+ excluded_values=_missing_channels(context.channels),+ # The prompt escapes `<` and `>` in event names, so the schema carries the exact names the model must return.+ allowed_values={"trigger_event": [name for name, _ in context.events]},+ human=as_untrusted_data("project_events", lines, source="event names sent by this project's app"),+ analytics_client=analytics_client,+ )+ return result.ideas if result else []+++def _missing_channels(channels: frozenset[Channel]) -> frozenset[str]:+ return frozenset({"sms", "push"} - channels)+++def _channel_rule(channels: frozenset[Channel]) -> str:+ if not channels:+ return "The team has no SMS or push provider, so use email to reach people."+ return f"The team can also send {' and '.join(sorted(channels))}. Use them only when they suit the message better than email."+++def plan_steps(+ *, team: Team, user: User, context: StepsContext, analytics_client: Any = None+) -> PlannedWorkflow | None:+ email_rule = (+ "For each email step, set email_template_id only when a saved template's name and subject clearly match "+ "the purpose of that step. Generic or placeholder templates never match. Otherwise leave it null and "+ "write the subject, heading and paragraphs."+ if context.email_templates+ else "For each email step, write the subject, heading and paragraphs, and leave email_template_id null."+ )+ slack_rule = (+ "Slack steps post to a channel the team picks later."+ if context.has_slack+ else "The team has not connected Slack yet. A slack step is fine, the team connects it on the step."+ )+ idea = context.idea+ human = as_untrusted_data(+ "workflow",+ [+ f"name: {idea.name}",+ f"description: {idea.description}",+ f"trigger event: {idea.trigger_event}",+ f"outline: {', '.join(idea.step_outline)}",+ ],+ source="a workflow idea written from this project's event names",+ )+ human += "\n\n" + as_untrusted_data(+ "project_events", list(context.events), source="event names sent by this project's app"+ )+ human += "\n\n" + as_untrusted_data(+ "step_catalog",+ [+ f"template_id={template.template_id} name={template.name} description={template.description[:120]}"+ for template in context.step_templates+ ],+ source="the function templates a workflow step can use",+ )+ if context.email_templates:+ human += "\n\n" + as_untrusted_data(+ "saved_email_templates",+ [+ f"id={template.id} name={template.name} subject={template.subject}"+ for template in context.email_templates+ ],+ source="email templates this team saved in PostHog",+ )+ return invoke_structured(+ team=team,+ user=user,+ model=PLANNER_MODEL,+ effort="medium",+ feature="data_suggestion_steps",+ schema=PlannedWorkflow,+ system=_STEPS_PROMPT.format(+ email_rule=email_rule,+ channel_rule=_channel_rule(context.channels),+ slack_rule=slack_rule,+ max_steps=MAX_PLANNED_STEPS,+ ),+ excluded_values=_missing_channels(context.channels),+ # An empty enum would make every wait_until_event step impossible, so the list is only set when there is one.+ allowed_values={"wait_event": context.events} if context.events else None,+ human=human,+ analytics_client=analytics_client,+ )diff --git a/products/workflows/backend/services/data_suggestions/ranking.py b/products/workflows/backend/services/data_suggestions/ranking.pynew file mode 100644index 000000000000..58233b1b29a2--- /dev/null+++ b/products/workflows/backend/services/data_suggestions/ranking.py@@ -0,0 +1,101 @@+import re+import math+from collections.abc import Callable++from products.workflows.backend.facade.contracts import LifecycleStage++# For a team with no workflows yet, welcome and onboarding flows convert best, but their events fire far less+# often than product usage events. These weights let a quiet sign-up event outrank a busy usage event, while+# volume still counts within a stage.+STAGE_WEIGHTS: dict[LifecycleStage, float] = {+ "signup": 5.0,+ "onboarding": 4.0,+ "trial": 3.0,+ "purchase": 3.0,+ "churn_risk": 2.5,+ "failure": 1.5,+ "support": 1.5,+ "other": 1.0,+}++MIN_WEEKLY_COUNT = 3+# A busy project can have hundreds of names that match one pattern, like `error`. The cap stops one pattern from+# taking every place in the list Jev classifies.+MAX_GUESSED_PER_STAGE = 15++# Only pick which events Jev gets to classify, so lifecycle-looking names are not cut by the limit. Checked in+# order. Deletion counts only for accounts and their owners, because most `*_deleted` events are routine product+# actions, not churn.+_STAGE_REGEXES: tuple[tuple[LifecycleStage, str], ...] = (+ ("signup", r"sign.?up|signed.?up|regist|(account|user|workspace|organi[sz]ation|team).?created"),+ ("onboarding", r"onboard|activat|welcome|invite"),+ ("trial", r"trial"),+ ("churn_risk", r"cancel|churn|downgrad|unsubscri|(account|user|workspace|organi[sz]ation).?delet"),+ ("failure", r"fail|error"),+ ("purchase", r"subscri|upgrad|purchas|order|checkout|payment|paid|plan"),+ ("support", r"ticket|survey|feedback"),+)+_STAGE_PATTERNS: tuple[tuple[LifecycleStage, re.Pattern[str]], ...] = tuple(+ (stage, re.compile(pattern, re.IGNORECASE)) for stage, pattern in _STAGE_REGEXES+)+++def guess_stage(event_name: str) -> LifecycleStage:+ for stage, pattern in _STAGE_PATTERNS:+ if pattern.search(event_name):+ return stage+ return "other"+++def select_prompt_events(+ weekly_counts: dict[str, int],+ *,+ limit: int,+ stages: dict[str, LifecycleStage] | None = None,+ weights: dict[LifecycleStage, float] = STAGE_WEIGHTS,+) -> list[tuple[str, int]]:+ """The events the model gets to choose from. With stages from Jev they are ranked like the suggestions,+ without them lifecycle-looking names go first. Picking by volume alone would cut a quiet sign-up event."""+ eligible = sorted(+ ((name, count) for name, count in weekly_counts.items() if count >= MIN_WEEKLY_COUNT),+ key=lambda item: item[1],+ reverse=True,+ )+ if stages:+ return sorted(+ eligible, key=lambda item: suggestion_score(stages.get(item[0], "other"), item[1], weights), reverse=True+ )[:limit]+ lifecycle: list[tuple[str, int]] = []+ others: list[tuple[str, int]] = []+ overflow: list[tuple[str, int]] = []+ guessed_per_stage: dict[LifecycleStage, int] = {}+ for item in eligible:+ stage = guess_stage(item[0])+ if stage == "other":+ others.append(item)+ elif guessed_per_stage.get(stage, 0) < MAX_GUESSED_PER_STAGE:+ guessed_per_stage[stage] = guessed_per_stage.get(stage, 0) + 1+ lifecycle.append(item)+ else:+ overflow.append(item)+ return (lifecycle + others + overflow)[:limit]+++def suggestion_score(+ stage: LifecycleStage, weekly_count: int, weights: dict[LifecycleStage, float] = STAGE_WEIGHTS+) -> float:+ return weights[stage] * math.log10(weekly_count + 1)+++def pick_one_per_stage[T](items: list[T], *, stage_of: Callable[[T], LifecycleStage], limit: int) -> list[T]:+ """The best item of each stage, in the order given, so two cards never cover the same moment."""+ picked: list[T] = []+ seen: set[LifecycleStage] = set()+ for item in items:+ stage = stage_of(item)+ if stage not in seen:+ seen.add(stage)+ picked.append(item)+ if len(picked) == limit:+ break+ return pickeddiff --git a/products/workflows/backend/services/data_suggestions/service.py b/products/workflows/backend/services/data_suggestions/service.pynew file mode 100644index 000000000000..5f51aa57e571--- /dev/null+++ b/products/workflows/backend/services/data_suggestions/service.py@@ -0,0 +1,464 @@+import json+import uuid+import threading+import dataclasses+from collections.abc import Callable, Iterator+from contextlib import contextmanager+from typing import Any++from django.conf import settings+from django.core.cache import cache++import structlog++from posthog.cloud_utils import is_cloud+from posthog.errors import CH_TRANSIENT_ERRORS, InternalCHQueryError+from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded, ClickHouseQueryTimeOut+from posthog.exceptions_capture import capture_exception+from posthog.llm.system_one_client import system_one_configured+from posthog.models import Team, User+from posthog.ph_client import get_client+from posthog.utils import get_instance_region++from products.messaging.backend.facade.api import EmailTemplateContent, EmailTemplateSummary, get_template_email_content+from products.workflows.backend.facade.contracts import (+ BuiltSuggestion,+ DataSuggestion,+ DataSuggestionNotFound,+ DataSuggestionsResult,+)+from products.workflows.backend.services.data_suggestions import team_context+from products.workflows.backend.services.data_suggestions.builder import BuildContext, build_workflow, clean_copy+from products.workflows.backend.services.data_suggestions.event_volume import weekly_counts+from products.workflows.backend.services.data_suggestions.planner import (+ MAX_PLANNED_STEPS,+ IdeaContext,+ PlannedWorkflow,+ StepsContext,+ WorkflowIdea,+ plan_steps,+ suggest_ideas,+)+from products.workflows.backend.services.data_suggestions.ranking import (+ pick_one_per_stage,+ select_prompt_events,+ suggestion_score,+)+from products.workflows.backend.services.data_suggestions.stages import (+ MAX_CLASSIFIED_EVENTS,+ StageClassificationFailed,+ classify_event_stages,+)+from products.workflows.backend.services.hog_flow_templates import list_step_templates++from ee.hogai.utils.feature_flags import is_privacy_mode_enabled++logger = structlog.get_logger(__name__)++CACHE_TTL_SECONDS = 7 * 24 * 60 * 60+# A failed run waits this long before it tries again, so an outage does not rerun the queries on every visit.+FAILURE_CACHE_TTL_SECONDS = 5 * 60+# Longer than the slowest run, model retries included, so a second run cannot start while the first is alive. Short+# enough that a crashed worker does not block a team for long.+_GENERATION_LOCK_SECONDS = 15 * 60+# A built draft is kept this long, so a retry after a failed save does not pay for another plan.+_BUILD_CACHE_SECONDS = 60 * 60+MAX_SUGGESTIONS = 3+_PROMPT_EVENTS_LIMIT = 60+_GENERATION_ERRORS = (+ StageClassificationFailed,+ InternalCHQueryError,+ ClickHouseQueryTimeOut,+ ClickHouseQueryMemoryLimitExceeded,+ *CH_TRANSIENT_ERRORS,+)++_GENERATING = DataSuggestionsResult(status="generating", suggestions=())+_BUILDING = BuiltSuggestion(status="building")+_BUILD_FAILED = BuiltSuggestion(status="failed")+_UNAVAILABLE = DataSuggestionsResult(status="unavailable", suggestions=())+_ONCE_PER_PERSON_STAGES = frozenset({"signup", "onboarding"})+++def get_data_suggestions(*, team: Team) -> DataSuggestionsResult:+ """The cards as they are now. This never runs a query or a model, so a read-only caller cannot cause spend."""+ unavailable = _unavailable_reason(team)+ if unavailable is not None:+ return unavailable+ # Checked before the cache, so a refresh in progress reads as generating rather than as the old cards.+ if cache.get(_generation_lock_key(team)) is not None:+ return _GENERATING+ return _read_cache(team) or _UNAVAILABLE+++def start_data_suggestions(*, team: Team, refresh: bool, enqueue: Callable[[str], None]) -> DataSuggestionsResult:+ """Returns the cached cards, or starts a background run through `enqueue` and reports that it is generating."""+ unavailable = _unavailable_reason(team)+ if unavailable is not None:+ return unavailable+ cached = _read_cache(team)+ if cached is not None and not refresh:+ return cached+ # Visits that arrive while a run is going would each repeat the queries and the model calls.+ lock_token = str(uuid.uuid4())+ if not cache.add(_generation_lock_key(team), lock_token, _GENERATION_LOCK_SECONDS):+ return _GENERATING+ try:+ enqueue(lock_token)+ except Exception:+ _release_lock(team.id, lock_token)+ logger.exception("workflows.data_suggestions.enqueue_failed", team_id=team.id)+ return _UNAVAILABLE+ return _GENERATING+++def needs_new_generation(*, team: Team, refresh: bool) -> bool:+ """Whether a generate call would start a run, the only case that costs model time."""+ # A refresh always counts, because the run it joins can end before the request reaches the lock.+ return refresh or (_read_cache(team) is None and cache.get(_generation_lock_key(team)) is None)+++def run_data_suggestions(*, team_id: int, user_id: int, lock_token: str) -> None:+ """The background run that `start_data_suggestions` queues. It caches the result and releases the lock."""+ lock_key = _generation_lock_key_for(team_id)+ try:+ team = Team.objects.select_related("organization").get(id=team_id)+ user = User.objects.get(id=user_id)+ # Consent or privacy settings can change between the click and the worker picking the run up.+ if _unavailable_reason(team) is not None:+ return+ previous = _read_cache(team)+ with _analytics_client() as analytics_client:+ result = _generate(team=team, user=user, analytics_client=analytics_client)+ # A failed refresh keeps the working suggestions, so builds that use their ids still find them.+ if result.status != "ready" and previous is not None and previous.status == "ready":+ return+ # An empty answer often means the team's events have not arrived yet, so it is retried as soon as a failure.+ ttl = CACHE_TTL_SECONDS if result.status == "ready" and result.suggestions else FAILURE_CACHE_TTL_SECONDS+ # A newer run owns the cache once this run lost the lock, and its suggestion ids must stay.+ if _lost_lock(lock_key, lock_token):+ return+ # Written before the lock is released, so the next visit reads it instead of starting another run.+ cache.set(_cache_key(team), _to_cache(result), ttl)+ finally:+ _release_lock(team_id, lock_token)+++def start_build(+ *, team: Team, suggestion_id: str, caller: str, retry: bool, enqueue: Callable[[str], None]+) -> BuiltSuggestion:+ """The built draft, or a background build through `enqueue`. Ask again while the status is building.++ Each `caller` checks drafts the way its own create request does, so builds are stored per caller.++ A failed result stays until `retry` asks for a new build, so every tab that polls the build reads the failure.+ """+ if team.organization.is_ai_data_processing_approved is not True or _cached_suggestion(team, suggestion_id) is None:+ raise DataSuggestionNotFound()+ stored = _read_build(team.id, suggestion_id, caller)+ if stored is not None and not (retry and stored.status == "failed"):+ return stored+ # A second click or tab while a build runs would pay for another plan.+ lock_token = str(uuid.uuid4())+ if not cache.add(_build_lock_key(team.id, suggestion_id, caller), lock_token, _GENERATION_LOCK_SECONDS):+ return _BUILDING+ # Cleared once the lock is held, so the polls of this retry read building instead of the old failure.+ cache.delete(_build_key(team.id, suggestion_id, caller))+ try:+ enqueue(lock_token)+ except Exception:+ _release(_build_lock_key(team.id, suggestion_id, caller), lock_token)+ logger.exception("workflows.data_suggestions.build_enqueue_failed", team_id=team.id)+ return _BUILD_FAILED+ # A worker that ran inline, like in tests, has already stored the result.+ return _read_build(team.id, suggestion_id, caller) or _BUILDING+++def needs_new_build(*, team: Team, suggestion_id: str, caller: str, retry: bool) -> bool:+ """Whether a build call would start planning, the only case that costs model time."""+ stored = _read_build(team.id, suggestion_id, caller)+ reusable = stored is not None and not (retry and stored.status == "failed")+ return not reusable and cache.get(_build_lock_key(team.id, suggestion_id, caller)) is None+++def run_build(+ *,+ team_id: int,+ user_id: int,+ suggestion_id: str,+ caller: str,+ lock_token: str,+ is_valid_draft: Callable[[Team, dict[str, Any]], bool],+) -> None:+ """The background build that `start_build` queues. It stores the result and releases the lock."""+ lock_key = _build_lock_key(team_id, suggestion_id, caller)+ try:+ try:+ team = Team.objects.select_related("organization").get(id=team_id)+ user = User.objects.get(id=user_id)+ cached = _read_cache(team)+ suggestion = _cached_suggestion(team, suggestion_id)+ # Consent can change between the click and the worker picking the build up.+ if team.organization.is_ai_data_processing_approved is not True or suggestion is None or cached is None:+ result = _BUILD_FAILED+ else:+ result = _plan_and_build(+ team=team, user=user, suggestion=suggestion, events=cached.events, is_valid_draft=is_valid_draft+ )+ except Exception as error:+ # Without a stored failure the next poll finds no result and no lock, and queues the same build again.+ logger.exception("workflows.data_suggestions.build_failed", team_id=team_id)+ capture_exception(error, {"team_id": team_id})+ result = _BUILD_FAILED+ ttl = _BUILD_CACHE_SECONDS if result.status == "ready" else FAILURE_CACHE_TTL_SECONDS+ if not _lost_lock(lock_key, lock_token):+ cache.set(_build_key(team_id, suggestion_id, caller), dataclasses.asdict(result), ttl)+ finally:+ _release(lock_key, lock_token)+++def _plan_and_build(+ *,+ team: Team,+ user: User,+ suggestion: DataSuggestion,+ events: tuple[str, ...],+ is_valid_draft: Callable[[Team, dict[str, Any]], bool],+) -> BuiltSuggestion:+ idea = WorkflowIdea(+ name=suggestion.name,+ description=suggestion.description,+ reason=suggestion.reason,+ trigger_event=suggestion.trigger_event,+ step_outline=list(suggestion.step_outline),+ )+ email_templates = team_context.email_templates(team)+ slack_integration_id = team_context.slack_integration_id(team)+ step_templates = tuple(list_step_templates(team))+ channels = team_context.channels(team)+ with _analytics_client() as analytics_client:+ plan = plan_steps(+ team=team,+ user=user,+ context=StepsContext(+ idea=idea,+ email_templates=email_templates,+ step_templates=step_templates,+ events=events,+ channels=channels,+ has_slack=slack_integration_id is not None,+ ),+ analytics_client=analytics_client,+ )+ if plan is None:+ return _BUILD_FAILED++ built = build_workflow(+ idea,+ plan,+ BuildContext(+ allowed_events=frozenset({suggestion.trigger_event, *events}),+ step_template_ids=frozenset(template.template_id for template in step_templates),+ channels=channels,+ email_templates=_chosen_template_bodies(team, plan, email_templates),+ sender=team_context.email_sender(team),+ slack_integration_id=slack_integration_id,+ once_per_person=suggestion.stage in _ONCE_PER_PERSON_STAGES,+ ),+ )+ if built is None or not is_valid_draft(team, built.workflow):+ return _BUILD_FAILED+ # Saved templates are copied into every email step, and a draft larger than a request body cannot be saved.+ if len(json.dumps(built.workflow)) > settings.DATA_UPLOAD_MAX_MEMORY_SIZE:+ return _BUILD_FAILED+ return BuiltSuggestion(status="ready", workflow=built.workflow, uses_saved_template=built.uses_saved_template)+++def _chosen_template_bodies(+ team: Team, plan: PlannedWorkflow, summaries: tuple[EmailTemplateSummary, ...]+) -> dict[str, EmailTemplateContent]:+ # Saved designs can be large, so only the bodies of the templates the plan picked are loaded.+ chosen = {step.email_template_id for step in plan.steps if step.email_template_id}+ bodies: dict[str, EmailTemplateContent] = {}+ for summary in summaries:+ if str(summary.id) not in chosen:+ continue+ email = get_template_email_content(team.id, summary.id)+ if email is not None:+ bodies[str(summary.id)] = EmailTemplateContent(id=summary.id, name=summary.name, email=email)+ return bodies+++def _unavailable_reason(team: Team) -> DataSuggestionsResult | None:+ if team.organization.is_ai_data_processing_approved is not True:+ return DataSuggestionsResult(status="ai_not_approved", suggestions=())+ # The Jev client cannot send the gateway's privacy header, so event names would be recorded. Until it can,+ # organizations in privacy mode get no suggestions.+ if is_privacy_mode_enabled(team):+ return _UNAVAILABLE+ # Without Jev the ranking cannot tell a sign-up from routine usage, so no suggestions are made.+ if not system_one_configured():+ return _UNAVAILABLE+ return None+++def _cache_key(team: Team) -> str:+ return f"workflows:data_suggestions:v4:{team.id}"+++def _generation_lock_key(team: Team) -> str:+ return _generation_lock_key_for(team.id)+++def _generation_lock_key_for(team_id: int) -> str:+ return f"workflows:data_suggestions:generating:{team_id}"+++def _release_lock(team_id: int, lock_token: str) -> None:+ _release(_generation_lock_key_for(team_id), lock_token)+++def _lost_lock(key: str, lock_token: str) -> bool:+ # Reads can come from a Redis replica, which may not have the lock yet. Only another run's token means a newer run+ # took over, so a missing lock does not count.+ holder = cache.get(key)+ return holder is not None and holder != lock_token+++def _release(key: str, lock_token: str) -> None:+ # Only the run that holds the lock releases it, so a run that outlived its lease cannot drop a newer run's lock.+ if cache.get(key) == lock_token:+ cache.delete(key)+++def _build_key(team_id: int, suggestion_id: str, caller: str) -> str:+ return f"workflows:data_suggestions:build:{team_id}:{suggestion_id}:{caller}"+++def _build_lock_key(team_id: int, suggestion_id: str, caller: str) -> str:+ return f"workflows:data_suggestions:building:{team_id}:{suggestion_id}:{caller}"+++def _read_build(team_id: int, suggestion_id: str, caller: str) -> BuiltSuggestion | None:+ stored = cache.get(_build_key(team_id, suggestion_id, caller))+ if not isinstance(stored, dict):+ return None+ try:+ return BuiltSuggestion(**stored)+ except TypeError:+ return None+++def _to_cache(result: DataSuggestionsResult) -> dict[str, Any]:+ # Plain data, not a pickled class, so moving or renaming the dataclasses never breaks a cached entry.+ return dataclasses.asdict(result)+++def _read_cache(team: Team) -> DataSuggestionsResult | None:+ stored = cache.get(_cache_key(team))+ if not isinstance(stored, dict):+ return None+ try:+ return DataSuggestionsResult(+ status=stored["status"],+ suggestions=tuple(+ DataSuggestion(**{**item, "step_outline": tuple(item["step_outline"])})+ for item in stored["suggestions"]+ ),+ events=tuple(stored["events"]),+ )+ except (KeyError, TypeError):+ # An entry from before a field change is treated as missing, so the next visit generates new cards.+ return None+++def _cached_suggestion(team: Team, suggestion_id: str) -> DataSuggestion | None:+ cached = _read_cache(team)+ if cached is None:+ return None+ return next((item for item in cached.suggestions if item.id == suggestion_id), None)+++@contextmanager+def _analytics_client() -> Iterator[Any]:+ # The traces hold project event names and model output, so they go to the deployment's own region rather than+ # the process-wide client, which reports to the US project. Only cloud reports, like ph_scoped_capture. The+ # client flushes on exit, because a Celery task cannot rely on a background flush. The flush runs in its own+ # thread, so an ingestion outage cannot hold back the result or the worker.+ client = get_client(get_instance_region() or "US") if is_cloud() else None+ try:+ yield client+ finally:+ if client is not None:+ threading.Thread(target=client.shutdown, daemon=True).start()+++def _generate(*, team: Team, user: User, analytics_client: Any) -> DataSuggestionsResult:+ try:+ return _suggest(team=team, user=user, analytics_client=analytics_client)+ except _GENERATION_ERRORS:+ return _UNAVAILABLE+ except Exception as error:+ # Any other failure, like a database error, is cached as unavailable too, so the next visit does not repeat+ # the counts and the classification straight away.+ logger.exception("workflows.data_suggestions.generation_failed", team_id=team.id)+ capture_exception(error, {"team_id": team.id})+ return _UNAVAILABLE+++def _suggest(*, team: Team, user: User, analytics_client: Any) -> DataSuggestionsResult:+ used_events = team_context.used_trigger_events(team)+ all_counts = weekly_counts(team)+ # A build can wait on any busy event, including one another workflow already starts from.+ planning_events = tuple(name for name, _ in select_prompt_events(all_counts, limit=_PROMPT_EVENTS_LIMIT))+ counts = {name: count for name, count in all_counts.items() if name not in used_events}+ if not counts:+ return DataSuggestionsResult(status="ready", suggestions=())++ candidates = select_prompt_events(counts, limit=MAX_CLASSIFIED_EVENTS)+ jev_stages = classify_event_stages(team_id=team.id, event_names=[name for name, _ in candidates])+ prompt_events = select_prompt_events(counts, limit=_PROMPT_EVENTS_LIMIT, stages=jev_stages)+ if not prompt_events:+ return DataSuggestionsResult(status="ready", suggestions=())+ offered = {name for name, _ in prompt_events}+ ideas = suggest_ideas(+ team=team,+ user=user,+ context=IdeaContext(+ events=tuple(prompt_events),+ stages=jev_stages,+ channels=team_context.channels(team),+ has_slack=team_context.slack_integration_id(team) is not None,+ ),+ analytics_client=analytics_client,+ )+ if not ideas:+ return _UNAVAILABLE++ suggestions: list[DataSuggestion] = []+ seen_events: set[str] = set()+ for idea in ideas:+ outline = tuple(idea.step_outline[:MAX_PLANNED_STEPS])+ # The model can only pick from the listed events; anything else is a made-up name.+ if idea.trigger_event not in offered or idea.trigger_event in seen_events or not outline:+ continue+ seen_events.add(idea.trigger_event)+ suggestions.append(+ DataSuggestion(+ id=str(uuid.uuid4()),+ name=clean_copy(idea.name)[:50],+ description=clean_copy(idea.description),+ reason=clean_copy(idea.reason),+ trigger_event=idea.trigger_event,+ weekly_count=counts[idea.trigger_event],+ # Jev judges each event the same way for every customer. An event Jev did not classify is "other".+ stage=jev_stages.get(idea.trigger_event, "other"),+ step_outline=outline,+ )+ )+ ranked = sorted(suggestions, key=lambda item: suggestion_score(item.stage, item.weekly_count), reverse=True)+ return DataSuggestionsResult(+ status="ready",+ suggestions=tuple(pick_one_per_stage(ranked, stage_of=lambda item: item.stage, limit=MAX_SUGGESTIONS)),+ events=planning_events,+ )diff --git a/products/workflows/backend/services/data_suggestions/stages.py b/products/workflows/backend/services/data_suggestions/stages.pynew file mode 100644index 000000000000..3315992e50ce--- /dev/null+++ b/products/workflows/backend/services/data_suggestions/stages.py@@ -0,0 +1,96 @@+"""Ask Jev, the decision model, which customer lifecycle stage each candidate event marks."""++from collections.abc import Sequence+from typing import cast, get_args++import structlog++from posthog.exceptions_capture import capture_exception+from posthog.llm.gateway_client import team_distinct_id+from posthog.llm.managed_decision_model import ManagedDecisionModel+from posthog.llm.system_one import ChoiceAnswer, ChoiceQuestion, SystemOneNotConfigured, SystemOneRequestFailed+from posthog.llm.system_one_client import GATEWAY_MAX_QUESTIONS, build_system_one_client++from products.workflows.backend.facade.contracts import LifecycleStage+from products.workflows.backend.services.data_suggestions.ranking import guess_stage++logger = structlog.get_logger(__name__)++STAGE_MODEL = ManagedDecisionModel("workflows-data-suggestion-stages")+# Below this the answer is a guess, and a wrong high-weight stage would push noise above real moments.+MIN_CONFIDENCE = 0.5+# Signup and onboarding carry the highest ranking weight, so a doubtful answer there pushes a routine or internal+# event above the real moments.+MIN_CONFIDENCE_BY_STAGE: dict[str, float] = {"signup": 0.7, "onboarding": 0.7}+MAX_CLASSIFIED_EVENTS = GATEWAY_MAX_QUESTIONS * 3+_TIMEOUT_SECONDS = 15.0++STAGE_CRITERIA: dict[str, str] = {+ "signup": "A new account or user is created, or someone registers.",+ "onboarding": "A first step after sign-up: setup, activation, a first key action, or inviting teammates.",+ "trial": "A trial starts, is used, or is about to end.",+ "purchase": "Someone pays, upgrades, subscribes, orders or checks out.",+ "churn_risk": "Someone cancels, downgrades, unsubscribes, deletes their account or goes inactive.",+ "failure": "Something went wrong for the user, such as an error, a failed payment or a failed action.",+ "support": "A support ticket, a survey answer or other feedback.",+ "other": "Routine product usage or a technical event that marks none of the moments above.",+}+++class StageClassificationFailed(Exception):+ """Jev is not configured or did not answer, so the stages for this run are unknown."""+++def classify_event_stages(*, team_id: int, event_names: Sequence[str]) -> dict[str, LifecycleStage]:+ """The stage Jev picks for each event it answers with enough confidence. Raises StageClassificationFailed+ when Jev is not configured or fails."""+ names = list(event_names)[:MAX_CLASSIFIED_EVENTS]+ if not names:+ return {}+ try:+ # Without team_id the gateway bills PostHog, so the classification never draws on the customer's credits.+ client = build_system_one_client(+ model=STAGE_MODEL.current(),+ ai_product="workflows",+ distinct_id=team_distinct_id(team_id),+ properties={"ai_feature": "data_suggestion_stages"},+ timeout=_TIMEOUT_SECONDS,+ )+ except SystemOneNotConfigured as error:+ raise StageClassificationFailed() from error++ stages: dict[str, LifecycleStage] = {}+ valid_stages = set(get_args(LifecycleStage))+ for start in range(0, len(names), GATEWAY_MAX_QUESTIONS):+ chunk = names[start : start + GATEWAY_MAX_QUESTIONS]+ questions = {+ f"e{index}": ChoiceQuestion(+ # The name stays in the state, so text in an ingested event name never becomes an instruction.+ instructions=(+ f"Which customer lifecycle stage does the product analytics event at index {index} of "+ "`event_names` in the state mark? Judge only from the name."+ ),+ criteria=STAGE_CRITERIA,+ )+ for index in range(len(chunk))+ }+ try:+ result = client.decide(state={"event_names": chunk}, questions=questions)+ except SystemOneRequestFailed as error:+ logger.warning(+ "workflows.data_suggestions.stage_classification_failed",+ team_id=team_id,+ status_code=error.status_code,+ )+ capture_exception(error, {"team_id": team_id, "chunk_size": len(chunk)})+ raise StageClassificationFailed() from error+ for index, name in enumerate(chunk):+ answer = result.answers.get(f"e{index}")+ if isinstance(answer, ChoiceAnswer) and answer.choice in valid_stages:+ required = MIN_CONFIDENCE_BY_STAGE.get(answer.choice, MIN_CONFIDENCE)+ confident = answer.confidence >= required+ # Jev can call a busy usage event a sign-up, and its volume then outranks every real moment. The two+ # highest weights need the event name to look like the stage too.+ agrees = answer.choice not in MIN_CONFIDENCE_BY_STAGE or guess_stage(name) == answer.choice+ stages[name] = cast(LifecycleStage, answer.choice) if confident and agrees else "other"+ return stagesdiff --git a/products/workflows/backend/services/data_suggestions/team_context.py b/products/workflows/backend/services/data_suggestions/team_context.pynew file mode 100644index 000000000000..7484a5920d2d--- /dev/null+++ b/products/workflows/backend/services/data_suggestions/team_context.py@@ -0,0 +1,64 @@+"""What the team already has: workflows, integrations and saved email templates."""++from posthog.models import Team+from posthog.models.integration import Integration++from products.messaging.backend.facade.api import EmailTemplateSummary, list_email_templates+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow+from products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfig+from products.workflows.backend.services.data_suggestions.builder import EmailSender+from products.workflows.backend.services.data_suggestions.planner import Channel++_TEMPLATES_LIMIT = 20+++def used_trigger_events(team: Team) -> set[str]:+ used: set[str] = set()+ for trigger in HogFlow.objects.filter(team_id=team.id).exclude(status="archived").values_list("trigger", flat=True):+ filters = (trigger or {}).get("filters") or {}+ for event in filters.get("events") or []:+ if isinstance(event, dict) and isinstance(event.get("id"), str):+ used.add(event["id"])+ return used+++def channels(team: Team) -> frozenset[Channel]:+ kinds = set(Integration.objects.filter(team_id=team.id).values_list("kind", flat=True))+ connected: set[Channel] = set()+ if "twilio" in kinds:+ connected.add("sms")+ if kinds & {"apns", "firebase"}:+ connected.add("push")+ return frozenset(connected)+++def slack_integration_id(team: Team) -> int | None:+ return (+ Integration.objects.filter(team_id=team.id, kind="slack")+ .order_by("created_at")+ .values_list("id", flat=True)+ .first()+ )+++def email_sender(team: Team) -> EmailSender | None:+ """The project's default sender, or its only verified sender. With several and no default the step stays+ blank, so the team picks one rather than a draft sending from an identity nobody chose."""+ verified = [+ EmailSender(integration_id=integration.id, email=str(config["email"]), name=str(config.get("name") or ""))+ for integration in Integration.objects.filter(team_id=team.id, kind="email").order_by("created_at")+ if (config := integration.config or {}).get("verified") is True and config.get("email")+ ]+ default_id = (+ TeamWorkflowsConfig.objects.filter(team_id=team.id)+ .values_list("default_email_integration_id", flat=True)+ .first()+ )+ default = next((sender for sender in verified if sender.integration_id == default_id), None)+ if default is not None:+ return default+ return verified[0] if len(verified) == 1 else None+++def email_templates(team: Team) -> tuple[EmailTemplateSummary, ...]:+ return tuple(list_email_templates(team.id, limit=_TEMPLATES_LIMIT))diff --git a/products/workflows/backend/services/hog_flow_templates.py b/products/workflows/backend/services/hog_flow_templates.pyindex 4d9282cb32a9..7a2b679016bf 100644--- a/products/workflows/backend/services/hog_flow_templates.py+++ b/products/workflows/backend/services/hog_flow_templates.py@@ -4,6 +4,10 @@ from uuid import UUIDfrom django.db.models import Q, QuerySet+from posthog.dataclasses import frozen+from posthog.models import Team++from products.cdp.backend.flag_gated_templates import hidden_gated_template_idsfrom products.cdp.backend.models.hog_function_template import HogFunctionTemplatefrom products.workflows.backend.facade.contracts import (FunctionTemplateSchema,@@ -147,3 +151,57 @@ def get_function_template_schema(template_id: str) -> FunctionTemplateSchema | Nif template is None:return Nonereturn FunctionTemplateSchema(type=template.type, inputs_schema=template.inputs_schema)+++@frozen+class StepTemplate:+ template_id: str+ name: str+ description: str+++# The editor offers these as built-in steps, so they are in the step catalog although their status is hidden.+# Keep in sync with the step nodes the editor's build panel lists in+# products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuild.tsx. Flag-gated steps still drop out+# through hidden_gated_template_ids.+_BUILT_IN_STEP_TEMPLATE_IDS = frozenset(+ {+ "template-slack",+ "template-webhook",+ "template-posthog-create-task",+ "template-posthog-run-scout",+ "template-posthog-classify",+ "template-posthog-capture",+ "template-posthog-update-person-properties",+ "template-posthog-group-identify",+ "template-posthog-set-variable",+ }+)++# Email, SMS and push have step types of their own, so they are not catalog steps.+_OWN_STEP_TYPE_TEMPLATE_IDS = frozenset({"template-email", "template-twilio", "template-native-push"})+++def list_step_templates(team: Team) -> list[StepTemplate]:+ """The function templates a workflow step can use, as the editor's step picker offers them."""+ excluded_ids = set(hidden_gated_template_ids(team)) | _OWN_STEP_TYPE_TEMPLATE_IDS+ latest: dict[str, HogFunctionTemplate] = {}+ # DISTINCT ON keeps the newest version of each template in the query, so old versions never reach the worker.+ for template in (+ HogFunctionTemplate.objects.filter(type="destination")+ .exclude(status__in=["deprecated", "coming_soon"])+ .exclude(template_id__in=excluded_ids)+ .order_by("template_id", "-created_at")+ .distinct("template_id")+ .only("template_id", "name", "description", "status", "mapping_templates", "inputs_schema")+ ):+ if template.status == "hidden" and template.template_id not in _BUILT_IN_STEP_TEMPLATE_IDS:+ continue+ # The worker does not apply mappings, so a mapping destination with a secret input cannot run as a step.+ if template.mapping_templates and any(item.get("secret") for item in template.inputs_schema or []):+ continue+ latest[template.template_id] = template+ return [+ StepTemplate(template_id=template_id, name=template.name, description=template.description or "")+ for template_id, template in latest.items()+ ]diff --git a/products/workflows/backend/tasks/__init__.py b/products/workflows/backend/tasks/__init__.pyindex 047db797750b..59bcecd8d2fc 100644--- a/products/workflows/backend/tasks/__init__.py+++ b/products/workflows/backend/tasks/__init__.py@@ -1,3 +1,3 @@-from . import email_sending_tiers, hog_flows, people_import, ses_account_reputation+from . import data_suggestions, email_sending_tiers, hog_flows, people_import, ses_account_reputation-__all__ = ["email_sending_tiers", "hog_flows", "people_import", "ses_account_reputation"]+__all__ = ["data_suggestions", "email_sending_tiers", "hog_flows", "people_import", "ses_account_reputation"]diff --git a/products/workflows/backend/tasks/data_suggestions.py b/products/workflows/backend/tasks/data_suggestions.pynew file mode 100644index 000000000000..34dde4a28f48--- /dev/null+++ b/products/workflows/backend/tasks/data_suggestions.py@@ -0,0 +1,31 @@+from celery import shared_task++from posthog.event_usage import EventSource+from posthog.scoping_audit import skip_team_scope_audit+from posthog.tasks.utils import CeleryQueue++from products.workflows.backend.services.data_suggestions.service import run_build, run_data_suggestions+++@shared_task(ignore_result=True, queue=CeleryQueue.LONG_RUNNING.value)+@skip_team_scope_audit+def generate_data_suggestions(team_id: int, user_id: int, lock_token: str) -> None:+ run_data_suggestions(team_id=team_id, user_id=user_id, lock_token=lock_token)+++@shared_task(ignore_result=True, queue=CeleryQueue.LONG_RUNNING.value)+@skip_team_scope_audit+def build_data_suggestion(team_id: int, user_id: int, suggestion_id: str, lock_token: str, event_source: str) -> None:+ # hog_flow.py imports this package through hog_flow_writes, and the draft check imports hog_flow.py.+ from products.workflows.backend.presentation.views.data_suggestion_drafts import ( # noqa: PLC0415 - circular import+ is_valid_draft,+ )++ run_build(+ team_id=team_id,+ user_id=user_id,+ suggestion_id=suggestion_id,+ caller=event_source,+ lock_token=lock_token,+ is_valid_draft=lambda team, workflow: is_valid_draft(team, workflow, EventSource(event_source)),+ )diff --git a/products/workflows/backend/test/test_data_suggestions.py b/products/workflows/backend/test/test_data_suggestions.pynew file mode 100644index 000000000000..8eb7fe938f33--- /dev/null+++ b/products/workflows/backend/test/test_data_suggestions.py@@ -0,0 +1,400 @@+import uuid+from typing import Any, get_args++from unittest.mock import MagicMock, patch++from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.llm.system_one import ChoiceAnswer, SystemOneNotConfigured, SystemOneRequestFailed, SystemOneResult++from products.messaging.backend.facade.api import EmailTemplateContent+from products.workflows.backend.facade.contracts import DataSuggestionsStatus, LifecycleStage, OutlineKind+from products.workflows.backend.presentation.views.workflow_data_suggestions import (+ DataSuggestionsStatus as DataSuggestionsStatusChoices,+ DataSuggestionStage,+ DataSuggestionStepKind,+)+from products.workflows.backend.services.data_suggestions.builder import BuildContext, build_workflow+from products.workflows.backend.services.data_suggestions.email_design import EmailCopy, render_email+from products.workflows.backend.services.data_suggestions.llm import invoke_structured, strict_schema+from products.workflows.backend.services.data_suggestions.planner import (+ PlannedBranch,+ PlannedStep,+ PlannedWorkflow,+ WorkflowIdea,+)+from products.workflows.backend.services.data_suggestions.ranking import select_prompt_events, suggestion_score+from products.workflows.backend.services.data_suggestions.stages import StageClassificationFailed, classify_event_stages++IDEA = WorkflowIdea(+ name="Trial started upgrade nudge",+ description="Nudge people to upgrade while their trial is running.",+ reason="trial_started fires every day.",+ trigger_event="trial_started",+ step_outline=["email", "delay", "email"],+)+++def step(step_id: str = "email_1", **overrides: Any) -> PlannedStep:+ values: dict[str, Any] = {+ "id": step_id,+ "type": "email",+ "name": "Email",+ "setup_note": "",+ "next": None,+ "branches": None,+ "template_id": None,+ "wait_event": None,+ "wait_event_next": None,+ "duration": None,+ "email_template_id": None,+ "email_subject": "Your trial started",+ "email_heading": "Welcome to your trial",+ "email_paragraphs": ["Here is how to get started."],+ "slack_message": None,+ }+ values.update(overrides)+ return PlannedStep(**values)+++def plan(*steps: PlannedStep, first_step: str | None = None) -> PlannedWorkflow:+ return PlannedWorkflow(first_step=first_step or (steps[0].id if steps else "email_1"), steps=list(steps))+++def branch(label: str, next_id: str | None, percentage: int | None = None) -> PlannedBranch:+ return PlannedBranch(label=label, percentage=percentage, next=next_id)+++def context(**overrides: Any) -> BuildContext:+ values: dict[str, Any] = {+ "allowed_events": frozenset({"trial_started", "onboarding_completed"}),+ "step_template_ids": frozenset({"template-webhook", "template-slack"}),+ "channels": frozenset(),+ "email_templates": {},+ "sender": None,+ "slack_integration_id": None,+ }+ values.update(overrides)+ return BuildContext(**values)+++def edges(built: Any) -> list[tuple]:+ return [(edge["from"], edge["to"], edge["type"], edge.get("index")) for edge in built.workflow["edges"]]+++class TestDataSuggestions(SimpleTestCase):+ def test_email_escapes_copy_and_carries_an_editor_design(self) -> None:+ email = render_email(EmailCopy(subject="Hi", heading="<script>x</script>", paragraphs=("a & b",)))+ assert "<script>" not in email.html+ assert "a & b" in email.html+ assert email.design["body"]["rows"]++ @parameterized.expand(+ [+ ("event the project does not send", {"trigger_event": "made_up_event"}, plan(step())),+ ("unknown saved template", {}, plan(step(email_template_id="not-a-template"))),+ ("email without copy", {}, plan(step(email_heading=None))),+ ("delay without a duration", {}, plan(step("wait", type="delay"))),+ ("no steps", {}, plan()),+ ("sms without an sms provider", {}, plan(step("text", type="sms"))),+ ("push without a push provider", {}, plan(step("notify", type="push"))),+ ("first step that does not exist", {}, plan(step(), first_step="missing")),+ ("next that does not exist", {}, plan(step(next="missing"))),+ ("duplicate step ids", {}, plan(step(), step())),+ ("template outside the catalog", {}, plan(step("hook", type="function", template_id="template-made-up"))),+ (+ "loop back to an earlier step",+ {},+ plan(step("a", next="b"), step("b", type="delay", duration="1d", next="a")),+ ),+ ("step no path reaches", {}, plan(step("a"), step("b", type="delay", duration="1d"))),+ ("branch without paths", {}, plan(step("check", type="conditional_branch"))),+ ("wait with no event", {}, plan(step("wait", type="wait_until_event"))),+ (+ "wait on an event the project does not send",+ {},+ plan(step("wait", type="wait_until_event", wait_event="made_up_event")),+ ),+ (+ "step reachable only through a split's continue edge",+ {},+ plan(+ step("ab", type="random_split", branches=[branch("A", None, 50), branch("B", None, 50)], next="x"),+ step("x", type="delay", duration="1d"),+ ),+ ),+ (+ "split with a share outside 1 to 100",+ {},+ plan(step("ab", type="random_split", branches=[branch("A", None, -50), branch("B", None, 150)])),+ ),+ (+ "split that does not add up to 100",+ {},+ plan(step("ab", type="random_split", branches=[branch("A", None, 50), branch("B", None, 40)])),+ ),+ (+ "more than 20 steps",+ {},+ plan(+ *[step(f"s{index}", type="delay", duration="1d", next=f"s{index + 1}") for index in range(20)],+ step("s20"),+ ),+ ),+ ]+ )+ def test_build_workflow_rejects_plans_that_do_not_hold_up(+ self, _name: str, idea_overrides: dict, planned: PlannedWorkflow+ ) -> None:+ assert build_workflow(IDEA.model_copy(update=idea_overrides), planned, context()) is None++ def test_build_workflow_wires_waits_branches_and_blank_integration_steps(self) -> None:+ built = build_workflow(+ IDEA,+ plan(+ step("welcome", next="wait"),+ step(+ "wait",+ type="wait_until_event",+ wait_event="onboarding_completed",+ wait_event_next="notify",+ duration="2d",+ next="split",+ ),+ step("notify", type="function", template_id="template-webhook", setup_note="Add the endpoint URL"),+ step("split", type="random_split", branches=[branch("A", "nudge", 50), branch("B", None, 50)]),+ step("nudge", type="slack", slack_message="Trial user needs help", next="window"),+ step("window", type="wait_until_time_window"),+ ),+ context(once_per_person=True),+ )+ assert built is not None+ assert built.workflow["trigger_masking"] == {"hash": "{person.id}", "ttl": None, "threshold": None}+ assert edges(built) == [+ ("trigger_node", "action_0_email", "continue", None),+ ("action_0_email", "action_1_wait_until_event", "continue", None),+ ("action_1_wait_until_event", "action_2_function", "branch", 0),+ ("action_1_wait_until_event", "action_3_random_split", "continue", None),+ ("action_2_function", "exit_node", "continue", None),+ ("action_3_random_split", "action_4_slack", "branch", 0),+ ("action_3_random_split", "exit_node", "branch", 1),+ ("action_3_random_split", "exit_node", "continue", None),+ ("action_4_slack", "action_5_wait_until_time_window", "continue", None),+ ("action_5_wait_until_time_window", "exit_node", "continue", None),+ ]+ actions = {action["id"]: action for action in built.workflow["actions"]}+ wait_config = actions["action_1_wait_until_event"]["config"]+ assert wait_config["events"][0]["filters"]["events"][0]["id"] == "onboarding_completed"+ assert wait_config["max_wait_duration"] == "2d"+ assert actions["action_2_function"]["config"] == {"template_id": "template-webhook", "inputs": {}}+ assert actions["action_2_function"]["description"] == "Add the endpoint URL"+ assert actions["action_3_random_split"]["config"]["cohorts"] == [+ {"percentage": 50, "name": "A"},+ {"percentage": 50, "name": "B"},+ ]+ slack_inputs = actions["action_4_slack"]["config"]["inputs"]+ assert "slack_workspace" not in slack_inputs+ assert slack_inputs["text"]["value"] == "Trial user needs help"+ assert actions["action_5_wait_until_time_window"]["config"]["day"] == "weekday"++ @patch("products.workflows.backend.services.data_suggestions.llm.logger")+ @patch("products.workflows.backend.services.data_suggestions.llm.is_privacy_mode_enabled", return_value=True)+ @patch("products.workflows.backend.services.data_suggestions.llm.MaxChatAnthropic")+ def test_a_malformed_answer_is_logged_without_its_content(+ self, chat: MagicMock, _privacy: MagicMock, logger: MagicMock+ ) -> None:+ chat.return_value.invoke.return_value.content = '{"first_step": "secret_signup_event"}'++ result = invoke_structured(+ team=MagicMock(id=1),+ user=MagicMock(distinct_id="user-1"),+ model="claude-test",+ effort="low",+ feature="test",+ schema=PlannedWorkflow,+ system="",+ human="",+ excluded_values=frozenset(),+ )++ assert result is None+ assert "secret_signup_event" not in str(logger.warning.call_args)+ assert "exc_info" not in logger.warning.call_args.kwargs++ def test_plan_schema_only_offers_connected_channels_and_project_events(self) -> None:+ schema = strict_schema(PlannedWorkflow, frozenset({"sms", "push"}), {"wait_event": ["trial_started", "sms"]})+ wait_event = schema["$defs"]["PlannedStep"]["properties"]["wait_event"]["anyOf"]+ assert {"type": "string", "enum": ["trial_started", "sms"]} in wait_event+ assert {"type": "null"} in wait_event+ step_types = schema["$defs"]["PlannedStep"]["properties"]["type"]["enum"]+ assert "email" in step_types+ assert "sms" not in step_types+ assert "push" not in step_types+ assert schema["$defs"]["PlannedStep"]["additionalProperties"] is False++ def test_build_workflow_reuses_a_saved_template(self) -> None:+ saved = EmailTemplateContent(+ id=uuid.uuid4(),+ name="Trial welcome",+ email={"subject": "Saved subject", "html": "<p>saved</p>", "text": None, "design": {"body": {}}},+ )+ built = build_workflow(IDEA, plan(step(email_template_id="tpl-1")), context(email_templates={"tpl-1": saved}))+ assert built is not None+ assert built.uses_saved_template+ email = built.workflow["actions"][1]["config"]["inputs"]["email"]["value"]+ assert email["subject"] == "Saved subject"+ assert email["html"] == "<p>saved</p>"+ assert "text" not in email++ def test_build_workflow_puts_a_wait_between_back_to_back_emails(self) -> None:+ built = build_workflow(+ IDEA, plan(step("first", next="second"), step("second", email_subject="Second")), context()+ )+ assert built is not None+ assert [action["type"] for action in built.workflow["actions"][1:4]] == [+ "function_email",+ "delay",+ "function_email",+ ]+ assert built.workflow["actions"][2]["config"] == {"delay_duration": "1d"}+ assert edges(built)[1:3] == [+ ("action_0_email", "action_1_delay", "continue", None),+ ("action_1_delay", "action_2_email", "continue", None),+ ]++ @parameterized.expand(+ [+ (+ "liquid in an email",+ step(email_paragraphs=["Hi {{ person.properties.secret }} there {% if x %}"]),+ lambda inputs: inputs["email"]["value"]["html"],+ "person.properties.secret",+ ),+ (+ "hog in a slack message",+ step("ping", type="slack", slack_message="New sign-up {person.properties.secret} here"),+ lambda inputs: inputs["text"]["value"],+ "{person",+ ),+ (+ "nested braces in a slack message",+ step("ping", type="slack", slack_message="New sign-up {{x}person.properties.secret} here"),+ lambda inputs: inputs["text"]["value"],+ "{person",+ ),+ ]+ )+ def test_build_workflow_strips_template_tags_from_model_copy(+ self, _name: str, planned: PlannedStep, copy_of: Any, leftover: str+ ) -> None:+ built = build_workflow(IDEA, plan(planned), context())+ assert built is not None+ copy = copy_of(built.workflow["actions"][1]["config"]["inputs"])+ assert leftover not in copy+ assert "{%" not in copy++ @parameterized.expand(+ [+ ("starts with a capital", "welcome new trial users", "Welcome new trial users"),+ ("an em dash becomes a comma", "Welcome — let's get started", "Welcome, let's get started"),+ ]+ )+ def test_build_workflow_cleans_model_copy(self, _name: str, written: str, expected: str) -> None:+ built = build_workflow(IDEA.model_copy(update={"name": written}), plan(step()), context())+ assert built is not None+ assert built.workflow["name"] == expected++ @parameterized.expand(+ [+ ("stage", DataSuggestionStage, LifecycleStage),+ ("step kind", DataSuggestionStepKind, OutlineKind),+ ("status", DataSuggestionsStatusChoices, DataSuggestionsStatus),+ ]+ )+ def test_api_choices_match_the_values_the_service_returns(self, _name: str, choices: Any, literal: Any) -> None:+ assert set(choices.values) == set(get_args(literal))++ def test_select_prompt_events_keeps_quiet_lifecycle_events_and_drops_noise(self) -> None:+ counts = {"query executed": 9000, "page scrolled": 5000, "user_signed_up": 40, "rare_click": 2}+ assert select_prompt_events(counts, limit=2) == [("user_signed_up", 40), ("query executed", 9000)]++ def test_select_prompt_events_does_not_let_one_name_pattern_fill_the_list(self) -> None:+ counts = {f"upload_{index}_failed": 1000 + index for index in range(40)}+ counts |= {"user_signed_up": 10, "first_event_ingested": 500}++ selected = [name for name, _ in select_prompt_events(counts, limit=20)]++ assert "user_signed_up" in selected+ assert "first_event_ingested" in selected++ @parameterized.expand(+ [+ ("quiet sign-up beats busy usage", ("signup", 40), ("other", 10_000)),+ ("onboarding beats a busier failure", ("onboarding", 20), ("failure", 500)),+ ("volume decides within a stage", ("trial", 300), ("trial", 30)),+ ]+ )+ def test_suggestion_score_prefers_welcome_flows(self, _name: str, higher: tuple, lower: tuple) -> None:+ assert suggestion_score(*higher) > suggestion_score(*lower)++ def test_select_prompt_events_ranks_by_jev_stage_when_known(self) -> None:+ counts = {"query executed": 9000, "account_opened": 40, "report_viewed": 300}+ stages: dict[str, LifecycleStage] = {+ "account_opened": "signup",+ "query executed": "other",+ "report_viewed": "other",+ }+ assert [name for name, _ in select_prompt_events(counts, limit=2, stages=stages)] == [+ "account_opened",+ "query executed",+ ]++ @patch("products.workflows.backend.services.data_suggestions.stages.build_system_one_client")+ def test_classify_event_stages_keeps_confident_answers_only(self, build_client: MagicMock) -> None:+ build_client.return_value.decide.return_value = SystemOneResult(+ model="jev-test",+ answers={+ "e0": ChoiceAnswer(choice="signup", confidence=0.9, probabilities={"signup": 0.9}),+ "e1": ChoiceAnswer(choice="purchase", confidence=0.3, probabilities={"purchase": 0.3}),+ "e2": ChoiceAnswer(choice="signup", confidence=0.6, probabilities={"signup": 0.6}),+ "e3": ChoiceAnswer(choice="failure", confidence=0.6, probabilities={"failure": 0.6}),+ "e4": ChoiceAnswer(choice="signup", confidence=0.9, probabilities={"signup": 0.9}),+ },+ input_tokens=10,+ )+ assert classify_event_stages(+ team_id=1,+ event_names=["account_created", "thing_happened", "summary_generated", "upload_failed", "query executed"],+ ) == {+ "account_created": "signup",+ "thing_happened": "other",+ "summary_generated": "other",+ "upload_failed": "failure",+ "query executed": "other",+ }++ @parameterized.expand([("jev is not configured", True), ("jev does not answer", False)])+ @patch("products.workflows.backend.services.data_suggestions.stages.build_system_one_client")+ def test_classify_event_stages_fails_without_a_working_jev(+ self, _name: str, not_configured: bool, build_client: MagicMock+ ) -> None:+ if not_configured:+ build_client.side_effect = SystemOneNotConfigured("no gateway")+ else:+ build_client.return_value.decide.side_effect = SystemOneRequestFailed("boom", status_code=529)+ with self.assertRaises(StageClassificationFailed):+ classify_event_stages(team_id=1, event_names=["signed_up"])++ @parameterized.expand(+ [+ ("workspace creation is a sign-up moment", "workspace_created", True),+ ("account deletion is churn", "account_deleted", True),+ ("deleting a product object is not churn", "hog_flow_deleted", False),+ ("plain usage is not a lifecycle moment", "dashboard_viewed", False),+ ]+ )+ def test_fallback_patterns_put_lifecycle_events_first(self, _name: str, event: str, first: bool) -> None:+ selected = select_prompt_events({"busy_usage": 5000, event: 10}, limit=2)+ assert (selected[0][0] == event) is firstdiff --git a/products/workflows/backend/tests/api/test_workflow_data_suggestions.py b/products/workflows/backend/tests/api/test_workflow_data_suggestions.pynew file mode 100644index 000000000000..b8e4cf8b4e2c--- /dev/null+++ b/products/workflows/backend/tests/api/test_workflow_data_suggestions.py@@ -0,0 +1,699 @@+import time_machine+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events+from unittest.mock import MagicMock, patch++from django.core.cache import cache+from django.db import OperationalError+from django.utils import timezone++from clickhouse_driver.errors import NetworkError+from parameterized import parameterized++from posthog.errors import InternalCHQueryError+from posthog.exceptions import ClickHouseQueryTimeOut+from posthog.models.integration import Integration+from posthog.models.personal_api_key import PersonalAPIKey, hash_key_value+from posthog.models.utils import generate_random_token_personal++from products.cdp.backend.templates.hog_function_template import sync_template_to_db+from products.messaging.backend.facade.testing import create_message_template_for_test+from products.workflows.backend.facade.contracts import DataSuggestionsResult+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow+from products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfig+from products.workflows.backend.services.data_suggestions.builder import BuildContext, build_workflow+from products.workflows.backend.services.data_suggestions.event_volume import FULL_SCAN_MAX_WEEKLY_EVENTS, weekly_counts+from products.workflows.backend.services.data_suggestions.planner import (+ PlannedBranch,+ PlannedStep,+ PlannedWorkflow,+ WorkflowIdea,+)+from products.workflows.backend.services.data_suggestions.service import (+ FAILURE_CACHE_TTL_SECONDS,+ _build_key,+ _cache_key,+ _generation_lock_key,+ _to_cache,+ run_data_suggestions,+ start_build,+)+from products.workflows.backend.services.data_suggestions.stages import StageClassificationFailed+from products.workflows.backend.services.data_suggestions.team_context import email_sender+from products.workflows.backend.services.email_sending_controls import ensure_workflows_config+from products.workflows.backend.tests.api.test_hog_flow_action_email import _email_function_template, webhook_template++SERVICE = "products.workflows.backend.services.data_suggestions.service"+EVENT_VOLUME = "products.workflows.backend.services.data_suggestions.event_volume"+VIEW = "products.workflows.backend.presentation.views.workflow_data_suggestions"+FLAG = f"{VIEW}.posthoganalytics.feature_enabled"+++def _idea(trigger_event: str) -> WorkflowIdea:+ return WorkflowIdea(+ name=f"Follow up on {trigger_event}",+ description="Send a short email after the event.",+ reason=f"{trigger_event} happens often.",+ trigger_event=trigger_event,+ step_outline=["email", "delay", "email"],+ )+++def _step(step_id: str, step_type: str, **overrides: object) -> PlannedStep:+ values: dict = {+ "id": step_id,+ "type": step_type,+ "name": step_id,+ "setup_note": "",+ "next": None,+ "branches": None,+ "template_id": None,+ "wait_event": None,+ "wait_event_next": None,+ "duration": None,+ "email_template_id": None,+ "email_subject": None,+ "email_heading": None,+ "email_paragraphs": None,+ "slack_message": None,+ }+ values.update(overrides)+ return PlannedStep(**values)+++def _email_step(step_id: str, subject: str, **overrides: object) -> PlannedStep:+ return _step(+ step_id,+ "email",+ email_subject=subject,+ email_heading=subject,+ email_paragraphs=["Thanks for trying the product."],+ **overrides,+ )+++@patch(FLAG, return_value=True)+class TestWorkflowDataSuggestions(ClickhouseTestMixin, APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ cache.delete(_cache_key(self.team))+ self.jev_configured = patch(f"{SERVICE}.system_one_configured", return_value=True).start()+ # FLAG patches the shared feature_enabled, which the privacy mode check reads too.+ self.privacy_mode = patch(f"{SERVICE}.is_privacy_mode_enabled", return_value=False).start()+ patch(f"{SERVICE}.classify_event_stages", return_value={}).start()+ self.addCleanup(patch.stopall)+ sync_template_to_db(_email_function_template())+ sync_template_to_db(webhook_template)+ for event, count in [+ ("trial_started", 3),+ ("signed_up", 2),+ ("$pageview", 5),+ ("user_registered", 3),+ ("query executed", 30),+ ]:+ for index in range(count):+ _create_event(team=self.team, event=event, distinct_id=f"person-{index}")+ flush_persons_and_events()++ def _list(self, refresh: bool = False) -> dict:+ url = f"/api/projects/{self.team.id}/workflow_data_suggestions/"+ # Celery runs eagerly in tests, so the run that generate starts has finished when it returns.+ started = self.client.post(f"{url}generate/", {"refresh": refresh}, format="json")+ assert started.status_code == 200, started.json()+ response = self.client.get(f"{url}current/")+ assert response.status_code == 200, response.json()+ return response.json()++ @patch(f"{SERVICE}.suggest_ideas")+ def test_suggests_only_busy_events_and_caches_the_answer(self, suggest_ideas: MagicMock, _flag) -> None:+ suggest_ideas.return_value = [_idea("trial_started"), _idea("made_up_event")]++ body = self._list()++ context = suggest_ideas.call_args.kwargs["context"]+ assert dict(context.events) == {"trial_started": 3, "user_registered": 3, "query executed": 30}+ assert body["status"] == "ready"+ assert [(s["trigger_event"], s["weekly_count"]) for s in body["suggestions"]] == [("trial_started", 3)]+ assert self._list()["suggestions"] == body["suggestions"]+ assert suggest_ideas.call_count == 1++ @patch(f"{SERVICE}.classify_event_stages")+ @patch(f"{SERVICE}.suggest_ideas")+ def test_ranks_welcome_flows_above_busier_events(+ self, suggest_ideas: MagicMock, classify: MagicMock, _flag+ ) -> None:+ classify.return_value = {"query executed": "other", "trial_started": "trial", "user_registered": "signup"}+ suggest_ideas.return_value = [+ _idea("query executed"),+ _idea("trial_started"),+ _idea("user_registered"),+ ]++ body = self._list()++ assert [(s["trigger_event"], s["stage"]) for s in body["suggestions"]] == [+ ("user_registered", "signup"),+ ("trial_started", "trial"),+ ("query executed", "other"),+ ]++ @patch(f"{SERVICE}.classify_event_stages")+ @patch(f"{SERVICE}.suggest_ideas")+ def test_keeps_only_the_best_idea_per_stage(self, suggest_ideas: MagicMock, classify: MagicMock, _flag) -> None:+ classify.return_value = {"user_registered": "signup", "query executed": "signup", "trial_started": "trial"}+ suggest_ideas.return_value = [+ _idea("user_registered"),+ _idea("query executed"),+ _idea("trial_started"),+ ]++ body = self._list()++ assert [(s["trigger_event"], s["stage"]) for s in body["suggestions"]] == [+ ("query executed", "signup"),+ ("trial_started", "trial"),+ ]++ @patch(f"{SERVICE}.classify_event_stages")+ @patch(f"{SERVICE}.suggest_ideas")+ def test_jev_stages_override_the_llm_label_and_reach_the_prompt(+ self, suggest_ideas: MagicMock, classify: MagicMock, _flag+ ) -> None:+ classify.return_value = {"query executed": "onboarding", "trial_started": "other"}+ suggest_ideas.return_value = [_idea("trial_started"), _idea("query executed")]++ body = self._list()++ assert suggest_ideas.call_args.kwargs["context"].stages == classify.return_value+ assert [(s["trigger_event"], s["stage"]) for s in body["suggestions"]] == [+ ("query executed", "onboarding"),+ ("trial_started", "other"),+ ]++ @parameterized.expand(+ [+ ("jev fails", StageClassificationFailed(), []),+ ("claude returns nothing", None, []),+ ]+ )+ @patch(f"{SERVICE}.classify_event_stages")+ @patch(f"{SERVICE}.suggest_ideas")+ def test_a_failed_run_shows_nothing_and_is_not_retried_on_every_visit(+ self,+ _name: str,+ classify_error: Exception | None,+ ideas: list,+ suggest_ideas: MagicMock,+ classify: MagicMock,+ _flag,+ ) -> None:+ classify.side_effect = classify_error+ classify.return_value = {}+ suggest_ideas.return_value = ideas++ assert self._list() == {"status": "unavailable", "suggestions": []}+ assert self._list() == {"status": "unavailable", "suggestions": []}+ assert classify.call_count == 1++ @patch(f"{SERVICE}.suggest_ideas")+ def test_an_empty_answer_is_retried_soon(self, suggest_ideas: MagicMock, _flag) -> None:+ suggest_ideas.return_value = [_idea("made_up_event")]++ with time_machine.travel(timezone.now(), tick=False) as clock:+ assert self._list() == {"status": "ready", "suggestions": []}+ clock.shift(FAILURE_CACHE_TTL_SECONDS + 60)+ self._list()++ assert suggest_ideas.call_count == 2++ @patch(f"{EVENT_VOLUME}.estimated_weekly_events", return_value=2 * FULL_SCAN_MAX_WEEKLY_EVENTS)+ def test_large_teams_get_sampled_counts_scaled_back_up(self, _estimate: MagicMock, _flag) -> None:+ counts = weekly_counts(self.team)++ assert counts["query executed"] % 2 == 0++ @patch(f"{EVENT_VOLUME}.estimated_weekly_events", return_value=10**9 * FULL_SCAN_MAX_WEEKLY_EVENTS)+ def test_events_a_sample_misses_are_counted_exactly(self, _estimate: MagicMock, _flag) -> None:+ assert weekly_counts(self.team) == {+ "trial_started": 3,+ "signed_up": 2,+ "user_registered": 3,+ "query executed": 30,+ }++ def test_counts_every_event_past_the_default_row_limit(self, _flag) -> None:+ names = [f"quiet_{index}" for index in range(150)]+ for name in names:+ _create_event(team=self.team, event=name, distinct_id="person-1")+ flush_persons_and_events()++ assert set(names) <= set(weekly_counts(self.team))++ @patch(f"{SERVICE}.suggest_ideas")+ def test_a_queued_retry_reads_building_not_the_old_failure(self, suggest_ideas: MagicMock, _flag) -> None:+ suggest_ideas.return_value = [_idea("trial_started")]+ suggestion_id = self._list()["suggestions"][0]["id"]+ cache.set(_build_key(self.team.id, suggestion_id, "web"), {"status": "failed"}, 60)++ retry = start_build(+ team=self.team, suggestion_id=suggestion_id, caller="web", retry=True, enqueue=lambda _token: None+ )+ poll = start_build(+ team=self.team, suggestion_id=suggestion_id, caller="web", retry=False, enqueue=lambda _token: None+ )++ assert retry.status == poll.status == "building"++ @patch(f"{SERVICE}.suggest_ideas", return_value=[])+ def test_events_a_workflow_already_triggers_on_are_not_offered(self, suggest_ideas: MagicMock, _flag) -> None:+ HogFlow.objects.create(+ team=self.team,+ name="Existing trial flow",+ status="draft",+ trigger={"type": "event", "filters": {"events": [{"id": "trial_started", "type": "events"}]}},+ actions=[],+ )++ self._list()++ assert "trial_started" not in dict(suggest_ideas.call_args.kwargs["context"].events)++ @parameterized.expand(+ [+ ("query timeout", ClickHouseQueryTimeOut()),+ ("query error", InternalCHQueryError("boom")),+ ("connection failure", NetworkError("Code: 209. (host:9440)")),+ ("database error", OperationalError("server closed the connection")),+ ]+ )+ @patch(f"{EVENT_VOLUME}.execute_hogql_query")+ def test_a_failed_count_query_shows_nothing_and_is_not_retried_on_every_visit(+ self, _name: str, error: Exception, execute: MagicMock, _flag+ ) -> None:+ execute.side_effect = error++ assert self._list() == {"status": "unavailable", "suggestions": []}+ assert self._list() == {"status": "unavailable", "suggestions": []}+ assert execute.call_count == 1++ @parameterized.expand(+ [+ ("read", "current", {}, "cached", 200),+ ("generate answered from the cache", "generate", {}, "cached", 200),+ ("generate that has to run", "generate", {}, "empty", 429),+ ("generate that joins a running run", "generate", {}, "running", 200),+ ("refresh while a run is going", "generate", {"refresh": True}, "running", 429),+ ("refresh", "generate", {"refresh": True}, "cached", 429),+ ("refresh sent as 1", "generate", {"refresh": "1"}, "cached", 429),+ ("build", "build", {"suggestion_id": "missing"}, "cached", 429),+ ]+ )+ @patch(f"{VIEW}.AIBurstRateThrottle.wait", return_value=None)+ @patch(f"{VIEW}.AIBurstRateThrottle.allow_request", return_value=False)+ @patch(f"{SERVICE}.suggest_ideas", return_value=[])+ def test_only_calls_that_can_run_an_llm_are_throttled(+ self,+ _name: str,+ endpoint: str,+ params: dict,+ state: str,+ status: int,+ _suggest_ideas: MagicMock,+ _allow: MagicMock,+ _wait: MagicMock,+ _flag,+ ) -> None:+ if state == "cached":+ cache.set(_cache_key(self.team), _to_cache(DataSuggestionsResult(status="ready", suggestions=())), 60)+ elif state == "running":+ cache.set(_generation_lock_key(self.team), "other-run", 60)+ url = f"/api/projects/{self.team.id}/workflow_data_suggestions/{endpoint}/"+ if endpoint == "current":+ response = self.client.get(url)+ else:+ response = self.client.post(url, params, format="json")++ assert response.status_code == status++ @parameterized.expand(+ [+ ("read", ["hog_flow:read", "query:read"], "get", "current", 200),+ ("read without query access", ["hog_flow:read"], "get", "current", 403),+ ("generate with a read-only key", ["hog_flow:read", "query:read"], "post", "generate", 403),+ ("generate without query access", ["hog_flow:write"], "post", "generate", 403),+ ]+ )+ @patch(f"{SERVICE}.suggest_ideas", return_value=[])+ def test_a_key_needs_workflow_and_query_scopes(+ self, _name: str, scopes: list[str], method: str, endpoint: str, status: int, suggest_ideas: MagicMock, _flag+ ) -> None:+ key = generate_random_token_personal()+ PersonalAPIKey.objects.create(label="key", user=self.user, secure_value=hash_key_value(key), scopes=scopes)+ self.client.logout()++ response = getattr(self.client, method)(+ f"/api/projects/{self.team.id}/workflow_data_suggestions/{endpoint}/",+ headers={"authorization": f"Bearer {key}"},+ )++ assert response.status_code == status+ suggest_ideas.assert_not_called()++ @parameterized.expand(+ [+ ("without ai data processing approval", False, True, False, "ai_not_approved"),+ ("without jev", True, False, False, "unavailable"),+ ("in privacy mode", True, True, True, "unavailable"),+ ]+ )+ @patch(f"{SERVICE}.suggest_ideas")+ def test_ai_is_not_called(+ self,+ _name: str,+ approved: bool,+ jev_configured: bool,+ privacy_mode: bool,+ status: str,+ suggest_ideas: MagicMock,+ _flag,+ ) -> None:+ self.organization.is_ai_data_processing_approved = approved+ self.organization.save()+ self.jev_configured.return_value = jev_configured+ self.privacy_mode.return_value = privacy_mode++ assert self._list() == {"status": status, "suggestions": []}+ suggest_ideas.assert_not_called()++ @patch(f"{SERVICE}.classify_event_stages")+ @patch(f"{SERVICE}.suggest_ideas")+ def test_a_failed_refresh_keeps_the_working_suggestions(+ self, suggest_ideas: MagicMock, classify: MagicMock, _flag+ ) -> None:+ classify.return_value = {}+ suggest_ideas.return_value = [_idea("trial_started")]+ suggestions = self._list()["suggestions"]+ classify.side_effect = StageClassificationFailed()++ assert self._list(refresh=True) == {"status": "ready", "suggestions": suggestions}+ assert self._list() == {"status": "ready", "suggestions": suggestions}++ @patch(f"{SERVICE}.plan_steps")+ @patch(f"{SERVICE}.suggest_ideas")+ def test_build_returns_a_draft_the_create_endpoint_accepts(+ self, suggest_ideas: MagicMock, plan_steps: MagicMock, _flag+ ) -> None:+ suggest_ideas.return_value = [_idea("trial_started")]+ plan_steps.return_value = PlannedWorkflow(+ first_step="welcome",+ steps=[+ _email_step("welcome", "Your trial started", next="wait"),+ _step(+ "wait",+ "wait_until_event",+ wait_event="user_registered",+ wait_event_next="notify",+ duration="3d",+ next="check",+ ),+ _step("notify", "function", template_id="template-webhook", setup_note="Add the endpoint URL"),+ _step(+ "check",+ "conditional_branch",+ branches=[PlannedBranch(label="Is on a paid plan", percentage=None, next=None)],+ next="nudge",+ ),+ _email_step("nudge", "Ready to upgrade?"),+ ],+ )+ suggestion_id = self._list()["suggestions"][0]["id"]+ build_url = f"/api/projects/{self.team.id}/workflow_data_suggestions/build/"++ build = self.client.post(build_url, {"suggestion_id": suggestion_id}, format="json")+ assert build.status_code == 200, build.json()+ assert build.json()["status"] == "ready"+ workflow = build.json()["workflow"]+ retry = self.client.post(build_url, {"suggestion_id": suggestion_id}, format="json")+ assert retry.json()["workflow"] == workflow+ assert plan_steps.call_count == 1+ assert [action["type"] for action in workflow["actions"]] == [+ "trigger",+ "function_email",+ "wait_until_condition",+ "function",+ "conditional_branch",+ "function_email",+ "exit",+ ]+ catalog = {template.template_id for template in plan_steps.call_args.kwargs["context"].step_templates}+ assert "template-webhook" in catalog+ assert "template-email" not in catalog++ create = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows", {**workflow, "status": "draft"}, format="json"+ )+ assert create.status_code == 201, create.json()+ assert create.json()["trigger"]["filters"]["events"][0]["id"] == "trial_started"++ def test_a_built_branch_has_unset_conditions_shaped_like_an_editor_branch(self, _flag) -> None:+ built = build_workflow(+ _idea("trial_started"),+ PlannedWorkflow(+ first_step="check",+ steps=[+ _step(+ "check",+ "conditional_branch",+ branches=[PlannedBranch(label="Is on a paid plan", percentage=None, next=None)],+ )+ ],+ ),+ BuildContext(+ allowed_events=frozenset({"trial_started"}),+ step_template_ids=frozenset(),+ channels=frozenset(),+ email_templates={},+ sender=None,+ slack_integration_id=None,+ ),+ )+ assert built is not None++ branch = next(action for action in built.workflow["actions"] if action["type"] == "conditional_branch")+ # The editor's schema rejects null filters, so a suggested branch must look like one added by hand.+ assert branch["config"]["conditions"] == [{"filters": {}, "name": "Is on a paid plan"}]++ @patch(f"{SERVICE}.suggest_ideas")+ def test_a_second_request_does_not_generate_while_one_is_running(self, suggest_ideas: MagicMock, _flag) -> None:+ suggest_ideas.return_value = [_idea("trial_started")]+ assert self._list()["status"] == "ready"+ cache.add(_generation_lock_key(self.team), "another-run", 60)++ assert self._list(refresh=True) == {"status": "generating", "suggestions": []}+ assert suggest_ideas.call_count == 1++ cache.delete(_generation_lock_key(self.team))+ self._list(refresh=True)+ assert suggest_ideas.call_count == 2++ @parameterized.expand(+ [+ ("ai consent withdrawn after the click", False, "own-run", "own-run", 0, False, False),+ ("a run whose lease went to a newer run", True, "newer-run", "own-run", 1, True, False),+ ("a replica that has not seen the lock yet", True, None, "own-run", 1, False, True),+ ]+ )+ @patch(f"{SERVICE}.suggest_ideas", return_value=[])+ def test_a_background_run_checks_consent_and_only_writes_while_no_newer_run_holds_the_lock(+ self,+ _name: str,+ approved: bool,+ holder: str | None,+ token: str,+ model_calls: int,+ lock_left: bool,+ cached: bool,+ suggest_ideas: MagicMock,+ _flag,+ ) -> None:+ self.organization.is_ai_data_processing_approved = approved+ self.organization.save()+ if holder is not None:+ cache.set(_generation_lock_key(self.team), holder, 60)++ run_data_suggestions(team_id=self.team.id, user_id=self.user.id, lock_token=token)++ assert suggest_ideas.call_count == model_calls+ assert (cache.get(_generation_lock_key(self.team)) is not None) is lock_left+ assert (cache.get(_cache_key(self.team)) is not None) is cached++ @patch(f"{SERVICE}.suggest_ideas")+ def test_a_run_that_loses_its_lease_does_not_replace_the_newer_cards(self, suggest_ideas: MagicMock, _flag) -> None:+ def newer_run_takes_over(**_kwargs: object) -> list:+ cache.set(_generation_lock_key(self.team), "newer-run", 60)+ return [_idea("trial_started")]++ suggest_ideas.side_effect = newer_run_takes_over+ cache.set(_generation_lock_key(self.team), "own-run", 60)++ run_data_suggestions(team_id=self.team.id, user_id=self.user.id, lock_token="own-run")++ assert cache.get(_cache_key(self.team)) is None+ assert cache.get(_generation_lock_key(self.team)) == "newer-run"++ @parameterized.expand(+ [+ ("planner returns nothing", True, None, 200, "failed", 2),+ ("planner raises", True, RuntimeError("database gone"), 200, "failed", 2),+ ("ai consent withdrawn after the cards were cached", False, None, 404, None, 0),+ ]+ )+ @patch(f"{SERVICE}.plan_steps", return_value=None)+ @patch(f"{SERVICE}.suggest_ideas")+ def test_a_failed_build_stays_failed_for_polls_until_a_retry(+ self,+ _name: str,+ approved: bool,+ planner_error: Exception | None,+ status: int,+ build_status: str | None,+ planner_calls: int,+ suggest_ideas: MagicMock,+ plan_steps: MagicMock,+ _flag,+ ) -> None:+ suggest_ideas.return_value = [_idea("trial_started")]+ plan_steps.side_effect = planner_error+ suggestion_id = self._list()["suggestions"][0]["id"]+ self.organization.is_ai_data_processing_approved = approved+ self.organization.save()+ build_url = f"/api/projects/{self.team.id}/workflow_data_suggestions/build/"++ responses = [+ self.client.post(build_url, {"suggestion_id": suggestion_id, "retry": retry}, format="json")+ for retry in (True, False, True)+ ]++ assert [response.status_code for response in responses] == [status] * 3+ if build_status is not None:+ assert [response.json()["status"] for response in responses] == [build_status] * 3+ assert plan_steps.call_count == planner_calls++ @patch(f"{SERVICE}.plan_steps")+ @patch(f"{SERVICE}.suggest_ideas")+ def test_a_saved_template_offers_its_subject_and_copies_only_the_fields_it_has(+ self, suggest_ideas: MagicMock, plan_steps: MagicMock, _flag+ ) -> None:+ saved_id = create_message_template_for_test(+ team_id=self.team.id,+ name="Trial welcome",+ content={"email": {"subject": "Saved subject", "html": "<p>Saved</p>"}},+ )+ create_message_template_for_test(+ team_id=self.team.id, name="Draft", content={"email": {"subject": "No body yet", "html": ""}}+ )+ suggest_ideas.return_value = [_idea("trial_started")]+ plan_steps.return_value = PlannedWorkflow(+ first_step="welcome", steps=[_step("welcome", "email", email_template_id=str(saved_id))]+ )+ suggestion_id = self._list()["suggestions"][0]["id"]++ built = self.client.post(+ f"/api/projects/{self.team.id}/workflow_data_suggestions/build/", {"suggestion_id": suggestion_id}+ ).json()++ offered = plan_steps.call_args.kwargs["context"].email_templates+ assert [(template.id, template.subject) for template in offered] == [(saved_id, "Saved subject")]+ assert built["status"] == "ready"+ assert built["uses_saved_template"] is True+ email = built["workflow"]["actions"][1]["config"]["inputs"]["email"]["value"]+ assert email["html"] == "<p>Saved</p>"+ assert "text" not in email++ @patch(f"{SERVICE}.plan_steps")+ @patch(f"{SERVICE}.suggest_ideas")+ def test_a_second_build_of_the_same_suggestion_waits_for_the_first(+ self, suggest_ideas: MagicMock, plan_steps: MagicMock, _flag+ ) -> None:+ suggest_ideas.return_value = [_idea("trial_started")]+ suggestion_id = self._list()["suggestions"][0]["id"]+ cache.add(f"workflows:data_suggestions:building:{self.team.id}:{suggestion_id}:web", "first-click", 60)++ response = self.client.post(+ f"/api/projects/{self.team.id}/workflow_data_suggestions/build/",+ {"suggestion_id": suggestion_id},+ format="json",+ )++ assert response.json() == {"status": "building", "workflow": None, "uses_saved_template": False}+ plan_steps.assert_not_called()++ @patch(f"{SERVICE}.plan_steps")+ @patch(f"{SERVICE}.suggest_ideas")+ def test_an_api_key_only_gets_drafts_its_own_create_call_accepts(+ self, suggest_ideas: MagicMock, plan_steps: MagicMock, _flag+ ) -> None:+ suggest_ideas.return_value = [_idea("trial_started")]+ plan_steps.return_value = PlannedWorkflow(+ first_step="notify", steps=[_step("notify", "function", template_id="template-webhook")]+ )+ suggestion_id = self._list()["suggestions"][0]["id"]+ build_url = f"/api/projects/{self.team.id}/workflow_data_suggestions/build/"+ key = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="writer", user=self.user, secure_value=hash_key_value(key), scopes=["hog_flow:write", "query:read"]+ )++ web = self.client.post(build_url, {"suggestion_id": suggestion_id}, format="json")+ self.client.logout()+ api = self.client.post(+ build_url, {"suggestion_id": suggestion_id}, format="json", headers={"authorization": f"Bearer {key}"}+ )++ # The webhook URL stays blank, which the web editor saves as a draft and an API client's create rejects.+ assert web.json()["status"] == "ready"+ assert api.json()["status"] == "failed"++ @parameterized.expand(+ [+ ("the project default", ["[email protected]", "[email protected]"], "[email protected]", "[email protected]"),+ ("the only verified sender", ["[email protected]"], None, "[email protected]"),+ ("several senders and no default", ["[email protected]", "[email protected]"], None, None),+ ]+ )+ def test_drafts_send_from(+ # Without a method-level patch, parameterized passes the class-level flag mock before the case values.+ self,+ _flag: MagicMock,+ _name: str,+ senders: list[str],+ default: str | None,+ expected: str | None,+ ) -> None:+ integrations = {+ address: Integration.objects.create(+ team=self.team, kind="email", config={"email": address, "verified": True}+ )+ for address in senders+ }+ if default is not None:+ ensure_workflows_config(self.team.id)+ TeamWorkflowsConfig.objects.filter(team_id=self.team.id).update(+ default_email_integration_id=integrations[default].id+ )++ sender = email_sender(self.team)++ assert (sender.email if sender else None) == expected++ def test_build_with_an_unknown_suggestion_is_not_found(self, _flag) -> None:+ response = self.client.post(+ f"/api/projects/{self.team.id}/workflow_data_suggestions/build/",+ {"suggestion_id": "missing"},+ format="json",+ )+ assert response.status_code == 404++ def test_endpoints_are_off_without_the_feature_flag(self, flag: MagicMock) -> None:+ flag.return_value = False+ response = self.client.get(f"/api/projects/{self.team.id}/workflow_data_suggestions/current/")+ assert response.status_code == 403diff --git a/products/workflows/frontend/Workflows/hogflows/tree/HogFlowTreeBranch.tsx b/products/workflows/frontend/Workflows/hogflows/tree/HogFlowTreeBranch.tsxindex 28b7a1950376..0fc84535b4e3 100644--- a/products/workflows/frontend/Workflows/hogflows/tree/HogFlowTreeBranch.tsx+++ b/products/workflows/frontend/Workflows/hogflows/tree/HogFlowTreeBranch.tsx@@ -47,7 +47,7 @@ export function HogFlowTreeBranch({const isBranchSelected = selectedBranch?.actionId === node.action.id && selectedBranch.index === branchIndexconst branchFilters =branchIndex !== null && node.action.type === 'conditional_branch'- ? (node.action.config.conditions[branchIndex]?.filters.properties ?? [])+ ? (node.action.config.conditions[branchIndex]?.filters?.properties ?? []): []const percentage =branchIndex !== null && node.action.type === 'random_cohort_branch'diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.tsindex 77e439fee78c..92cb05a34a35 100644--- a/products/workflows/frontend/generated/api.schemas.ts+++ b/products/workflows/frontend/generated/api.schemas.ts@@ -2070,6 +2070,152 @@ export interface BlastRadiusApi {confirm_token: string}+export interface DataSuggestionBuildRequestApi {+ /** The id of a suggestion from the list endpoint. */+ suggestion_id: string+ /** Start a new build when the last one failed. Leave it false when asking for a running build's status. */+ retry?: boolean+}++/**+ * * `ready` - Ready+ * * `building` - Building+ * * `failed` - Failed+ */+export type DataSuggestionBuildStatusEnumApi =+ (typeof DataSuggestionBuildStatusEnumApi)[keyof typeof DataSuggestionBuildStatusEnumApi]++export const DataSuggestionBuildStatusEnumApi = {+ Ready: 'ready',+ Building: 'building',+ Failed: 'failed',+} as const++export interface DataSuggestionBuildResponseApi {+ /** ready when the draft is built, building while a background build runs (call build again to check), failed when the plan did not produce a valid workflow. A failed result is reported once, so the next call starts a new build.+ *+ * * `ready` - Ready+ * * `building` - Building+ * * `failed` - Failed */+ status: DataSuggestionBuildStatusEnumApi+ /** With status ready: a validated draft workflow (name, description, trigger, actions, edges, conversion, exit_condition) that the workflow create endpoint accepts from this caller. Nothing is saved by this call. Null otherwise. */+ workflow: unknown+ /** Whether an email step reuses a saved email template. */+ uses_saved_template: boolean+}++/**+ * * `ready` - Ready+ * * `generating` - Generating+ * * `ai_not_approved` - Ai Not Approved+ * * `unavailable` - Unavailable+ */+export type DataSuggestionsStatusEnumApi =+ (typeof DataSuggestionsStatusEnumApi)[keyof typeof DataSuggestionsStatusEnumApi]++export const DataSuggestionsStatusEnumApi = {+ Ready: 'ready',+ Generating: 'generating',+ AiNotApproved: 'ai_not_approved',+ Unavailable: 'unavailable',+} as const++/**+ * * `signup` - Signup+ * * `onboarding` - Onboarding+ * * `trial` - Trial+ * * `purchase` - Purchase+ * * `churn_risk` - Churn Risk+ * * `failure` - Failure+ * * `support` - Support+ * * `other` - Other+ */+export type DataSuggestionStageEnumApi = (typeof DataSuggestionStageEnumApi)[keyof typeof DataSuggestionStageEnumApi]++export const DataSuggestionStageEnumApi = {+ Signup: 'signup',+ Onboarding: 'onboarding',+ Trial: 'trial',+ Purchase: 'purchase',+ ChurnRisk: 'churn_risk',+ Failure: 'failure',+ Support: 'support',+ Other: 'other',+} as const++/**+ * * `email` - Email+ * * `sms` - Sms+ * * `push` - Push+ * * `slack` - Slack+ * * `webhook` - Webhook+ * * `delay` - Delay+ * * `wait_until` - Wait Until+ * * `branch` - Branch+ * * `split` - Split+ * * `action` - Action+ */+export type DataSuggestionStepKindEnumApi =+ (typeof DataSuggestionStepKindEnumApi)[keyof typeof DataSuggestionStepKindEnumApi]++export const DataSuggestionStepKindEnumApi = {+ Email: 'email',+ Sms: 'sms',+ Push: 'push',+ Slack: 'slack',+ Webhook: 'webhook',+ Delay: 'delay',+ WaitUntil: 'wait_until',+ Branch: 'branch',+ Split: 'split',+ Action: 'action',+} as const++export interface DataSuggestionApi {+ /** Opaque id of this suggestion, valid while the suggestions stay cached. */+ id: string+ /** Suggested workflow name, written by AI from the project's events. */+ name: string+ /** One sentence on what the workflow does. */+ description: string+ /** One sentence on why the workflow fits this project. */+ reason: string+ /** The project event that starts the workflow. */+ trigger_event: string+ /** How often the trigger event fired in the last 7 days. */+ weekly_count: number+ /** The customer lifecycle stage the trigger event marks. Suggestions are ranked by stage first, so welcome and onboarding flows come before busier events.+ *+ * * `signup` - Signup+ * * `onboarding` - Onboarding+ * * `trial` - Trial+ * * `purchase` - Purchase+ * * `churn_risk` - Churn Risk+ * * `failure` - Failure+ * * `support` - Support+ * * `other` - Other */+ stage: DataSuggestionStageEnumApi+ /** The main planned step kinds after the trigger, in order. */+ step_outline: DataSuggestionStepKindEnumApi[]+}++export interface DataSuggestionsResponseApi {+ /** ready when suggestions were made (the list can still be empty), generating while a background run makes them (poll current until it ends), ai_not_approved when the organization has not approved AI data processing, unavailable when nothing was made or the run failed.+ *+ * * `ready` - Ready+ * * `generating` - Generating+ * * `ai_not_approved` - Ai Not Approved+ * * `unavailable` - Unavailable */+ status: DataSuggestionsStatusEnumApi+ /** Up to 3 suggested workflows, ranked by lifecycle stage and then by weekly volume. */+ suggestions: DataSuggestionApi[]+}++export interface DataSuggestionGenerateRequestApi {+ /** Make new suggestions even when the cached ones are still valid. */+ refresh?: boolean+}+/*** * `error_tracking` - Error tracking issue* * `early_access` - Early access featurediff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.tsindex a22255d22b3e..6c9afe80c772 100644--- a/products/workflows/frontend/generated/api.ts+++ b/products/workflows/frontend/generated/api.ts@@ -13,6 +13,10 @@ import type {AppMetricsTotalsResponseApi,BlastRadiusApi,BlastRadiusRequestApi,+ DataSuggestionBuildRequestApi,+ DataSuggestionBuildResponseApi,+ DataSuggestionGenerateRequestApi,+ DataSuggestionsResponseApi,EmailDraftApi,EmailDraftRequestApi,EmailSendingSuspensionStatusApi,@@ -1317,6 +1321,63 @@ export const hogFlowsUserBlastRadiusCreate = async (})}+export const getWorkflowDataSuggestionsBuildUrl = (projectId: string) => {+ return `/api/projects/${projectId}/workflow_data_suggestions/build/`+}++/**+ * Workflow ideas written by AI from the project's own events. Both calls are free for the customer.+ */+export const workflowDataSuggestionsBuild = async (+ projectId: string,+ dataSuggestionBuildRequestApi: DataSuggestionBuildRequestApi,+ options?: RequestInit+): Promise<DataSuggestionBuildResponseApi> => {+ return apiMutator<DataSuggestionBuildResponseApi>(getWorkflowDataSuggestionsBuildUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(dataSuggestionBuildRequestApi),+ })+}++export const getWorkflowDataSuggestionsCurrentUrl = (projectId: string) => {+ return `/api/projects/${projectId}/workflow_data_suggestions/current/`+}++/**+ * Workflow ideas written by AI from the project's own events. Both calls are free for the customer.+ */+export const workflowDataSuggestionsCurrent = async (+ projectId: string,+ options?: RequestInit+): Promise<DataSuggestionsResponseApi> => {+ return apiMutator<DataSuggestionsResponseApi>(getWorkflowDataSuggestionsCurrentUrl(projectId), {+ ...options,+ method: 'GET',+ })+}++export const getWorkflowDataSuggestionsGenerateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/workflow_data_suggestions/generate/`+}++/**+ * Workflow ideas written by AI from the project's own events. Both calls are free for the customer.+ */+export const workflowDataSuggestionsGenerate = async (+ projectId: string,+ dataSuggestionGenerateRequestApi?: DataSuggestionGenerateRequestApi,+ options?: RequestInit+): Promise<DataSuggestionsResponseApi> => {+ return apiMutator<DataSuggestionsResponseApi>(getWorkflowDataSuggestionsGenerateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(dataSuggestionGenerateRequestApi),+ })+}+export const getWorkflowEmailDraftsCreateUrl = (projectId: string) => {return `/api/projects/${projectId}/workflow_email_drafts/`}diff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.tsindex f3caf7fe9745..4bd139026435 100644--- a/products/workflows/frontend/generated/api.zod.ts+++ b/products/workflows/frontend/generated/api.zod.ts@@ -3221,6 +3221,33 @@ export const HogFlowsUserBlastRadiusCreateBody = /* @__PURE__ */ zod.object({),})+/**+ * Workflow ideas written by AI from the project's own events. Both calls are free for the customer.+ */+export const workflowDataSuggestionsBuildBodyRetryDefault = false++export const WorkflowDataSuggestionsBuildBody = /* @__PURE__ */ zod.object({+ suggestion_id: zod.string().describe('The id of a suggestion from the list endpoint.'),+ retry: zod+ .boolean()+ .default(workflowDataSuggestionsBuildBodyRetryDefault)+ .describe(+ "Start a new build when the last one failed. Leave it false when asking for a running build's status."+ ),+})++/**+ * Workflow ideas written by AI from the project's own events. Both calls are free for the customer.+ */+export const workflowDataSuggestionsGenerateBodyRefreshDefault = false++export const WorkflowDataSuggestionsGenerateBody = /* @__PURE__ */ zod.object({+ refresh: zod+ .boolean()+ .default(workflowDataSuggestionsGenerateBodyRefreshDefault)+ .describe('Make new suggestions even when the cached ones are still valid.'),+})+/*** Write a first draft of an email to the people an entity points at. A model writes it when the project has AI drafts on and the organization approved AI data processing; otherwise, or when the model fails, the fixed template for the source is returned. Nothing is saved.* @summary Draft an email about an error, feature, survey, flag or cohortdiff --git a/products/workflows/frontend/setupGuide/WorkflowsPathChoice.tsx b/products/workflows/frontend/setupGuide/WorkflowsPathChoice.tsxindex dcb5ab02b1b1..71e9e49bf9f3 100644--- a/products/workflows/frontend/setupGuide/WorkflowsPathChoice.tsx+++ b/products/workflows/frontend/setupGuide/WorkflowsPathChoice.tsx@@ -1,16 +1,48 @@-import { useActions } from 'kea'+import { useActions, useValues } from 'kea'import { LemonButton } from '@posthog/lemon-ui'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { WorkflowDataSuggestions } from './suggestions/WorkflowDataSuggestions'+import { workflowDataSuggestionsLogic } from './suggestions/workflowDataSuggestionsLogic'import { workflowsSetupGuideLogic } from './workflowsSetupGuideLogic'/** The first-run choice on the workflows empty state. The choice picks the onboarding a person gets. */export function WorkflowsPathChoice(): JSX.Element {+ const { featureFlags } = useValues(featureFlagLogic)++ // The suggestions logic loads on mount, so it only mounts behind the flag.+ return featureFlags[FEATURE_FLAGS.WORKFLOWS_DATA_SUGGESTIONS] ? (+ <PathChoiceWithSuggestions />+ ) : (+ <PathButtons messagingIsPrimary />+ )+}++function PathChoiceWithSuggestions(): JSX.Element {+ const { cards } = useValues(workflowDataSuggestionsLogic({ surface: 'empty_state' }))++ // The first suggestion card becomes the one primary button once cards show.+ return (+ <div className="flex flex-col gap-4">+ <PathButtons messagingIsPrimary={cards.length === 0} />+ <WorkflowDataSuggestions />+ </div>+ )+}++function PathButtons({ messagingIsPrimary }: { messagingIsPrimary: boolean }): JSX.Element {const { choosePath } = useActions(workflowsSetupGuideLogic)return (<div className="flex flex-wrap gap-2">- <LemonButton type="primary" onClick={() => choosePath('messaging')} data-attr="workflows-path-messaging">+ <LemonButton+ type={messagingIsPrimary ? 'primary' : 'secondary'}+ onClick={() => choosePath('messaging')}+ data-attr="workflows-path-messaging"+ >Message your users</LemonButton><LemonButtondiff --git a/products/workflows/frontend/setupGuide/suggestions/WorkflowDataSuggestions.tsx b/products/workflows/frontend/setupGuide/suggestions/WorkflowDataSuggestions.tsxnew file mode 100644index 000000000000..f55e57f6f92b--- /dev/null+++ b/products/workflows/frontend/setupGuide/suggestions/WorkflowDataSuggestions.tsx@@ -0,0 +1,50 @@+import { useValues } from 'kea'++import { IconSparkles } from '@posthog/icons'+import { LemonSkeleton, LemonTag, Spinner, Tooltip } from '@posthog/lemon-ui'++import { workflowDataSuggestionsLogic } from './workflowDataSuggestionsLogic'+import { WorkflowSuggestionCard } from './WorkflowSuggestionCard'++const LOADING_CARD_COUNT = 3++export function WorkflowDataSuggestions(): JSX.Element | null {+ const { cards, generating } = useValues(workflowDataSuggestionsLogic({ surface: 'empty_state' }))++ // Suggestions are optional: a failed or empty run shows nothing, not even the divider.+ if (!generating && cards.length === 0) {+ return null+ }++ return (+ <div className="flex flex-col gap-2" data-attr="workflows-data-suggestions">+ <div className="flex items-center gap-3">+ <div className="h-px flex-1 bg-border-primary" />+ <span className="inline-flex items-center gap-1 text-xs text-tertiary">+ {generating ? <Spinner className="size-3" /> : <IconSparkles className="size-3" />}+ Or start from your data+ <Tooltip title="AI writes these suggestions from your project's events. Check each draft before you turn it on.">+ <LemonTag type="completion" size="small">+ Beta+ </LemonTag>+ </Tooltip>+ </span>+ <div className="h-px flex-1 bg-border-primary" />+ </div>+ {generating ? (+ <>+ <span className="text-center text-xs text-secondary">+ Suggesting workflows based on the events your project sends+ </span>+ {Array.from({ length: LOADING_CARD_COUNT }, (_, index) => (+ <LemonSkeleton key={index} className="h-40 rounded" />+ ))}+ </>+ ) : (+ cards.map((card, index) => (+ <WorkflowSuggestionCard key={card.key} card={card} surface="empty_state" primary={index === 0} />+ ))+ )}+ </div>+ )+}diff --git a/products/workflows/frontend/setupGuide/suggestions/WorkflowSuggestionCard.tsx b/products/workflows/frontend/setupGuide/suggestions/WorkflowSuggestionCard.tsxnew file mode 100644index 000000000000..c52a1ebfc47b--- /dev/null+++ b/products/workflows/frontend/setupGuide/suggestions/WorkflowSuggestionCard.tsx@@ -0,0 +1,98 @@+import { useActions, useValues } from 'kea'++import {+ IconBolt,+ IconClock,+ IconDecisionTree,+ IconHourglass,+ IconLetter,+ IconNotification,+ IconPercentage,+ IconSparkles,+ IconWebhooks,+} from '@posthog/icons'+import { LemonButton, LemonCard, LemonTag } from '@posthog/lemon-ui'++import { IconSlack, IconTwilio } from 'lib/lemon-ui/icons'+import { humanFriendlyNumber } from 'lib/utils/numbers'++import type { SuggestionCard, SuggestionStepKind } from './suggestionCards'+import { WorkflowDataSuggestionsSurface, workflowDataSuggestionsLogic } from './workflowDataSuggestionsLogic'++const STEP_DISPLAY: Record<SuggestionStepKind | 'trigger', { label: string; icon: JSX.Element }> = {+ trigger: { label: 'Trigger', icon: <IconBolt /> },+ email: { label: 'Email', icon: <IconLetter /> },+ delay: { label: 'Wait', icon: <IconClock /> },+ sms: { label: 'SMS', icon: <IconTwilio /> },+ push: { label: 'Push', icon: <IconNotification /> },+ slack: { label: 'Slack', icon: <IconSlack /> },+ webhook: { label: 'Webhook', icon: <IconWebhooks /> },+ wait_until: { label: 'Wait until', icon: <IconHourglass /> },+ branch: { label: 'Branch', icon: <IconDecisionTree /> },+ split: { label: 'Split', icon: <IconPercentage /> },+ action: { label: 'Action', icon: <IconBolt /> },+}++// A plan can have up to 20 steps, so the card shows the first few and a count of the rest.+const MAX_STEP_CHIPS = 6++export function WorkflowSuggestionCard({+ card,+ surface,+ primary = false,+}: {+ card: SuggestionCard+ surface: WorkflowDataSuggestionsSurface+ primary?: boolean+}): JSX.Element {+ const logic = workflowDataSuggestionsLogic({ surface })+ const { buildingKey } = useValues(logic)+ const { startSuggestion } = useActions(logic)+ const building = buildingKey === card.key++ return (+ <LemonCard hoverEffect={false} className="flex h-full flex-col gap-3 p-4">+ <div className="flex flex-wrap items-center gap-2">+ <LemonTag type="highlight" icon={<IconSparkles />}>+ Made for your data+ </LemonTag>+ <span className="inline-flex min-w-0 items-center gap-1 text-xs text-secondary">+ <code className="truncate text-primary">{card.triggerEvent}</code>+ <span translate="no">{humanFriendlyNumber(card.weeklyCount)}</span>+ <span>this week</span>+ </span>+ </div>+ <div className="flex flex-col gap-1">+ <h4 className="mb-0 text-base font-semibold">{card.title}</h4>+ <p className="mb-0 text-sm text-secondary">{card.description}</p>+ </div>+ <ol className="m-0 flex list-none flex-wrap items-center gap-1 p-0" aria-label="Workflow steps">+ {(['trigger', ...card.steps.slice(0, MAX_STEP_CHIPS)] as const).map((step, index) => (+ <li+ key={`${step}-${index}`}+ className="inline-flex items-center gap-1 rounded border bg-surface-secondary px-1.5 py-0.5 text-xs"+ >+ {STEP_DISPLAY[step].icon}+ {STEP_DISPLAY[step].label}+ </li>+ ))}+ {card.steps.length > MAX_STEP_CHIPS && (+ <li className="text-xs text-secondary">+{card.steps.length - MAX_STEP_CHIPS} more</li>+ )}+ </ol>+ <div className="mt-auto flex">+ <LemonButton+ type={primary ? 'primary' : 'secondary'}+ size="small"+ loading={building}+ disabledReason={buildingKey && !building ? 'Another workflow is being built' : undefined}+ onClick={() => startSuggestion(card)}+ // pinned: data-attr - autocapture dashboards read it+ data-attr="workflows-data-suggestion-ai"+ >+ {building ? 'Building your workflow' : 'Create workflow'}+ </LemonButton>+ </div>+ </LemonCard>+ )+}diff --git a/products/workflows/frontend/setupGuide/suggestions/suggestionCards.ts b/products/workflows/frontend/setupGuide/suggestions/suggestionCards.tsnew file mode 100644index 000000000000..e9dc724b51ec--- /dev/null+++ b/products/workflows/frontend/setupGuide/suggestions/suggestionCards.ts@@ -0,0 +1,32 @@+import type {+ DataSuggestionApi,+ DataSuggestionStageEnumApi,+ DataSuggestionStepKindEnumApi,+} from '../../generated/api.schemas'++export type SuggestionStepKind = DataSuggestionStepKindEnumApi++/** One suggested workflow card, written by the AI from the project's events. */+export interface SuggestionCard {+ key: string+ stage: DataSuggestionStageEnumApi+ title: string+ description: string+ triggerEvent: string+ weeklyCount: number+ steps: SuggestionStepKind[]+ suggestionId: string+}++export function cardFromSuggestion(suggestion: DataSuggestionApi): SuggestionCard {+ return {+ key: `ai-${suggestion.id}`,+ stage: suggestion.stage,+ title: suggestion.name,+ description: suggestion.description,+ triggerEvent: suggestion.trigger_event,+ weeklyCount: suggestion.weekly_count,+ steps: suggestion.step_outline,+ suggestionId: suggestion.id,+ }+}diff --git a/products/workflows/frontend/setupGuide/suggestions/workflowDataSuggestionsLogic.test.ts b/products/workflows/frontend/setupGuide/suggestions/workflowDataSuggestionsLogic.test.tsnew file mode 100644index 000000000000..c28b5f5c0865--- /dev/null+++ b/products/workflows/frontend/setupGuide/suggestions/workflowDataSuggestionsLogic.test.ts@@ -0,0 +1,137 @@+import { router } from 'kea-router'++import { lemonToast } from '@posthog/lemon-ui'++import { initKeaTests } from '~/test/init'++import { loadEntrySource } from '../../Broadcasts/broadcastUsage'+import {+ hogFlowsCreate,+ workflowDataSuggestionsBuild,+ workflowDataSuggestionsCurrent,+ workflowDataSuggestionsGenerate,+} from '../../generated/api'+import { SuggestionCard } from './suggestionCards'+import { workflowDataSuggestionsLogic } from './workflowDataSuggestionsLogic'++jest.mock('../../generated/api', () => ({+ hogFlowsCreate: jest.fn(),+ workflowDataSuggestionsBuild: jest.fn(),+ workflowDataSuggestionsCurrent: jest.fn(),+ workflowDataSuggestionsGenerate: jest.fn(),+}))++const card: SuggestionCard = {+ key: 'ai-suggestion-1',+ stage: 'signup',+ title: 'Welcome new users',+ description: 'Send a welcome email after sign-up.',+ triggerEvent: 'user_registered',+ weeklyCount: 42,+ steps: ['email'],+ suggestionId: 'suggestion-1',+}++describe('workflowDataSuggestionsLogic', () => {+ beforeEach(() => {+ jest.mocked(workflowDataSuggestionsGenerate).mockResolvedValue({ status: 'ready', suggestions: [] })+ initKeaTests()+ })++ it('polls while the background run generates the cards', async () => {+ jest.useFakeTimers()+ try {+ jest.mocked(workflowDataSuggestionsGenerate).mockResolvedValue({ status: 'generating', suggestions: [] })+ jest.mocked(workflowDataSuggestionsCurrent).mockResolvedValue({+ status: 'ready',+ suggestions: [+ {+ id: 'suggestion-1',+ name: 'Welcome new users',+ description: 'Send a welcome email after sign-up.',+ reason: 'user_registered fires every day.',+ trigger_event: 'user_registered',+ weekly_count: 42,+ stage: 'signup',+ step_outline: ['email'],+ },+ ],+ })+ const logic = workflowDataSuggestionsLogic({ surface: 'empty_state' })+ logic.mount()++ await jest.advanceTimersByTimeAsync(0)+ expect(logic.values.generating).toBe(true)+ expect(workflowDataSuggestionsCurrent).not.toHaveBeenCalled()++ await jest.advanceTimersByTimeAsync(2000)++ expect(logic.values.generating).toBe(false)+ expect(logic.values.cards.map((shown) => shown.suggestionId)).toEqual(['suggestion-1'])+ } finally {+ jest.useRealTimers()+ }+ })++ it('opens the saved draft after a successful build', async () => {+ jest.mocked(workflowDataSuggestionsBuild).mockResolvedValue({+ status: 'ready',+ workflow: { name: 'Welcome new users' },+ uses_saved_template: false,+ })+ jest.mocked(hogFlowsCreate).mockResolvedValue({ id: 'workflow-1' } as any)+ const logic = workflowDataSuggestionsLogic({ surface: 'empty_state' })+ logic.mount()++ await logic.asyncActions.startSuggestion(card)++ expect(hogFlowsCreate).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({ name: 'Welcome new users', status: 'draft' }),+ expect.objectContaining({ signal: expect.anything() })+ )+ expect(router.values.location.pathname).toContain('workflow-1')+ expect(loadEntrySource('workflow-1')).toBe('data_suggestion')+ expect(logic.values.buildingKey).toBeNull()+ })++ it.each([+ ['saves the draft once the background build is ready', false, 1],+ ['stops without saving when the person leaves the page', true, 0],+ ])('%s', async (_name, leaves, saves) => {+ jest.useFakeTimers()+ try {+ jest.mocked(workflowDataSuggestionsBuild)+ .mockResolvedValueOnce({ status: 'building', workflow: null, uses_saved_template: false })+ .mockResolvedValue({ status: 'ready', workflow: { name: 'Welcome' }, uses_saved_template: false })+ jest.mocked(hogFlowsCreate).mockResolvedValue({ id: 'workflow-1' } as any)+ const logic = workflowDataSuggestionsLogic({ surface: 'empty_state' })+ logic.mount()+ await jest.advanceTimersByTimeAsync(0)++ logic.actions.startSuggestion(card)+ await jest.advanceTimersByTimeAsync(0)+ if (leaves) {+ logic.unmount()+ }+ await jest.advanceTimersByTimeAsync(2000)++ expect(hogFlowsCreate).toHaveBeenCalledTimes(saves)+ } finally {+ jest.useRealTimers()+ }+ })++ it('shows the error and frees the card when the build fails', async () => {+ const toast = jest.spyOn(lemonToast, 'error')+ jest.mocked(workflowDataSuggestionsBuild).mockRejectedValue({ detail: 'This suggestion has expired.' })+ const logic = workflowDataSuggestionsLogic({ surface: 'empty_state' })+ logic.mount()++ await logic.asyncActions.startSuggestion(card)++ expect(toast).toHaveBeenCalledWith('This suggestion has expired.')+ expect(hogFlowsCreate).not.toHaveBeenCalled()+ expect(logic.values.buildingKey).toBeNull()+ })+})diff --git a/products/workflows/frontend/setupGuide/suggestions/workflowDataSuggestionsLogic.ts b/products/workflows/frontend/setupGuide/suggestions/workflowDataSuggestionsLogic.tsnew file mode 100644index 000000000000..9ac26c52b6c6--- /dev/null+++ b/products/workflows/frontend/setupGuide/suggestions/workflowDataSuggestionsLogic.ts@@ -0,0 +1,321 @@+import {+ MakeLogicType,+ actions,+ afterMount,+ connect,+ isBreakpoint,+ kea,+ key,+ listeners,+ path,+ props,+ reducers,+ selectors,+} from 'kea'+import { loaders } from 'kea-loaders'+import { router } from 'kea-router'+import posthog from 'posthog-js'++import { lemonToast } from '@posthog/lemon-ui'++import { projectLogic } from 'scenes/projectLogic'+import { urls } from 'scenes/urls'++import { saveEntrySource } from '../../Broadcasts/broadcastUsage'+import {+ hogFlowsCreate,+ workflowDataSuggestionsBuild,+ workflowDataSuggestionsCurrent,+ workflowDataSuggestionsGenerate,+} from '../../generated/api'+import type { DataSuggestionsResponseApi } from '../../generated/api.schemas'+import { SuggestionCard, cardFromSuggestion } from './suggestionCards'++// A background run or build usually takes 10 to 30 seconds. Past the deadline it counts as failed.+const POLL_INTERVAL_MS = 2000+// Covers the worst case of the run's stages one after another: counts, Jev and one Claude call.+const POLL_DEADLINE_MS = 5 * 60 * 1000+const SAVE_REQUEST_TIMEOUT_MS = 30 * 1000+// A stalled request would otherwise keep the skeletons up past the deadline.+const POLL_REQUEST_TIMEOUT_MS = 10_000+const BUILD_FAILED_MESSAGE = "We couldn't build this workflow. Try again, or start from a template."++// pinned: analytics property values for the `workflows data suggestion*` events - renaming breaks dashboards+export type WorkflowDataSuggestionsSurface = 'empty_state'++export interface WorkflowDataSuggestionsLogicProps {+ surface: WorkflowDataSuggestionsSurface+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface workflowDataSuggestionsLogicValues {+ currentProjectId: number | null // projectLogic+ aiResult: DataSuggestionsResponseApi | null+ aiResultLoading: boolean+ buildingKey: string | null+ cards: SuggestionCard[]+ generating: boolean+ pollingTimedOut: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface workflowDataSuggestionsLogicActions {+ giveUpPolling: () => {+ value: true+ }+ loadAiResult: () => any+ loadAiResultFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadAiResultSuccess: (+ aiResult: DataSuggestionsResponseApi | null,+ payload?: any+ ) => {+ aiResult: DataSuggestionsResponseApi | null+ payload?: any+ }+ pollAiResult: () => any+ pollAiResultFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ pollAiResultSuccess: (+ aiResult: DataSuggestionsResponseApi | null,+ payload?: any+ ) => {+ aiResult: DataSuggestionsResponseApi | null+ payload?: any+ }+ setBuildingKey: (key: string | null) => {+ key: string | null+ }+ startSuggestion: (card: SuggestionCard) => {+ card: SuggestionCard+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface workflowDataSuggestionsLogicMeta {+ key: 'empty_state'+ __keaTypeGenInternalSelectorTypes: {+ cards: (aiResult: DataSuggestionsResponseApi | null) => SuggestionCard[]+ generating: (+ aiResult: DataSuggestionsResponseApi | null,+ aiResultLoading: boolean,+ pollingTimedOut: boolean+ ) => boolean+ }+}++export type workflowDataSuggestionsLogicType = MakeLogicType<+ workflowDataSuggestionsLogicValues,+ workflowDataSuggestionsLogicActions,+ WorkflowDataSuggestionsLogicProps,+ workflowDataSuggestionsLogicMeta+>++export const workflowDataSuggestionsLogic = kea<workflowDataSuggestionsLogicType>([+ path((surface) => [+ 'products',+ 'workflows',+ 'frontend',+ 'setupGuide',+ 'suggestions',+ 'workflowDataSuggestionsLogic',+ surface,+ ]),+ props({} as WorkflowDataSuggestionsLogicProps),+ key((props) => props.surface),+ connect(() => ({+ values: [projectLogic, ['currentProjectId']],+ })),+ actions({+ giveUpPolling: true,+ startSuggestion: (card: SuggestionCard) => ({ card }),+ setBuildingKey: (key: string | null) => ({ key }),+ }),+ reducers({+ buildingKey: [+ null as string | null,+ {+ setBuildingKey: (_, { key }) => key,+ },+ ],+ pollingTimedOut: [+ false,+ {+ giveUpPolling: () => true,+ },+ ],+ }),+ loaders(({ values }) => ({+ aiResult: [+ null as DataSuggestionsResponseApi | null,+ {+ // Returns the cached cards, or starts a background run and answers with status generating.+ loadAiResult: async (): Promise<DataSuggestionsResponseApi | null> => {+ try {+ return await workflowDataSuggestionsGenerate(+ String(values.currentProjectId),+ {},+ { signal: AbortSignal.timeout(POLL_REQUEST_TIMEOUT_MS) }+ )+ } catch {+ // Suggestions are optional, so a failed call shows nothing rather than an error.+ return null+ }+ },+ pollAiResult: async (): Promise<DataSuggestionsResponseApi | null> => {+ try {+ return await workflowDataSuggestionsCurrent(String(values.currentProjectId), {+ signal: AbortSignal.timeout(POLL_REQUEST_TIMEOUT_MS),+ })+ } catch {+ // One failed read keeps the last answer, so polling goes on until the deadline.+ return values.aiResult+ }+ },+ },+ ],+ })),+ selectors({+ cards: [+ (s) => [s.aiResult],+ (aiResult: DataSuggestionsResponseApi | null): SuggestionCard[] =>+ aiResult?.status === 'ready' ? aiResult.suggestions.map(cardFromSuggestion) : [],+ ],+ generating: [+ (s) => [s.aiResult, s.aiResultLoading, s.pollingTimedOut],+ (+ aiResult: DataSuggestionsResponseApi | null,+ aiResultLoading: boolean,+ pollingTimedOut: boolean+ ): boolean => !pollingTimedOut && (aiResultLoading || aiResult?.status === 'generating'),+ ],+ }),+ listeners(({ actions, values, props, cache }) => {+ // Both the first call and every poll land here: keep polling while the background run goes on.+ const handleResult = (aiResult: DataSuggestionsResponseApi | null): void => {+ // The manager reruns a registered timer when the tab becomes visible, so only a running generation keeps one.+ cache.disposables.dispose('poll')+ if (aiResult?.status === 'generating') {+ if (Date.now() > cache.pollDeadline) {+ actions.giveUpPolling()+ return+ }+ cache.disposables.add(() => {+ const timer = window.setTimeout(() => actions.pollAiResult(), POLL_INTERVAL_MS)+ return () => window.clearTimeout(timer)+ }, 'poll')+ return+ }+ if (aiResult?.status === 'ready' && aiResult.suggestions.length > 0) {+ // pinned: analytics event name - renaming breaks dashboards+ posthog.capture('workflows data suggestions shown', {+ surface: props.surface,+ source: 'ai',+ trigger_events: aiResult.suggestions.map((suggestion) => suggestion.trigger_event),+ stages: aiResult.suggestions.map((suggestion) => suggestion.stage),+ })+ }+ }+ return {+ loadAiResultSuccess: ({ aiResult }) => {+ cache.pollDeadline = Date.now() + POLL_DEADLINE_MS+ handleResult(aiResult)+ },+ pollAiResultSuccess: ({ aiResult }) => handleResult(aiResult),+ startSuggestion: async ({ card }, breakpoint) => {+ if (values.buildingKey) {+ return+ }+ // pinned: analytics event name - renaming breaks dashboards+ posthog.capture('workflows data suggestion clicked', {+ surface: props.surface,+ source: 'ai',+ trigger_event: card.triggerEvent,+ weekly_count: card.weeklyCount,+ stage: card.stage,+ })+ actions.setBuildingKey(card.key)+ const projectId = String(values.currentProjectId)+ const deadline = Date.now() + POLL_DEADLINE_MS+ // The timeout ends a stalled request at the deadline, so the buttons do not stay disabled.+ // Only the click retries a failed build. Polls read the failure, like every other tab does.+ const requestBuild = (retry: boolean): ReturnType<typeof workflowDataSuggestionsBuild> =>+ workflowDataSuggestionsBuild(+ projectId,+ { suggestion_id: card.suggestionId, retry },+ { signal: AbortSignal.timeout(Math.max(deadline - Date.now(), 0)) }+ )+ try {+ // The build runs in the background. Asking again is free while it runs, and breakpoint stops+ // the loop, the save and the redirect once the person leaves the page.+ let built = await requestBuild(true)+ breakpoint()+ while (built.status === 'building') {+ if (Date.now() > deadline) {+ throw new Error(BUILD_FAILED_MESSAGE)+ }+ await breakpoint(POLL_INTERVAL_MS)+ try {+ built = await requestBuild(false)+ } catch (error: any) {+ // The build keeps running through a network failure or a server error, so the loop asks again until+ // the deadline. A 403 or 404 does not change, so it ends the loop.+ if (isBreakpoint(error) || (error?.status !== undefined && error.status < 500)) {+ throw error+ }+ }+ breakpoint()+ }+ if (built.status !== 'ready') {+ throw new Error(BUILD_FAILED_MESSAGE)+ }+ const workflow = await hogFlowsCreate(+ projectId,+ { ...(built.workflow as Record<string, unknown>), status: 'draft' } as Parameters<+ typeof hogFlowsCreate+ >[1],+ { signal: AbortSignal.timeout(SAVE_REQUEST_TIMEOUT_MS) }+ )+ breakpoint()+ // pinned: entry source value - 'workflow enabled' reports it, so renaming breaks the funnel+ saveEntrySource(workflow.id, 'data_suggestion')+ // pinned: analytics event name - renaming breaks dashboards+ posthog.capture('workflows data suggestion built', {+ workflow_id: workflow.id,+ surface: props.surface,+ trigger_event: card.triggerEvent,+ stage: card.stage,+ uses_saved_template: built.uses_saved_template,+ })+ router.actions.push(urls.workflow(workflow.id, 'workflow'))+ } catch (error: any) {+ if (isBreakpoint(error)) {+ throw error+ }+ lemonToast.error(+ error?.name === 'TimeoutError'+ ? BUILD_FAILED_MESSAGE+ : error?.detail || error?.message || BUILD_FAILED_MESSAGE+ )+ } finally {+ if (!cache.disposables.isDisposed) {+ actions.setBuildingKey(null)+ }+ }+ },+ }+ }),+ afterMount(({ actions }) => {+ actions.loadAiResult()+ }),+])diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 3249e3efe580..dde0f2692512 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -30080,6 +30080,153 @@ export namespace Schemas {issues_summary: string[];}+ /**+ * * `signup` - Signup+ * * `onboarding` - Onboarding+ * * `trial` - Trial+ * * `purchase` - Purchase+ * * `churn_risk` - Churn Risk+ * * `failure` - Failure+ * * `support` - Support+ * * `other` - Other+ */+ export type DataSuggestionStageEnum = typeof DataSuggestionStageEnum[keyof typeof DataSuggestionStageEnum];+++ export const DataSuggestionStageEnum = {+ Signup: 'signup',+ Onboarding: 'onboarding',+ Trial: 'trial',+ Purchase: 'purchase',+ ChurnRisk: 'churn_risk',+ Failure: 'failure',+ Support: 'support',+ Other: 'other',+ } as const;++ /**+ * * `email` - Email+ * * `sms` - Sms+ * * `push` - Push+ * * `slack` - Slack+ * * `webhook` - Webhook+ * * `delay` - Delay+ * * `wait_until` - Wait Until+ * * `branch` - Branch+ * * `split` - Split+ * * `action` - Action+ */+ export type DataSuggestionStepKindEnum = typeof DataSuggestionStepKindEnum[keyof typeof DataSuggestionStepKindEnum];+++ export const DataSuggestionStepKindEnum = {+ Email: 'email',+ Sms: 'sms',+ Push: 'push',+ Slack: 'slack',+ Webhook: 'webhook',+ Delay: 'delay',+ WaitUntil: 'wait_until',+ Branch: 'branch',+ Split: 'split',+ Action: 'action',+ } as const;++ export interface DataSuggestion {+ /** Opaque id of this suggestion, valid while the suggestions stay cached. */+ id: string;+ /** Suggested workflow name, written by AI from the project's events. */+ name: string;+ /** One sentence on what the workflow does. */+ description: string;+ /** One sentence on why the workflow fits this project. */+ reason: string;+ /** The project event that starts the workflow. */+ trigger_event: string;+ /** How often the trigger event fired in the last 7 days. */+ weekly_count: number;+ /** The customer lifecycle stage the trigger event marks. Suggestions are ranked by stage first, so welcome and onboarding flows come before busier events.+ *+ * * `signup` - Signup+ * * `onboarding` - Onboarding+ * * `trial` - Trial+ * * `purchase` - Purchase+ * * `churn_risk` - Churn Risk+ * * `failure` - Failure+ * * `support` - Support+ * * `other` - Other */+ stage: DataSuggestionStageEnum;+ /** The main planned step kinds after the trigger, in order. */+ step_outline: DataSuggestionStepKindEnum[];+ }++ export interface DataSuggestionBuildRequest {+ /** The id of a suggestion from the list endpoint. */+ suggestion_id: string;+ /** Start a new build when the last one failed. Leave it false when asking for a running build's status. */+ retry?: boolean;+ }++ /**+ * * `ready` - Ready+ * * `building` - Building+ * * `failed` - Failed+ */+ export type DataSuggestionBuildStatusEnum = typeof DataSuggestionBuildStatusEnum[keyof typeof DataSuggestionBuildStatusEnum];+++ export const DataSuggestionBuildStatusEnum = {+ Ready: 'ready',+ Building: 'building',+ Failed: 'failed',+ } as const;++ export interface DataSuggestionBuildResponse {+ /** ready when the draft is built, building while a background build runs (call build again to check), failed when the plan did not produce a valid workflow. A failed result is reported once, so the next call starts a new build.+ *+ * * `ready` - Ready+ * * `building` - Building+ * * `failed` - Failed */+ status: DataSuggestionBuildStatusEnum;+ /** With status ready: a validated draft workflow (name, description, trigger, actions, edges, conversion, exit_condition) that the workflow create endpoint accepts from this caller. Nothing is saved by this call. Null otherwise. */+ workflow: unknown;+ /** Whether an email step reuses a saved email template. */+ uses_saved_template: boolean;+ }++ export interface DataSuggestionGenerateRequest {+ /** Make new suggestions even when the cached ones are still valid. */+ refresh?: boolean;+ }++ /**+ * * `ready` - Ready+ * * `generating` - Generating+ * * `ai_not_approved` - Ai Not Approved+ * * `unavailable` - Unavailable+ */+ export type DataSuggestionsStatusEnum = typeof DataSuggestionsStatusEnum[keyof typeof DataSuggestionsStatusEnum];+++ export const DataSuggestionsStatusEnum = {+ Ready: 'ready',+ Generating: 'generating',+ AiNotApproved: 'ai_not_approved',+ Unavailable: 'unavailable',+ } as const;++ export interface DataSuggestionsResponse {+ /** ready when suggestions were made (the list can still be empty), generating while a background run makes them (poll current until it ends), ai_not_approved when the organization has not approved AI data processing, unavailable when nothing was made or the run failed.+ *+ * * `ready` - Ready+ * * `generating` - Generating+ * * `ai_not_approved` - Ai Not Approved+ * * `unavailable` - Unavailable */+ status: DataSuggestionsStatusEnum;+ /** Up to 3 suggested workflows, ranked by lifecycle stage and then by weekly volume. */+ suggestions: DataSuggestion[];+ }+export interface DataWarehouseExpression {readonly id: string;/**