Skip to content

: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.

feat(workflows): write push steps in workflow ideas for mobile-first projects (#122263)

Daniel Marchuk840e37fb3a7c
diff --git a/products/workflows/backend/facade/contracts.py b/products/workflows/backend/facade/contracts.py
index 4fc54ec3e0d7..15898e81c9b0 100644
--- a/products/workflows/backend/facade/contracts.py
+++ b/products/workflows/backend/facade/contracts.py
@@ -920,6 +920,8 @@ class DataSuggestionsResult:
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, ...] = ()
+ # Whether most of the project's app events come from its mobile SDKs. Kept with the cards for the same reason.
+ mobile_first: bool = False
DataSuggestionBuildStatus = Literal["ready", "building", "failed"]
diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.py
index 8a23757f62a6..6dceecf50a4a 100644
--- a/products/workflows/backend/presentation/views/hog_flow.py
+++ b/products/workflows/backend/presentation/views/hog_flow.py
@@ -957,6 +957,18 @@ def _event_trigger_targets_something(filters: Any) -> bool:
return any(isinstance(prop, dict) and prop.get("key") for prop in filters.get("properties") or [])
+def _reject_empty_required_lists(input_schema: list[dict] | None, inputs: dict) -> None:
+ # The shared input check skips every falsy value, so {}, 0 and false pass as well as []. A live push step with no
+ # channel fails every send.
+ for schema in input_schema or []:
+ if not schema.get("required") or schema.get("type") != "integration_multi":
+ continue
+ item = inputs.get(schema["key"])
+ value = item.get("value") if isinstance(item, dict) else None
+ if not isinstance(value, list) or not value:
+ raise serializers.ValidationError({"inputs": {schema["key"]: {"input": "This field is required."}}})
+
+
def _should_validate_strictly(context: dict, is_draft: Optional[bool]) -> bool:
# Non-draft saves always validate fully. Drafts stay lenient for the web UI builder (which saves
# incomplete graphs mid-edit) and for internal re-saves (e.g. the refresh management command), which
@@ -2172,6 +2184,8 @@ class HogFlowActionSerializer(serializers.Serializer):
function_config_serializer.is_valid(raise_exception=True)
data["config"]["inputs"] = function_config_serializer.validated_data["inputs"]
+ if not is_draft:
+ _reject_empty_required_lists(input_schema, data["config"].get("inputs") or {})
if strict and template_id == _CREATE_TASK_TEMPLATE_ID:
self._validate_create_task_action(data["config"]["inputs"])
if strict and template_id == _RUN_SCOUT_TEMPLATE_ID:
diff --git a/products/workflows/backend/services/data_suggestions/README.md b/products/workflows/backend/services/data_suggestions/README.md
index 3a0a977adb55..8f3d947922db 100644
--- a/products/workflows/backend/services/data_suggestions/README.md
+++ b/products/workflows/backend/services/data_suggestions/README.md
@@ -80,7 +80,9 @@ Outside this folder:
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.
+- SMS is only offered when Twilio is connected.
+ Push is offered when APNs or Firebase is connected, or when most of the project's app events in the last day come from its mobile SDKs.
+ A mobile-first project gets push as its main channel, and a push step without a provider keeps a note to connect one.
Settings the model cannot know, like API keys and URLs, stay blank in the draft.
## Tests
diff --git a/products/workflows/backend/services/data_suggestions/builder.py b/products/workflows/backend/services/data_suggestions/builder.py
index 40ca8a0b8f33..4823891807ca 100644
--- a/products/workflows/backend/services/data_suggestions/builder.py
+++ b/products/workflows/backend/services/data_suggestions/builder.py
@@ -28,6 +28,8 @@ _REPEAT_ENTRY_SECONDS = 7 * 24 * 60 * 60
# so the draft starts on a random sample that brings the volume down to about this level.
_SAMPLE_ABOVE_WEEKLY_EVENTS = 50_000
_SAMPLE_ID = "action_sample"
+_PUSH_TITLE_LIMIT = 65
+PUSH_SETUP_NOTE = "Connect APNs or Firebase, and register device tokens in your app, before you turn this on."
@frozen
@@ -48,6 +50,7 @@ class BuildContext:
once_per_person: bool = False
event_properties: frozenset[str] = frozenset()
weekly_count: int = 0
+ push_integration_ids: tuple[int, ...] = ()
@frozen
@@ -248,6 +251,8 @@ def _wait_step(step_id: str, next_id: str) -> PlannedStep:
email_subject=None,
email_heading=None,
email_paragraphs=None,
+ push_title=None,
+ push_body=None,
slack_message=None,
)
@@ -275,7 +280,7 @@ def _build_step(step: PlannedStep, action_id: str, context: BuildContext) -> dic
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": {}})
+ return _build_push_step(step, action_id, context)
case "slack":
return _action(step, action_id, "function", _slack_config(step, context))
case "function":
@@ -337,6 +342,31 @@ def _wait_config(step: PlannedStep) -> dict[str, Any]:
}
+def _build_push_step(step: PlannedStep, action_id: str, context: BuildContext) -> dict[str, Any] | None:
+ title = with_variables(clean_copy(step.push_title or ""), frozenset())[:_PUSH_TITLE_LIMIT]
+ if not title:
+ return None
+ body = with_variables(clean_copy(step.push_body or ""), context.event_properties, raw=True)
+ action = _action(
+ step,
+ action_id,
+ "function_push",
+ {
+ "template_id": "template-native-push",
+ "inputs": {
+ "distinctId": {"value": "{event.distinct_id}", "templating": "hog"},
+ # Every connected app gets the send, and each person only has a device token on the apps they use.
+ "channels": {"value": list(context.push_integration_ids)},
+ "title": {"value": title, "templating": "hog"},
+ "body": {"value": body, "templating": "liquid"},
+ },
+ },
+ )
+ if not context.push_integration_ids:
+ action["description"] = " ".join(filter(None, [PUSH_SETUP_NOTE, action["description"]]))
+ return action
+
+
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)
diff --git a/products/workflows/backend/services/data_suggestions/event_volume.py b/products/workflows/backend/services/data_suggestions/event_volume.py
index 3f136e7750cf..db150aa6fdac 100644
--- a/products/workflows/backend/services/data_suggestions/event_volume.py
+++ b/products/workflows/backend/services/data_suggestions/event_volume.py
@@ -22,8 +22,11 @@ _COUNT_TIMEOUT_SECONDS = 30
# result, which still ranks the events and clears the minimum weekly count.
_COUNT_MAX_BYTES = 2_000_000_000
MAX_EVENTS = 5000
+# A share needs far fewer events than a ranking, so its scan reads about this many whatever the project's size.
+_SHARE_SAMPLE_EVENTS = 1_000_000
# PostHog's own events that mark a real moment, unlike the generic `$` events the planner must skip.
ALLOWED_POSTHOG_EVENTS = frozenset({"$conversation_ticket_created"})
+MOBILE_LIBS = frozenset({"posthog-ios", "posthog-android", "posthog-react-native", "posthog-flutter"})
def weekly_counts(team: Team) -> dict[str, int]:
@@ -49,6 +52,28 @@ def estimated_weekly_events(team: Team) -> int:
return int(rows[0][0]) * _ESTIMATE_SAMPLE_DENOMINATOR if rows else 0
+def mobile_share(team: Team) -> float:
+ """The share of the project's app events that its mobile SDKs send, out of mobile and web together. Server-side
+ events are left out, because a mobile app's backend often sends them too."""
+ query = parse_select(
+ """
+ SELECT countIf(properties.$lib IN {mobile}), countIf(properties.$lib IN {app})
+ FROM events
+ WHERE timestamp >= now() - INTERVAL 1 DAY
+ """,
+ placeholders={"mobile": _strings(MOBILE_LIBS), "app": _strings(MOBILE_LIBS | {"web"})},
+ )
+ # The events table is sorted by event name, so a scan that stops at the read cap would count only the events
+ # early in that order. A sample keeps the scan under the cap and spreads it over every event.
+ sample_denominator = max(1, math.ceil(estimated_weekly_events(team) / 7 / _SHARE_SAMPLE_EVENTS))
+ if sample_denominator > 1 and isinstance(query, ast.SelectQuery) and query.select_from is not None:
+ query.select_from.sample = _sample(sample_denominator)
+ rows = _run_count(team, query, "workflows_data_suggestions_mobile_share").results or []
+ if not rows or not rows[0][1]:
+ return 0.0
+ return int(rows[0][0]) / int(rows[0][1])
+
+
def _count_events(team: Team, sample_denominator: int, *, skip: frozenset[str]) -> dict[str, int]:
query = parse_select(
"""
diff --git a/products/workflows/backend/services/data_suggestions/planner.py b/products/workflows/backend/services/data_suggestions/planner.py
index 96c3cef1a962..7638ecb43dc4 100644
--- a/products/workflows/backend/services/data_suggestions/planner.py
+++ b/products/workflows/backend/services/data_suggestions/planner.py
@@ -95,6 +95,12 @@ class PlannedStep(BaseModel):
email_paragraphs: list[str] | None = Field(
description="For an email step without a saved template: 1 to 3 short paragraphs of body copy."
)
+ push_title: str | None = Field(
+ description="For a push step: the notification title, at most 50 characters, else null."
+ )
+ push_body: str | None = Field(
+ description="For a push step: one short sentence under the title, at most 120 characters, else null."
+ )
slack_message: str | None = Field(description="For a slack step: the message to post, else null.")
@@ -109,6 +115,7 @@ class IdeaContext:
stages: dict[str, LifecycleStage]
channels: frozenset[Channel]
has_slack: bool
+ mobile_first: bool = False
@frozen
@@ -121,6 +128,7 @@ class StepsContext:
has_slack: bool
# The trigger event's own properties, like a product name or an amount, that an email can show.
event_properties: tuple[str, ...] = ()
+ mobile_first: bool = False
_SIMPLE_RULE = (
@@ -152,7 +160,7 @@ Rules:
- {_REVENUE_RULE}
- Each idea must use a different trigger_event.
- List the ideas best first. Within one lifecycle stage only the first idea is shown.
-- Email is the main way to reach people. {{channel_rule}} {{slack_rule}}
+- {{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}
@@ -162,8 +170,9 @@ _STEPS_PROMPT = f"""You plan the steps of one PostHog workflow. The workflow and
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.
+- email: a message to the person. Write the copy.
+- push: a notification on the person's phone. Write push_title and push_body.
+- sms: a text message to the person. The team adds the message.
- 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.
@@ -209,7 +218,9 @@ def suggest_ideas(*, team: Team, user: User, context: IdeaContext, analytics_cli
effort="low",
feature="data_suggestion_ideas",
schema=WorkflowIdeas,
- system=_IDEAS_PROMPT.format(channel_rule=_channel_rule(context.channels), slack_rule=slack_rule),
+ system=_IDEAS_PROMPT.format(
+ channel_rule=_channel_rule(context.channels, context.mobile_first), 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]},
@@ -223,10 +234,18 @@ def _missing_channels(channels: frozenset[Channel]) -> frozenset[str]:
return frozenset({"sms", "push"} - channels)
-def _channel_rule(channels: frozenset[Channel]) -> str:
+def _channel_rule(channels: frozenset[Channel], mobile_first: bool) -> str:
+ if mobile_first and "push" in channels:
+ return (
+ "Most of this project's people use its mobile app, so push is the main way to reach them. Use email "
+ "only where a longer message helps, like a receipt or a guide."
+ )
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."
+ return "Email is the main way to reach people. The team has no SMS or push provider, so use email."
+ return (
+ f"Email is the main way to reach people. The team can also send {' and '.join(sorted(channels))}. "
+ "Use them only when they suit the message better than email."
+ )
def plan_steps(
@@ -299,7 +318,7 @@ def plan_steps(
schema=PlannedWorkflow,
system=_STEPS_PROMPT.format(
email_rule=email_rule,
- channel_rule=_channel_rule(context.channels),
+ channel_rule=_channel_rule(context.channels, context.mobile_first),
slack_rule=slack_rule,
personalization_rule=personalization_rule,
max_steps=MAX_PLANNED_STEPS,
diff --git a/products/workflows/backend/services/data_suggestions/premade.py b/products/workflows/backend/services/data_suggestions/premade.py
index 2ff2e458783b..06c7d26e6a5c 100644
--- a/products/workflows/backend/services/data_suggestions/premade.py
+++ b/products/workflows/backend/services/data_suggestions/premade.py
@@ -18,7 +18,7 @@ from posthog.models import Team, User
from products.workflows.backend.facade.contracts import BuiltSuggestion, DataSuggestion, WorkflowIdeaAlreadyResolved
from products.workflows.backend.facade.enums import WorkflowIdeaStatus
from products.workflows.backend.models import HogFlow, WorkflowIdea
-from products.workflows.backend.services.data_suggestions.builder import EmailSender
+from products.workflows.backend.services.data_suggestions.builder import PUSH_SETUP_NOTE, EmailSender
def premade_suggestions(team: Team) -> tuple[DataSuggestion, ...]:
@@ -121,6 +121,22 @@ def with_sender(workflow: dict[str, Any], sender: EmailSender | None) -> dict[st
return filled
+def with_push_channels(workflow: dict[str, Any], integration_ids: Sequence[int]) -> dict[str, Any]:
+ """Fills each blank push channel list, because the project may have connected a provider after the idea was
+ built. The note that asked for the provider goes too."""
+ if not integration_ids:
+ return workflow
+ filled = copy.deepcopy(workflow)
+ for action in filled.get("actions") or []:
+ if action.get("type") != "function_push":
+ continue
+ channels = cast(dict[str, Any], ((action.get("config") or {}).get("inputs") or {}).get("channels") or {})
+ if channels and not channels.get("value"):
+ channels["value"] = list(integration_ids)
+ action["description"] = str(action.get("description") or "").replace(PUSH_SETUP_NOTE, "").strip()
+ return filled
+
+
def _premade(team_id: int) -> QuerySet[WorkflowIdea]:
# for_team() also matches the parent project's ideas from a child environment, which an environment-scoped key
# must not read.
diff --git a/products/workflows/backend/services/data_suggestions/service.py b/products/workflows/backend/services/data_suggestions/service.py
index 943672891178..2f71d6085385 100644
--- a/products/workflows/backend/services/data_suggestions/service.py
+++ b/products/workflows/backend/services/data_suggestions/service.py
@@ -42,9 +42,10 @@ from products.workflows.backend.services.data_suggestions.builder import (
clean_copy,
missing_inputs,
)
-from products.workflows.backend.services.data_suggestions.event_volume import weekly_counts
+from products.workflows.backend.services.data_suggestions.event_volume import mobile_share, weekly_counts
from products.workflows.backend.services.data_suggestions.planner import (
MAX_PLANNED_STEPS,
+ Channel,
IdeaContext,
PlannedWorkflow,
StepsContext,
@@ -60,6 +61,7 @@ from products.workflows.backend.services.data_suggestions.premade import (
premade_suggestions,
store_premade_ideas,
waiting_premade_idea,
+ with_push_channels,
with_sender,
)
from products.workflows.backend.services.data_suggestions.ranking import (
@@ -102,6 +104,7 @@ _BUILDING = BuiltSuggestion(status="building")
_BUILD_FAILED = BuiltSuggestion(status="failed")
_UNAVAILABLE = DataSuggestionsResult(status="unavailable", suggestions=())
_ONCE_PER_PERSON_STAGES = frozenset({"signup", "onboarding"})
+_MOBILE_FIRST_SHARE = 0.5
# A project without a verified sender cannot pick one yet, so the field says what to do first.
NO_SENDER_FIELD = "Email sender (no verified sender yet: add a sending domain under Workflows > Channels)"
@@ -254,7 +257,7 @@ def save_premade_draft(
row = lock_premade_idea(team.id, idea_id)
if row is None:
return None
- workflow = with_sender(row.definition, team_context.email_sender(team))
+ workflow = _premade_workflow(team, row)
validated = validate_draft(team, workflow)
if validated is None:
return _BUILD_FAILED
@@ -280,12 +283,17 @@ def get_premade_workflow(
row = waiting_premade_idea(team.id, idea_id)
if row is None:
return None
- workflow = with_sender(row.definition, team_context.email_sender(team))
+ workflow = _premade_workflow(team, row)
if validate_draft(team, workflow) is None:
return _BUILD_FAILED
return _premade_build(team, row, workflow)
+def _premade_workflow(team: Team, row: WorkflowIdeaRow) -> dict[str, Any]:
+ workflow = with_sender(row.definition, team_context.email_sender(team))
+ return with_push_channels(workflow, team_context.push_integration_ids(team))
+
+
def _premade_build(team: Team, row: WorkflowIdeaRow, workflow: dict[str, Any]) -> BuiltSuggestion:
return BuiltSuggestion(
status="ready",
@@ -335,7 +343,12 @@ def run_build(
result = _BUILD_FAILED
else:
result, validated = _plan_and_build(
- team=team, user=user, suggestion=suggestion, events=cached.events, validate_draft=validate_draft
+ team=team,
+ user=user,
+ suggestion=suggestion,
+ events=cached.events,
+ mobile_first=cached.mobile_first,
+ validate_draft=validate_draft,
)
# A task that outlived its lock would save a second draft next to the newer run's draft.
if save_draft is not None and validated is not None and not _lost_lock(lock_key, lock_token):
@@ -375,7 +388,12 @@ def prepare_premade_ideas(
for suggestion in result.suggestions:
try:
build, _ = _plan_and_build(
- team=team, user=user, suggestion=suggestion, events=result.events, validate_draft=validate_draft
+ team=team,
+ user=user,
+ suggestion=suggestion,
+ events=result.events,
+ mobile_first=result.mobile_first,
+ validate_draft=validate_draft,
)
except Exception as error:
logger.exception("workflows.data_suggestions.prepare_build_failed", team_id=team.id)
@@ -393,6 +411,7 @@ def _plan_and_build(
user: User,
suggestion: DataSuggestion,
events: tuple[str, ...],
+ mobile_first: bool,
validate_draft: Callable[[Team, dict[str, Any]], dict[str, Any] | None],
) -> tuple[BuiltSuggestion, dict[str, Any] | None]:
idea = WorkflowIdea(
@@ -405,7 +424,7 @@ def _plan_and_build(
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)
+ channels = _offered_channels(team, mobile_first)
event_properties = team_context.event_property_names(team, suggestion.trigger_event)
context = BuildContext(
allowed_events=frozenset({suggestion.trigger_event, *events}),
@@ -417,6 +436,7 @@ def _plan_and_build(
once_per_person=suggestion.stage in _ONCE_PER_PERSON_STAGES,
event_properties=frozenset(event_properties),
weekly_count=suggestion.weekly_count,
+ push_integration_ids=team_context.push_integration_ids(team),
)
built = None
# The model now and then links a step to an id it never wrote. A second plan almost always holds up.
@@ -433,6 +453,7 @@ def _plan_and_build(
channels=channels,
has_slack=slack_integration_id is not None,
event_properties=event_properties,
+ mobile_first=mobile_first,
),
analytics_client=analytics_client,
)
@@ -477,6 +498,14 @@ def _current_build(team: Team, suggestion_id: str, caller: str) -> BuiltSuggesti
return dataclasses.replace(stored, missing_inputs=_missing_inputs(team, {"actions": actions}))
+def _offered_channels(team: Team, mobile_first: bool) -> frozenset[Channel]:
+ """The channels a plan may use. A mobile-first project gets push even before it connects a provider, and the
+ step's note asks the team to connect one."""
+ connected = team_context.channels(team)
+ push: frozenset[Channel] = frozenset({"push"})
+ return connected | push if mobile_first else connected
+
+
def _missing_inputs(team: Team, workflow: dict[str, Any]) -> tuple[MissingInput, ...]:
return missing_inputs(
workflow,
@@ -608,6 +637,8 @@ def _read_cache(team: Team) -> DataSuggestionsResult | None:
for item in stored["suggestions"]
),
events=tuple(stored["events"]),
+ # Cards cached before the share was stored were made without push, so their builds stay without it.
+ mobile_first=bool(stored.get("mobile_first", False)),
)
except (KeyError, TypeError):
# An entry from before a field change is treated as missing, so the next visit generates new cards.
@@ -665,14 +696,17 @@ def _suggest(*, team: Team, user: User, analytics_client: Any) -> DataSuggestion
if not prompt_events:
return DataSuggestionsResult(status="ready", suggestions=())
offered = {name for name, _ in prompt_events}
+ mobile_first = mobile_share(team) >= _MOBILE_FIRST_SHARE
+ channels = _offered_channels(team, mobile_first)
ideas = suggest_ideas(
team=team,
user=user,
context=IdeaContext(
events=tuple(prompt_events),
stages=jev_stages,
- channels=team_context.channels(team),
+ channels=channels,
has_slack=team_context.slack_integration_id(team) is not None,
+ mobile_first=mobile_first,
),
analytics_client=analytics_client,
)
@@ -707,4 +741,5 @@ def _suggest(*, team: Team, user: User, analytics_client: Any) -> DataSuggestion
status="ready",
suggestions=tuple(pick_one_per_stage(ranked, stage_of=lambda item: item.stage, limit=MAX_SUGGESTIONS)),
events=planning_events,
+ mobile_first=mobile_first,
)
diff --git a/products/workflows/backend/services/data_suggestions/team_context.py b/products/workflows/backend/services/data_suggestions/team_context.py
index 3049253397b1..e7f7c07592bd 100644
--- a/products/workflows/backend/services/data_suggestions/team_context.py
+++ b/products/workflows/backend/services/data_suggestions/team_context.py
@@ -68,6 +68,14 @@ def channels(team: Team) -> frozenset[Channel]:
return frozenset(connected)
+def push_integration_ids(team: Team) -> tuple[int, ...]:
+ return tuple(
+ Integration.objects.filter(team_id=team.id, kind__in=["apns", "firebase"])
+ .order_by("created_at")
+ .values_list("id", flat=True)
+ )
+
+
def slack_integration_id(team: Team) -> int | None:
return (
Integration.objects.filter(team_id=team.id, kind="slack")
diff --git a/products/workflows/backend/test/test_data_suggestions.py b/products/workflows/backend/test/test_data_suggestions.py
index cd5190e2c340..9d7d2dff74f1 100644
--- a/products/workflows/backend/test/test_data_suggestions.py
+++ b/products/workflows/backend/test/test_data_suggestions.py
@@ -16,7 +16,12 @@ from products.workflows.backend.presentation.views.workflow_data_suggestions imp
DataSuggestionStage,
DataSuggestionStepKind,
)
-from products.workflows.backend.services.data_suggestions.builder import BuildContext, build_workflow, missing_inputs
+from products.workflows.backend.services.data_suggestions.builder import (
+ PUSH_SETUP_NOTE,
+ BuildContext,
+ build_workflow,
+ missing_inputs,
+)
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 (
@@ -25,6 +30,7 @@ from products.workflows.backend.services.data_suggestions.planner import (
PlannedWorkflow,
WorkflowIdea,
)
+from products.workflows.backend.services.data_suggestions.premade import with_push_channels
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
@@ -53,6 +59,8 @@ def step(step_id: str = "email_1", **overrides: Any) -> PlannedStep:
"email_subject": "Your trial started",
"email_heading": "Welcome to your trial",
"email_paragraphs": ["Here is how to get started."],
+ "push_title": None,
+ "push_body": None,
"slack_message": None,
}
values.update(overrides)
@@ -99,7 +107,7 @@ class TestDataSuggestions(SimpleTestCase):
("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"))),
+ ("push the project cannot use", {}, plan(step("notify", type="push", push_title="Your trial started"))),
("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())),
@@ -204,6 +212,61 @@ class TestDataSuggestions(SimpleTestCase):
("action_2_function", "Webhook URL"),
}
+ @parameterized.expand([("provider connected", (7, 9)), ("no provider yet", ())])
+ def test_build_workflow_writes_push_copy_and_asks_for_a_provider_only_when_missing(
+ self, _name: str, integration_ids: tuple[int, ...]
+ ) -> None:
+ built = build_workflow(
+ IDEA,
+ plan(
+ step(
+ "notify",
+ type="push",
+ setup_note="Check the copy",
+ push_title="your {{ person.name }}trial started",
+ push_body="See what [[plan|your plan]] includes.",
+ )
+ ),
+ context(
+ channels=frozenset({"push"}),
+ push_integration_ids=integration_ids,
+ event_properties=frozenset({"plan"}),
+ ),
+ )
+ assert built is not None
+ push = built.workflow["actions"][1]
+ assert push["type"] == "function_push"
+ assert push["config"]["inputs"] == {
+ "distinctId": {"value": "{event.distinct_id}", "templating": "hog"},
+ "channels": {"value": list(integration_ids)},
+ "title": {"value": "Your trial started", "templating": "hog"},
+ "body": {
+ "value": "See what {{ event.properties.plan | default: 'your plan' | raw }} includes.",
+ "templating": "liquid",
+ },
+ }
+ push_schema = {
+ "template-native-push": [
+ {"key": "distinctId", "label": "Distinct ID", "required": True},
+ {"key": "channels", "label": "Push channels", "required": True},
+ {"key": "title", "label": "Notification title", "required": True},
+ ]
+ }
+ missing = [item.field for item in missing_inputs(built.workflow, push_schema)]
+ if integration_ids:
+ assert push["description"] == "Check the copy"
+ assert missing == []
+ else:
+ assert push["description"] == f"{PUSH_SETUP_NOTE} Check the copy"
+ assert missing == ["Push channels"]
+ connected_later = with_push_channels(built.workflow, [7])["actions"][1]
+ assert connected_later["config"]["inputs"]["channels"] == {"value": [7]}
+ assert connected_later["description"] == "Check the copy"
+
+ def test_build_workflow_drops_push_without_a_title(self) -> None:
+ planned = plan(step("notify", type="push", push_body="Only a body"))
+ assert build_workflow(IDEA, planned, context(channels=frozenset({"push"}))) is None
+
@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")
diff --git a/products/workflows/backend/tests/api/test_hog_flow.py b/products/workflows/backend/tests/api/test_hog_flow.py
index e849a0daccca..fa9ca13db56d 100644
--- a/products/workflows/backend/tests/api/test_hog_flow.py
+++ b/products/workflows/backend/tests/api/test_hog_flow.py
@@ -56,6 +56,7 @@ from products.workflows.backend.presentation.views.hog_flow import (
_should_validate_strictly,
mint_audience_confirm_token,
)
+from products.workflows.backend.tests.api.test_workflow_data_suggestions import _push_function_template
_AUDIENCE_CONDITION = {"key": "email", "type": "person", "value": "x", "operator": "icontains"}
_WIDER_AUDIENCE_CONDITION = {"key": "email", "type": "person", "value": "@", "operator": "icontains"}
@@ -193,6 +194,36 @@ class TestHogFlowAPI(APIBaseTest):
return hog_flow, action
+ @parameterized.expand(
+ [
+ ("empty list", [], 400),
+ ("empty object", {}, 400),
+ ("zero", 0, 400),
+ ("false", False, 400),
+ ("a channel", "provider", 201),
+ ]
+ )
+ def test_an_active_push_step_needs_a_channel(self, _name: str, channels: Any, expected_status: int) -> None:
+ sync_template_to_db(_push_function_template())
+ provider = Integration.objects.create(team=self.team, kind="firebase", config={})
+ hog_flow, _ = self._create_hog_flow_with_action(
+ {
+ "template_id": "template-native-push",
+ "inputs": {
+ "distinctId": {"value": "{event.distinct_id}"},
+ "channels": {"value": [provider.id] if channels == "provider" else channels},
+ "title": {"value": "Hi"},
+ },
+ }
+ )
+ hog_flow["actions"][1]["type"] = "function_push"
+
+ active = self.client.post(f"/api/projects/{self.team.id}/hog_flows", {**hog_flow, "status": "active"})
+ draft = self.client.post(f"/api/projects/{self.team.id}/hog_flows", {**hog_flow, "status": "draft"})
+
+ assert active.status_code == expected_status, active.json()
+ assert draft.status_code == 201, draft.json()
+
@patch("products.workflows.backend.presentation.views.hog_flow.publish_resource_edited")
def test_emits_resource_edited_on_create_and_update(self, mock_emit):
hog_flow, _ = self._create_hog_flow_with_action(
diff --git a/products/workflows/backend/tests/api/test_workflow_data_suggestions.py b/products/workflows/backend/tests/api/test_workflow_data_suggestions.py
index 6db63a850bff..3e3bfc47c054 100644
--- a/products/workflows/backend/tests/api/test_workflow_data_suggestions.py
+++ b/products/workflows/backend/tests/api/test_workflow_data_suggestions.py
@@ -1,3 +1,4 @@
+from copy import deepcopy
from io import StringIO
import time_machine
@@ -91,12 +92,33 @@ def _step(step_id: str, step_type: str, **overrides: object) -> PlannedStep:
"email_subject": None,
"email_heading": None,
"email_paragraphs": None,
+ "push_title": None,
+ "push_body": None,
"slack_message": None,
}
values.update(overrides)
return PlannedStep(**values)
+def _push_function_template() -> dict:
+ template = deepcopy(webhook_template)
+ template["id"] = "template-native-push"
+ template["name"] = "Push notification"
+ template["inputs_schema"] = [
+ {"key": "distinctId", "type": "string", "label": "Distinct ID", "required": True},
+ {
+ "key": "channels",
+ "type": "integration_multi",
+ "integration": "firebase,apns",
+ "label": "Push channels",
+ "required": True,
+ },
+ {"key": "title", "type": "string", "label": "Notification title", "required": True},
+ {"key": "body", "type": "string", "label": "Notification body", "required": False, "templating": "liquid"},
+ ]
+ return template
+
+
def _email_step(step_id: str, subject: str, **overrides: object) -> PlannedStep:
return _step(
step_id,
@@ -472,6 +494,61 @@ class TestWorkflowDataSuggestions(ClickhouseTestMixin, APIBaseTest):
assert create.status_code == 201, create.json()
assert create.json()["trigger"]["filters"]["events"][0]["id"] == "trial_started"
+ @parameterized.expand(
+ [
+ ("web app", "web", False, False),
+ ("mobile app without a push provider", "posthog-ios", False, True),
+ ("mobile app with a push provider", "posthog-android", True, True),
+ ]
+ )
+ @patch(f"{SERVICE}.plan_steps")
+ @patch(f"{SERVICE}.suggest_ideas")
+ def test_a_mobile_first_project_gets_push_drafts_the_create_endpoint_accepts(
+ self,
+ _name: str,
+ lib: str,
+ has_provider: bool,
+ mobile_first: bool,
+ suggest_ideas: MagicMock,
+ plan_steps: MagicMock,
+ ) -> None:
+ sync_template_to_db(_push_function_template())
+ for index in range(4):
+ _create_event(team=self.team, event="app opened", distinct_id=f"person-{index}", properties={"$lib": lib})
+ flush_persons_and_events()
+ provider = Integration.objects.create(team=self.team, kind="firebase", config={}) if has_provider else None
+ suggest_ideas.return_value = [_idea("trial_started")]
+ plan_steps.return_value = PlannedWorkflow(
+ first_step="notify",
+ steps=[_step("notify", "push", push_title="Your trial started", push_body="See what is included.")],
+ )
+ suggestion_id = self._list()["suggestions"][0]["id"]
+
+ idea_context = suggest_ideas.call_args.kwargs["context"]
+ assert (idea_context.mobile_first, "push" in idea_context.channels) == (mobile_first, mobile_first)
+ build = self.client.post(
+ f"/api/projects/{self.team.id}/workflow_data_suggestions/build/",
+ {"suggestion_id": suggestion_id},
+ format="json",
+ ).json()
+
+ if not mobile_first:
+ assert build["status"] == "failed"
+ return
+ assert plan_steps.call_args.kwargs["context"].mobile_first is True
+ push = build["workflow"]["actions"][1]
+ assert push["config"]["inputs"]["channels"]["value"] == ([provider.id] if provider else [])
+ missing = [item["field"] for item in build["missing_inputs"]]
+ assert ("Push channels" in missing) is (provider is None)
+ create = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows", {**build["workflow"], "status": "draft"}, format="json"
+ )
+ assert create.status_code == 201, create.json()
+ enable = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{create.json()['id']}", {"status": "active"}, format="json"
+ )
+ assert enable.status_code == (200 if provider else 400), enable.json()
+
def test_a_built_branch_has_unset_conditions_shaped_like_an_editor_branch(self) -> None:
built = build_workflow(
_idea("trial_started"),