: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): switch the suggestions scout on when a workflow asks for suggestions (#111943)
Daniel Marchukbe06ef57fc6e
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 07a561139936..e42a2bb875e9 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7823,9 +7823,9 @@ snapshots:products-web-analytics-content-autopilot-workspace--active-run--light:hash: v1.k794b7964.01d2d2224dc6d1eec26cb051db45e73b3f09578cace3d92a865717270f36e9a0.fyfh1pZRPid9MiuWc2YolgmQRCYae61gLJ9TTZiQ_AUproducts-web-analytics-content-autopilot-workspace--drafts-tab--dark:- hash: v1.k794b7964.8b76f06f9f7932c7011f0edbd86449b904ef1eb4fc0820685fb89b936e3f443e.pRJHP3NREhhrmFXFZqRwtZtFLEBWvBGp8DRglBSyd44+ hash: v1.k794b7964.637309bee3b445b811c08125b51c97c7405e998cef81982ab462a725251d9023.YjxtQHICh7pmzgtnLGi3ijA5kT3YtDuVR0fqCebxsRsproducts-web-analytics-content-autopilot-workspace--drafts-tab--light:- hash: v1.k794b7964.027ecb35adf95e2611cea3d1d390aec6c5a876d9f3bd920204216ab6803ca44a.H2CQyp9rv7yF8ghTpjUl_bYF4MsrKXwnk36ijRuY7sY+ hash: v1.k794b7964.68ef987ab841b7e5c388e882cbac22abafa8b029dd6ca7a6ed6f414e942259ac.FRDpQmpmPl51OBC3tAVrA1u3TWepGDCtKf9u5OEbERwproducts-web-analytics-content-autopilot-workspace--failed-run--dark:hash: v1.k794b7964.3d8a16bf937d62edab696e840497fad20cb5065d7d706833bec861357516a490.brmGznNIzalassalSt8p3-pUe09akPMMOqgToVi7GV4products-web-analytics-content-autopilot-workspace--failed-run--light:diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txtindex 3e40377cf0c3..86babdb66707 100644--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt@@ -122,6 +122,7 @@ post_delete:products.surveys.backend.models.survey_changedpost_delete:products.tasks.backend.models.delete_task_session_objectpost_delete:products.tasks.backend.search_index.channel_deletedpost_delete:products.workflows.backend.models.hog_flow.hog_flow.hog_flow_deleted+post_delete:products.workflows.backend.receivers.optimization_deletedpost_init:posthog.storage.gateway_credential_signal_handlers._snapshot_oauthpost_init:posthog.storage.gateway_credential_signal_handlers._snapshot_secret_keypost_init:posthog.storage.gateway_credential_signal_handlers._snapshot_user@@ -258,6 +259,7 @@ post_save:products.workflows.backend.models.hog_flow.hog_flow.action_saved_for_hpost_save:products.workflows.backend.models.hog_flow.hog_flow.hog_flow_savedpost_save:products.workflows.backend.models.hog_flow.hog_flow.team_saved_for_hog_flowspost_save:products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job.handle_hog_flow_batch_job_created+post_save:products.workflows.backend.receivers.workflow_savedpre_delete:ee.models.scim_provisioned_user.clear_scim_provisioned_user_configpre_delete:posthog.models.activity_logging.signal_handlers.handle_experiment_holdout_deletepre_delete:posthog.models.activity_logging.signal_handlers.handle_experiment_saved_metric_deletediff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.pyindex ef9565bd1e97..c5ba1848d9ed 100644--- a/products/signals/backend/facade/api.py+++ b/products/signals/backend/facade/api.py@@ -3,6 +3,7 @@ import uuidimport dataclassesfrom collections.abc import Callable, Iterator, Sequencefrom datetime import UTC, datetime, timedelta+from enum import StrEnumfrom typing import TYPE_CHECKING, Anyfrom django.conf import settings@@ -1402,3 +1403,183 @@ def scout_creation_available(*, team_id: int, user_id: int) -> bool:if not team_is_enrolled(canonical_team.id):return Falsereturn can_create_scout(user, canonical_team)+++def enable_scout_for_product(+ *,+ team: "Team",+ skill_name: str,+ source_product: str,+ acting_user: "User",+ write_scopes: Sequence[str] = (),+) -> bool:+ """Switch a canonical scout on for a project because a person asked for it in another product.++ The project gets that one skill and an enabled config the product owns. `acting_user` becomes+ the person the runs act as, because they turned the feature on. `write_scopes` is limited to+ `SCOUT_GRANTABLE_WRITE_SCOPES`. The caller must already have checked that this person may+ grant those scopes. It applies the same rules as the scout config API: the person needs editor+ access to skills, a new scout must fit the project's enabled-scout limit, and only a project+ admin or the person the runs act as may give a new scout write scopes or widen an existing grant.+ Returns False without writing when a rule refuses, when the organization has not approved AI data processing, when the scout+ is paused by a person or by the system, or when another product owns its config.+ """+ from posthog.temporal.oauth import ( # noqa: PLC0415 — keeps the token module off the facade's import path+ SCOUT_GRANTABLE_WRITE_SCOPES,+ )++ from products.access_control.backend.facade.user_access_control import ( # noqa: PLC0415 — keeps access control off the facade's import path+ UserAccessControl,+ )+ from products.signals.backend.scout_harness.config_registry import ( # noqa: PLC0415 — keeps the scout registry off the facade's import path+ enabled_scout_count,+ )+ from products.signals.backend.scout_harness.lazy_seed import ( # noqa: PLC0415 — keeps the skill seeding modules off the facade's import path+ canonical_config_tags_for,+ canonical_display_name_for,+ canonical_skill_names,+ canonical_structured_output_schema_for,+ sync_canonical_skills,+ )+ from products.signals.backend.scout_harness.team_limits import ( # noqa: PLC0415 — keeps the flag payload reader off the facade's import path+ max_enabled_scouts_for_team,+ )++ if skill_name not in canonical_skill_names():+ raise ValueError(f"{skill_name} is not a canonical scout")+ if team.organization.is_ai_data_processing_approved is not True:+ return False+ scopes = sorted(set(write_scopes) & SCOUT_GRANTABLE_WRITE_SCOPES)+ if not UserAccessControl(user=acting_user, team=team).check_access_level_for_resource("llm_skill", "editor"):+ return False++ sync_canonical_skills(team, withheld_skill_names=canonical_skill_names() - {skill_name})+ defaults: dict[str, Any] = {+ "source_product": source_product,+ "enabled": True,+ "write_scopes": scopes,+ "created_by": acting_user,+ "enabled_by": acting_user,+ }+ if tags := canonical_config_tags_for(skill_name):+ defaults["tags"] = list(tags)+ if display_name := canonical_display_name_for(skill_name):+ defaults["display_name"] = display_name+ if schema := canonical_structured_output_schema_for(skill_name):+ defaults["structured_output_schema"] = schema+ # Resolved before the transaction, so the flag read never happens while the row lock is held.+ max_enabled_scouts = max_enabled_scouts_for_team(team.id)+ with transaction.atomic():+ config = SignalScoutConfig.objects.for_team(team.id).select_for_update().filter(skill_name=skill_name).first()+ if config is None:+ if enabled_scout_count(team.id, exclude_skill=skill_name) >= max_enabled_scouts:+ return False+ if scopes and not _may_grant_scout_scopes(+ team=team, skill_name=skill_name, config=None, acting_user=acting_user+ ):+ return False+ config, created = SignalScoutConfig.objects.for_team(team.id).get_or_create(+ team_id=team.id, skill_name=skill_name, defaults=defaults+ )+ if created:+ return True+ # A config this product did not create is somebody's own scout, and its write access is theirs to grant.+ # A paused config stays paused, whether a person or a system breaker paused it.+ if config.source_product != source_product or not config.enabled:+ return False+ granted = sorted(set(config.write_scopes or []) | set(scopes))+ if granted != sorted(config.write_scopes or []):+ if not _may_grant_scout_scopes(team=team, skill_name=skill_name, config=config, acting_user=acting_user):+ return False+ config.write_scopes = granted+ config.save(update_fields=["write_scopes", "updated_at"])+ return True+++def _may_grant_scout_scopes(+ *, team: "Team", skill_name: str, config: SignalScoutConfig | None, acting_user: "User"+) -> bool:+ """Whether this person may give a scout write access, given that its runs act as the person `resolve_scout_acting_user_id` names."""+ from posthog.models.organization import (+ OrganizationMembership, # noqa: PLC0415 — keeps the membership model off the facade's import path+ )+ from posthog.user_permissions import (+ UserPermissions, # noqa: PLC0415 — keeps the permission resolver off the facade's import path+ )++ from products.signals.backend.scout_harness.skill_loader import ( # noqa: PLC0415 — keeps the skill loader off the facade's import path+ resolve_scout_acting_user_id,+ )++ level = UserPermissions(user=acting_user, team=team).current_team.effective_membership_level+ if level is not None and level >= OrganizationMembership.Level.ADMIN:+ return True+ acting_user_id = resolve_scout_acting_user_id(team, skill_name, config)+ # A new config records the requester as its enabler, so without a skill author its runs act as them.+ if config is None and acting_user_id is None:+ return True+ return acting_user_id == acting_user.pk+++class ScoutEnableRefusal(StrEnum):+ AI_NOT_APPROVED = "ai_not_approved"+ NO_SKILL_ACCESS = "no_skill_access"+ AT_LIMIT = "at_limit"+ NOT_SKILL_AUTHOR = "not_skill_author"+++def scout_enable_refusal_for_product(+ *, team: "Team", skill_name: str, acting_user: "User", write_scopes: Sequence[str] = ()+) -> ScoutEnableRefusal | None:+ """Why `enable_scout_for_product` would create no scout for this person, without writing anything.++ Returns None when the project already has a config for the skill, paused or not, because switching+ the feature on then creates nothing new. A caller asks before it saves the person's choice, so a+ refused choice is never stored.+ """+ from products.signals.backend.scout_harness.config_registry import ( # noqa: PLC0415 — keeps the scout registry off the facade's import path+ enabled_scout_count,+ )+ from products.signals.backend.scout_harness.team_limits import ( # noqa: PLC0415 — keeps the flag payload reader off the facade's import path+ max_enabled_scouts_for_team,+ )++ if SignalScoutConfig.objects.for_team(team.id).filter(skill_name=skill_name).exists():+ return None+ if team.organization.is_ai_data_processing_approved is not True:+ return ScoutEnableRefusal.AI_NOT_APPROVED+ if not UserAccessControl(user=acting_user, team=team).check_access_level_for_resource("llm_skill", "editor"):+ return ScoutEnableRefusal.NO_SKILL_ACCESS+ if enabled_scout_count(team.id, exclude_skill=skill_name) >= max_enabled_scouts_for_team(team.id):+ return ScoutEnableRefusal.AT_LIMIT+ if write_scopes and not _may_grant_scout_scopes(+ team=team, skill_name=skill_name, config=None, acting_user=acting_user+ ):+ return ScoutEnableRefusal.NOT_SKILL_AUTHOR+ return None+++def scout_status_for_product(*, team_id: int, skill_name: str) -> str | None:+ """The scout config's status for the skill, or None when the project has no config for it."""+ return (+ SignalScoutConfig.objects.for_team(team_id)+ .filter(skill_name=skill_name)+ .values_list("status", flat=True)+ .first()+ )+++def disable_scout_for_product(*, team_id: int, skill_name: str, source_product: str) -> bool:+ """Remove the config a product created when it switched a scout on.++ A config the product did not create is left alone, so a scout a person set up keeps running. A+ paused config is kept, whether a person or the system paused it, so the pause still holds if the+ product switches the scout on again. A lifecycle-locked config is kept too, because only a project+ admin or the person its runs act as may remove it. The run history stays. Returns False when nothing was removed.+ """+ deleted, _ = (+ SignalScoutConfig.objects.for_team(team_id)+ .filter(skill_name=skill_name, source_product=source_product, enabled=True, lifecycle_locked=False)+ .delete()+ )+ return deleted > 0diff --git a/products/workflows/backend/apps.py b/products/workflows/backend/apps.pyindex 30df1e378126..1bb42f8fd085 100644--- a/products/workflows/backend/apps.py+++ b/products/workflows/backend/apps.py@@ -5,3 +5,6 @@ class WorkflowsConfig(AppConfig):default_auto_field = "django.db.models.BigAutoField"name = "products.workflows.backend"label = "workflows"++ def ready(self) -> None:+ from products.workflows.backend import receivers # noqa: F401, PLC0415 — registers signal receiversdiff --git a/products/workflows/backend/facade/suggestions_scout.py b/products/workflows/backend/facade/suggestions_scout.pynew file mode 100644index 000000000000..aefab10550dc--- /dev/null+++ b/products/workflows/backend/facade/suggestions_scout.py@@ -0,0 +1,10 @@+"""Switching the workflows suggestions scout on and off as workflows opt in and out."""++from products.workflows.backend.services.suggestions_scout import (+ PROPOSAL_WRITE_SCOPE,+ suggestions_scout_refusal,+ suggestions_scout_status,+ sync_suggestions_scout,+)++__all__ = ["PROPOSAL_WRITE_SCOPE", "suggestions_scout_refusal", "suggestions_scout_status", "sync_suggestions_scout"]diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.pyindex d0cac4566e2e..40df8cbb4ab4 100644--- a/products/workflows/backend/presentation/views/hog_flow.py+++ b/products/workflows/backend/presentation/views/hog_flow.py@@ -76,10 +76,17 @@ from posthog.cdp.validation import HogFunctionFiltersSerializer, InputsSchemaSerfrom posthog.clickhouse.query_tagging import Feature, tag_queriesfrom posthog.dataclasses import frozenfrom posthog.event_usage import AGENT_EVENT_SOURCES, EventSource, get_event_source, report_user_action+from posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.impersonation import is_impersonatedfrom posthog.models import Team, Userfrom posthog.models.property.parse import expand_cohort_properties, parse_property_group_data-from posthog.permissions import AccessControlPermission, is_service_auth, posthog_feature_flag_enabled+from posthog.permissions import (+ AccessControlPermission,+ get_authenticator_scoped_team_ids,+ get_authenticator_scopes,+ is_service_auth,+ posthog_feature_flag_enabled,+)from posthog.plugins.plugin_server_api import (cancel_hog_flow_batch_job,cancel_hog_flow_invocations,@@ -223,6 +230,12 @@ from products.workflows.backend.facade.secrets import (secret_keys_for_action,strip_content_secrets,)+from products.workflows.backend.facade.suggestions_scout import (+ PROPOSAL_WRITE_SCOPE,+ suggestions_scout_refusal,+ suggestions_scout_status,+ sync_suggestions_scout,+)from products.workflows.backend.facade.templates import get_function_template_schemafrom products.workflows.backend.facade.validation import (DURATION_PATTERN,@@ -3601,8 +3614,34 @@ class WorkflowProposalEvidenceField(serializers.JSONField):pass+class SuggestionsScoutStatus(models.TextChoices):+ RUNNING = "running"+ PAUSED_BY_USER = "paused_by_user"+ PAUSED_BY_SYSTEM = "paused_by_system"+ NOT_RUNNING = "not_running"++class HogFlowOptimizationSerializer(serializers.Serializer):enabled = serializers.BooleanField(help_text="Whether PostHog may suggest changes to this workflow.")+ scout_status = serializers.ChoiceField(+ choices=SuggestionsScoutStatus.choices,+ read_only=True,+ help_text="Whether the project's suggestions scout runs. A paused scout files no suggestions, even for "+ "workflows that have suggestions on.",+ )+++# Why turning suggestions on would leave the project without a scout, worded for the person who tried.+SUGGESTIONS_REFUSAL_MESSAGES: dict[str, str] = {+ "at_limit": "This project already runs as many scouts as it can. Turn one off in scout settings, then try again.",+ "no_skill_access": "You need editor access to skills to turn on suggestions. Ask a project admin for access.",+ "ai_not_approved": "Suggestions use AI, and your organization hasn't approved AI data processing. "+ "An organization admin can approve it in organization settings.",+ "not_skill_author": "Suggestions run as the person who wrote this project's workflows scout. "+ "Ask them or a project admin to turn on suggestions.",+ "key_cannot_grant": "This API key can't turn on suggestions. Use a key with the hog_flow_proposal:write scope "+ "and access to the whole project.",+}class WorkflowProposalSerializer(serializers.Serializer):@@ -4695,6 +4734,14 @@ class HogFlowViewSet()self._emit_resource_edited(serializer.instance)+ # A workflow that kept suggestions on while it was off needs its scout back when it goes live again.+ if (+ result.previous.get("status") != HogFlowState.ACTIVE+ and serializer.instance.status == HogFlowState.ACTIVE+ and is_optimization_enabled(serializer.instance.id)+ ):+ self._sync_suggestions_scout(self.request)+# PostHog capture for hog_flow activated (draft -> active)if result.previous.get("status") == HogFlowState.DRAFT and serializer.instance.status == HogFlowState.ACTIVE:self._report_workflow_action(@@ -5486,6 +5533,12 @@ class HogFlowViewSet(enabled = param_serializer.validated_data["enabled"]if enabled and instance.status != HogFlowState.ACTIVE:raise WorkflowNotLiveError()+ if enabled and not is_optimization_enabled(instance.id):+ refusal = suggestions_scout_refusal(+ self.team, acting_user=cast(User, request.user), may_grant=self._may_grant_scout(request)+ )+ if refusal is not None:+ raise exceptions.ValidationError({"enabled": SUGGESTIONS_REFUSAL_MESSAGES[str(refusal)]})changed = set_optimization_enabled(hog_flow_id=instance.id, enabled=enabled)if changed:self._log_activity(@@ -5494,10 +5547,35 @@ class HogFlowViewSet(self._report_workflow_action("hog_flow_optimization_enabled" if enabled else "hog_flow_optimization_disabled", instance)+ self._sync_suggestions_scout(request)else:enabled = is_optimization_enabled(instance.id)- return Response(HogFlowOptimizationSerializer({"enabled": enabled}).data)+ return Response(+ HogFlowOptimizationSerializer(+ {"enabled": enabled, "scout_status": suggestions_scout_status(self.team)}+ ).data+ )++ def _may_grant_scout(self, request: Request) -> bool:+ # Switching the scout on grants a write scope that its runs use as this person, so a scoped API+ # key has to carry that scope itself, whichever way it toggles.+ token_scopes = get_authenticator_scopes(request.successful_authenticator)+ scoped_team_ids = get_authenticator_scoped_team_ids(request.successful_authenticator)+ # The scout lives on the project, so a key limited to one of its environments may not grant it.+ project_id = self.team.parent_team_id or self.team.id+ return (token_scopes is None or "*" in token_scopes or PROPOSAL_WRITE_SCOPE in token_scopes) and (+ scoped_team_ids is None or project_id in scoped_team_ids+ )++ def _sync_suggestions_scout(self, request: Request) -> None:+ # A failure never fails the toggle.+ try:+ sync_suggestions_scout(+ self.team, acting_user=cast(User, request.user), may_grant=self._may_grant_scout(request)+ )+ except Exception as error:+ capture_exception(error)@extend_schema(request=HogFlowInvocationSerializer, responses={200: _FallbackSerializer})@action(detail=True, methods=["POST"])diff --git a/products/workflows/backend/receivers.py b/products/workflows/backend/receivers.pynew file mode 100644index 000000000000..a3e8e17251f4--- /dev/null+++ b/products/workflows/backend/receivers.py@@ -0,0 +1,41 @@+from django.db import transaction+from django.db.models.signals import post_delete, post_save+from django.dispatch import receiver++from posthog.exceptions_capture import capture_exception+from posthog.models import Team++from products.workflows.backend.models import HogFlow, HogFlowOptimization+++def _sync_after_commit(team_id: int) -> None:+ def sync() -> None:+ # Deferred: the signals facade it pulls in would otherwise load on every django.setup().+ from products.workflows.backend.services import suggestions_scout # noqa: PLC0415++ # Without a person there is nobody to grant the scout's write scope, so this can only switch it off.+ try:+ team = Team.objects.filter(id=team_id).select_related("parent_team").first()+ if team is not None:+ suggestions_scout.sync_suggestions_scout(team, acting_user=None, may_grant=False)+ except Exception as error:+ capture_exception(error)++ transaction.on_commit(sync)+++@receiver(post_delete, sender=HogFlowOptimization)+def optimization_deleted(sender: type, instance: HogFlowOptimization, **kwargs: object) -> None:+ # Fires for each row a deleted workflow takes with it, in single and bulk deletes alike.+ if instance.enabled:+ _sync_after_commit(instance.team_id)+++@receiver(post_save, sender=HogFlow)+def workflow_saved(sender: type, instance: HogFlow, **kwargs: object) -> None:+ # Archiving the last opted-in workflow has to stop the scout as surely as opting it out does.+ if (+ instance.status != HogFlow.State.ACTIVE+ and HogFlowOptimization.objects.unscoped().filter(hog_flow_id=instance.id, enabled=True).exists()+ ):+ _sync_after_commit(instance.team_id)diff --git a/products/workflows/backend/services/suggestions_scout.py b/products/workflows/backend/services/suggestions_scout.pynew file mode 100644index 000000000000..833a5607a42d--- /dev/null+++ b/products/workflows/backend/services/suggestions_scout.py@@ -0,0 +1,80 @@+"""Keep the workflows scout running exactly where someone asked for suggestions.++The scout only reads live workflows whose owner turned on "Suggest improvements", so a project with+none gains nothing from its runs. The first live opted-in workflow switches the scout on for the+project, and losing the last one, by opting out, archiving or deleting it, removes it again.+"""++from django.db import connection, transaction+from django.db.models import Q++from posthog.models import Team, User++from products.signals.backend.facade.api import (+ ScoutEnableRefusal,+ disable_scout_for_product,+ enable_scout_for_product,+ scout_enable_refusal_for_product,+ scout_status_for_product,+)+from products.workflows.backend.models import HogFlow, HogFlowOptimization++SUGGESTIONS_SCOUT = "signals-scout-workflows"+SOURCE_PRODUCT = "workflows"+PROPOSAL_WRITE_SCOPE = "hog_flow_proposal:write"+# Arbitrary, fixed namespace for the per-project advisory lock that serializes reconciliation.+_LOCK_NAMESPACE = 72_031+++def sync_suggestions_scout(team: Team, *, acting_user: User | None, may_grant: bool) -> None:+ """Switch the scout on or off to match the project's live opted-in workflows.++ Switching it on grants `hog_flow_proposal:write` and makes `acting_user` the person its runs act as,+ so it happens only with an `acting_user` and `may_grant` set. Switching it off needs neither.+ When the project still needs the scout but nobody here may grant it, the scout config stays as it is.+ """+ # Scouts belong to the project's main environment, while workflows can live in any of its environments.+ project = team.parent_team or team+ with transaction.atomic():+ with connection.cursor() as cursor:+ cursor.execute("SELECT pg_advisory_xact_lock(%s, %s)", [_LOCK_NAMESPACE, project.id])+ environments = Team.objects.filter(Q(id=project.id) | Q(parent_team_id=project.id)).values("id")+ wanted = (+ HogFlowOptimization.objects.unscoped()+ .filter(team_id__in=environments, enabled=True, hog_flow__status=HogFlow.State.ACTIVE)+ .exists()+ )+ if not wanted:+ disable_scout_for_product(team_id=project.id, skill_name=SUGGESTIONS_SCOUT, source_product=SOURCE_PRODUCT)+ elif acting_user is not None and may_grant:+ enable_scout_for_product(+ team=project,+ skill_name=SUGGESTIONS_SCOUT,+ source_product=SOURCE_PRODUCT,+ acting_user=acting_user,+ write_scopes=[PROPOSAL_WRITE_SCOPE],+ )+++def suggestions_scout_refusal(team: Team, *, acting_user: User, may_grant: bool) -> ScoutEnableRefusal | str | None:+ """Why turning suggestions on here would leave the project with no scout, or None when it would not.++ A project that already has the scout needs nothing new, so nothing is refused there.+ """+ project = team.parent_team or team+ if scout_status_for_product(team_id=project.id, skill_name=SUGGESTIONS_SCOUT) is not None:+ return None+ if not may_grant:+ return "key_cannot_grant"+ return scout_enable_refusal_for_product(+ team=project, skill_name=SUGGESTIONS_SCOUT, acting_user=acting_user, write_scopes=[PROPOSAL_WRITE_SCOPE]+ )+++def suggestions_scout_status(team: Team) -> str:+ """`running`, `paused_by_user`, `paused_by_system` or `not_running` for the project's suggestions scout."""+ project = team.parent_team or team+ status = scout_status_for_product(team_id=project.id, skill_name=SUGGESTIONS_SCOUT)+ if status in ("paused_by_user", "paused_by_system"):+ return status+ return "running" if status is not None else "not_running"diff --git a/products/workflows/backend/tests/api/test_workflow_proposals.py b/products/workflows/backend/tests/api/test_workflow_proposals.pyindex e9c84e32b215..4bed19586ca8 100644--- a/products/workflows/backend/tests/api/test_workflow_proposals.py+++ b/products/workflows/backend/tests/api/test_workflow_proposals.py@@ -9,11 +9,16 @@ from unittest.mock import MagicMock, patchfrom parameterized import parameterizedfrom posthog.cdp.templates.hog_function_template import sync_template_to_db+from posthog.models import Team, Userfrom posthog.models.activity_logging.activity_log import ActivityLog+from posthog.models.organization import OrganizationMembershipfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_value+from products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATES+from products.signals.backend.models import SignalScoutConfig+from products.skills.backend.models.skills import LLMSkillfrom products.workflows.backend.models.hog_flow.hog_flow import HogFlowfrom products.workflows.backend.models.hog_flow_optimization import HogFlowOptimizationfrom products.workflows.backend.models.workflow_proposal import WorkflowProposal@@ -63,16 +68,18 @@ class TestWorkflowProposals(APIBaseTest):)assert response.status_code == 200, response.json()- def _create_active_flow(self) -> str:+ def _create_active_flow(self, optimize: bool = True, team_id: int | None = None) -> str:+ team_id = team_id or self.team.idcreate = self.client.post(- f"/api/projects/{self.team.id}/hog_flows",+ f"/api/projects/{team_id}/hog_flows",{"name": "Proposal Flow", "actions": [_trigger_action(), _webhook_action()]},)assert create.status_code == 201, create.json()flow_id = create.json()["id"]- activate = self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}", {"status": "active"})+ activate = self.client.patch(f"/api/projects/{team_id}/hog_flows/{flow_id}", {"status": "active"})assert activate.status_code == 200, activate.json()- self._optimize(flow_id)+ if optimize:+ self._optimize(flow_id)return flow_iddef _propose(self, flow_id: str, **overrides) -> dict:@@ -573,6 +580,236 @@ class TestWorkflowProposals(APIBaseTest):assert refused.json()["code"] == "workflow_not_optimized"assert WorkflowProposal.objects.for_team(self.team.id).count() == 0+ def _suggestions_scout(self) -> SignalScoutConfig | None:+ return SignalScoutConfig.objects.for_team(self.team.id).filter(skill_name="signals-scout-workflows").first()++ def _toggle(+ self,+ flow_id: str,+ enabled: bool,+ headers: dict | None = None,+ team_id: int | None = None,+ expected_status: int = 200,+ ) -> dict:+ response = self.client.post(+ f"/api/projects/{team_id or self.team.id}/hog_flows/{flow_id}/optimization",+ {"enabled": enabled},+ format="json",+ headers=headers or {},+ )+ assert response.status_code == expected_status, response.json()+ return response.json()++ def test_suggestions_scout_runs_while_any_workflow_asks_for_suggestions(self, _mock_flag):+ first, second = self._create_active_flow(optimize=False), self._create_active_flow(optimize=False)+ assert self._suggestions_scout() is None++ self._toggle(first, True)+ scout = self._suggestions_scout()+ assert scout is not None+ assert (scout.enabled, scout.write_scopes, scout.enabled_by_id) == (+ True,+ ["hog_flow_proposal:write"],+ self.user.id,+ )++ self._toggle(second, True)+ self._toggle(first, False)+ assert self._suggestions_scout() is not None++ self._toggle(second, False)+ assert self._suggestions_scout() is None++ @parameterized.expand(+ [+ ("paused by a person", "paused", "paused_by_user"),+ ("paused by the system", "system_paused", "paused_by_system"),+ ("a member widening another person's scout", "widen", "running"),+ ("api key without the proposal scope turning one off", "key_off", "not_running"),+ ("a scout a person set up", "own", "running"),+ ]+ )+ def test_suggestions_scout_gains_no_grant(self, _mock_flag, _name: str, case: str, scout_status: str):+ flow_team_id = self.team.id+ flow_id = self._create_active_flow(optimize=False, team_id=flow_team_id)+ headers: dict = {}+ enabled = True+ if case == "paused":+ SignalScoutConfig.objects.for_team(self.team.id).create(+ team=self.team, skill_name="signals-scout-workflows", enabled=False+ )+ elif case == "system_paused":+ SignalScoutConfig.objects.for_team(self.team.id).create(+ team=self.team,+ skill_name="signals-scout-workflows",+ source_product="workflows",+ status=SignalScoutConfig.Status.PAUSED_BY_SYSTEM,+ pause_reason=SignalScoutConfig.PauseReason.REPEATED_FAILURES,+ )+ elif case == "widen":+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()+ other = User.objects.create_and_join(self.organization, "[email protected]", None)+ SignalScoutConfig.objects.for_team(self.team.id).create(+ team=self.team,+ skill_name="signals-scout-workflows",+ source_product="workflows",+ enabled=True,+ created_by=other,+ enabled_by=other,+ )+ elif case == "own":+ SignalScoutConfig.objects.for_team(self.team.id).create(+ team=self.team, skill_name="signals-scout-workflows", enabled=True+ )+ elif case == "key_off":+ key = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="toggle", user=self.user, secure_value=hash_key_value(key), scopes=["hog_flow:write"]+ )+ headers = {"authorization": f"Bearer {key}"}+ for flow in (flow_id, self._create_active_flow(optimize=False)):+ HogFlowOptimization.objects.for_team(self.team.id).create(hog_flow_id=flow, enabled=True)+ enabled = False+ self.client.logout()++ original_check = UserAccessControl.check_access_level_for_resource+ with (+ patch(+ "products.signals.backend.scout_harness.team_limits.max_enabled_scouts_for_team",+ return_value=0 if case == "at_cap" else 100,+ ),+ patch.object(+ UserAccessControl,+ "check_access_level_for_resource",+ autospec=True,+ side_effect=lambda uac, resource, *args, **kwargs: (+ resource != "llm_skill"+ if case == "no_skill_access"+ else original_check(uac, resource, *args, **kwargs)+ ),+ ),+ ):+ response = self._toggle(flow_id, enabled, headers, team_id=flow_team_id)++ scout = self._suggestions_scout()+ assert scout is None or scout.write_scopes == []+ assert response["scout_status"] == scout_status+ if case == "system_paused":+ assert scout is not None and scout.status == SignalScoutConfig.Status.PAUSED_BY_SYSTEM++ @parameterized.expand(+ [+ ("a project at its enabled-scout limit", "at_cap", "already runs as many scouts"),+ ("a person without editor access to skills", "no_skill_access", "editor access to skills"),+ ("an organization that has not approved AI", "ai_not_approved", "approved AI data processing"),+ ("a member when a teammate wrote the scout skill", "other_author", "person who wrote"),+ ("api key without the proposal scope", "key_on", "hog_flow_proposal:write"),+ ("api key limited to a child environment", "child_key", "hog_flow_proposal:write"),+ ]+ )+ def test_turning_suggestions_on_is_refused_when_no_scout_could_run(+ self, _mock_flag, _name: str, case: str, message: str+ ):+ flow_team_id = self.team.id+ if case == "child_key":+ flow_team_id = Team.objects.create(organization=self.organization, name="child", parent_team=self.team).id+ flow_id = self._create_active_flow(optimize=False, team_id=flow_team_id)+ headers: dict = {}+ if case == "ai_not_approved":+ self.organization.is_ai_data_processing_approved = False+ self.organization.save()+ elif case == "other_author":+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()+ author = User.objects.create_and_join(+ self.organization, "[email protected]", None, level=OrganizationMembership.Level.ADMIN+ )+ LLMSkill.objects.create(+ team=self.team, name="signals-scout-workflows", description="d", body="b", created_by=author+ )+ elif case in ("key_on", "child_key"):+ key = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="toggle",+ user=self.user,+ secure_value=hash_key_value(key),+ scopes=["*"] if case == "child_key" else ["hog_flow:write"],+ scoped_teams=[flow_team_id] if case == "child_key" else None,+ )+ headers = {"authorization": f"Bearer {key}"}+ self.client.logout()++ original_check = UserAccessControl.check_access_level_for_resource+ with (+ patch(+ "products.signals.backend.scout_harness.team_limits.max_enabled_scouts_for_team",+ return_value=0 if case == "at_cap" else 100,+ ),+ patch.object(+ UserAccessControl,+ "check_access_level_for_resource",+ autospec=True,+ side_effect=lambda uac, resource, *args, **kwargs: (+ resource != "llm_skill"+ if case == "no_skill_access"+ else original_check(uac, resource, *args, **kwargs)+ ),+ ),+ ):+ response = self._toggle(flow_id, True, headers, team_id=flow_team_id, expected_status=400)++ assert message in response["detail"]+ assert not HogFlowOptimization.objects.unscoped().filter(hog_flow_id=flow_id, enabled=True).exists()+ assert self._suggestions_scout() is None++ @parameterized.expand(+ [+ ("a pause by a person", {"status": SignalScoutConfig.Status.PAUSED_BY_USER}),+ (+ "a pause by the system",+ {+ "status": SignalScoutConfig.Status.PAUSED_BY_SYSTEM,+ "pause_reason": SignalScoutConfig.PauseReason.REPEATED_FAILURES,+ },+ ),+ ("a lifecycle lock", {"lifecycle_locked": True}),+ ]+ )+ def test_suggestions_scout_keeps_its_settings_across_opt_out(self, _mock_flag, _name: str, kept: dict):+ flow_id = self._create_active_flow(optimize=False)+ self._toggle(flow_id, True)+ scout = self._suggestions_scout()+ assert scout is not None+ for field, value in kept.items():+ setattr(scout, field, value)+ scout.save(update_fields=list(kept))++ self._toggle(flow_id, False)+ scout = self._suggestions_scout()+ assert scout is not None+ self._toggle(flow_id, True)++ scout = self._suggestions_scout()+ assert scout is not None+ assert {field: getattr(scout, field) for field in kept} == kept++ @parameterized.expand([("archived",), ("draft",)])+ def test_the_suggestions_scout_follows_the_last_opted_in_workflow_leaving_live(self, _mock_flag, status):+ flow_id = self._create_active_flow(optimize=False)+ self._toggle(flow_id, True)+ assert self._suggestions_scout() is not None++ with self.captureOnCommitCallbacks(execute=True):+ response = self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}", {"status": status})+ assert response.status_code == 200, response.json()+ assert self._suggestions_scout() is None++ if status == "draft":+ response = self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}", {"status": "active"})+ assert response.status_code == 200, response.json()+ assert self._suggestions_scout() is not None+def test_a_retry_after_opt_out_returns_the_suggestion_it_already_made(self, _mock_flag):flow_id = self._create_active_flow()self.client.post(diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestions.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestions.tsxindex 3504243c0a0e..df417124ae77 100644--- a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestions.tsx+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestions.tsx@@ -1,6 +1,8 @@import { useActions, useValues } from 'kea'-import { LemonButton, Spinner } from '@posthog/lemon-ui'+import { LemonBanner, LemonButton, Spinner } from '@posthog/lemon-ui'++import { urls } from 'scenes/urls'import { WorkflowAppliedOutcome } from './WorkflowAppliedOutcome'import { workflowProposalsLogic } from './workflowProposalsLogic'@@ -22,6 +24,24 @@ function SuggestionsOffNotice(): JSX.Element {)}+function SuggestionsPausedNotice({ byUser }: { byUser: boolean }): JSX.Element {+ return (+ <LemonBanner+ type="warning"+ action={{+ children: 'Open scout settings',+ to: urls.inboxScout('signals-scout-workflows'),+ // pinned: data-attr - autocapture dashboards read it+ 'data-attr': 'workflow-suggestions-scout-paused-open',+ }}+ >+ {byUser+ ? 'Suggestions are paused for this project because someone paused the workflows scout. Resume it to get new suggestions.'+ : 'Suggestions are paused for this project because the workflows scout kept failing. Check it and resume it to get new suggestions.'}+ </LemonBanner>+ )+}+function SuggestionsUnreadableList({ onRetry }: { onRetry: () => void }): JSX.Element {return (<div className="flex flex-col items-start gap-2">@@ -96,22 +116,38 @@ export function WorkflowSuggestions({ id }: { id: string }): JSX.Element {measuredApplied.length === 0 &&rejectedProposals.length === 0+ const scoutStatus = optimization?.scout_status+ const pausedNotice =+ optimizationEnabled && (scoutStatus === 'paused_by_user' || scoutStatus === 'paused_by_system') ? (+ <SuggestionsPausedNotice byUser={scoutStatus === 'paused_by_user'} />+ ) : null// A failed read leaves the setting unknown, so it cannot stand in for "off".const notice = optimizationUnreadable ? (<SuggestionsUnreadableNotice />) : !optimizationEnabled ? (<SuggestionsOffNotice />- ) : null+ ) : (+ pausedNotice+ )if (nothingFiled) {// Off with nothing filed is the introduction; an unreadable setting keeps its own notice, since it// is not "off". Either one with a queue still shows the queue, which the server keeps resolvable.- if (notice) {- return optimizationUnreadable ? notice : <WorkflowSuggestionsIntroduction id={id} enabled={false} />+ if (optimizationUnreadable || !optimizationEnabled) {+ return optimizationUnreadable ? (+ <SuggestionsUnreadableNotice />+ ) : (+ <WorkflowSuggestionsIntroduction id={id} enabled={false} />+ )}if (!listsSettling) {- return <WorkflowSuggestionsIntroduction id={id} enabled />+ return (+ <div className="flex flex-col gap-4">+ {pausedNotice}+ <WorkflowSuggestionsIntroduction id={id} enabled />+ </div>+ )}}diff --git a/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.tsx b/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.tsxindex d9bc24cd48c3..184c4dba6fee 100644--- a/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.tsx+++ b/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.tsx@@ -199,12 +199,12 @@ export interface workflowProposalsLogicActions {errorObject?: any}setOptimizationEnabledSuccess: (- optimization: HogFlowOptimizationApi,+ optimization: HogFlowOptimizationApi | null,payload?: {enabled: boolean}) => {- optimization: HogFlowOptimizationApi+ optimization: HogFlowOptimizationApi | nullpayload?: {enabled: boolean}@@ -426,7 +426,18 @@ export const workflowProposalsLogic = kea<workflowProposalsLogicType>([}},setOptimizationEnabled: async ({ enabled }) => {- return await hogFlowsOptimizationCreate(String(values.currentTeamIdStrict), props.id, { enabled })+ try {+ return await hogFlowsOptimizationCreate(String(values.currentTeamIdStrict), props.id, {+ enabled,+ })+ } catch (error) {+ // A refusal says why suggestions can't run here, so show it as written and keep the setting.+ if (error instanceof ApiError && error.status === 400 && error.detail) {+ lemonToast.error(error.detail)+ return values.optimization+ }+ throw error+ }},},],diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.tsindex 645f0f63aaa6..76cb7319f879 100644--- a/products/workflows/frontend/generated/api.schemas.ts+++ b/products/workflows/frontend/generated/api.schemas.ts@@ -1249,9 +1249,32 @@ export interface AppMetricsTotalsResponseApi {totals: AppMetricsTotalsResponseApiTotals}+/**+ * * `running` - Running+ * * `paused_by_user` - Paused By User+ * * `paused_by_system` - Paused By System+ * * `not_running` - Not Running+ */+export type SuggestionsScoutStatusEnumApi =+ (typeof SuggestionsScoutStatusEnumApi)[keyof typeof SuggestionsScoutStatusEnumApi]++export const SuggestionsScoutStatusEnumApi = {+ Running: 'running',+ PausedByUser: 'paused_by_user',+ PausedBySystem: 'paused_by_system',+ NotRunning: 'not_running',+} as const+export interface HogFlowOptimizationApi {/** Whether PostHog may suggest changes to this workflow. */enabled: boolean+ /** Whether the project's suggestions scout runs. A paused scout files no suggestions, even for workflows that have suggestions on.+ *+ * * `running` - Running+ * * `paused_by_user` - Paused By User+ * * `paused_by_system` - Paused By System+ * * `not_running` - Not Running */+ readonly scout_status: SuggestionsScoutStatusEnumApi}/**diff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.tsindex eac84d04f175..9dd44614d6c1 100644--- a/products/workflows/frontend/generated/api.ts+++ b/products/workflows/frontend/generated/api.ts@@ -819,7 +819,7 @@ export const getHogFlowsOptimizationCreateUrl = (projectId: string, id: string)export const hogFlowsOptimizationCreate = async (projectId: string,id: string,- hogFlowOptimizationApi: HogFlowOptimizationApi,+ hogFlowOptimizationApi: NonReadonly<HogFlowOptimizationApi>,options?: RequestInit): Promise<HogFlowOptimizationApi> => {return apiMutator<HogFlowOptimizationApi>(getHogFlowsOptimizationCreateUrl(projectId, id), {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 7940c5bbf132..719e95d08b6e 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -54511,9 +54511,32 @@ export namespace Schemas {readonly suggestions_enabled: boolean | null;}+ /**+ * * `running` - Running+ * * `paused_by_user` - Paused By User+ * * `paused_by_system` - Paused By System+ * * `not_running` - Not Running+ */+ export type SuggestionsScoutStatusEnum = typeof SuggestionsScoutStatusEnum[keyof typeof SuggestionsScoutStatusEnum];+++ export const SuggestionsScoutStatusEnum = {+ Running: 'running',+ PausedByUser: 'paused_by_user',+ PausedBySystem: 'paused_by_system',+ NotRunning: 'not_running',+ } as const;+export interface HogFlowOptimization {/** Whether PostHog may suggest changes to this workflow. */enabled: boolean;+ /** Whether the project's suggestions scout runs. A paused scout files no suggestions, even for workflows that have suggestions on.+ *+ * * `running` - Running+ * * `paused_by_user` - Paused By User+ * * `paused_by_system` - Paused By System+ * * `not_running` - Not Running */+ readonly scout_status: SuggestionsScoutStatusEnum;}export interface HogFlowPublishImpactMoveTarget {