: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): add run-now action and hog_flow_id task filter (#91581)
Harley Alexander37c2f926642f
diff --git a/posthog/plugins/plugin_server_api.py b/posthog/plugins/plugin_server_api.pyindex 4c4cbd3dc08e..92975a2a17ea 100644--- a/posthog/plugins/plugin_server_api.py+++ b/posthog/plugins/plugin_server_api.py@@ -108,10 +108,13 @@ def create_hog_flow_scheduled_invocation(team_id: int, hog_flow_id: str, variables: dict[str, object]) -> requests.Response:logger.info(f"Creating scheduled hog flow invocation for hog flow {hog_flow_id} on workers")+ # Same rationale as get_hog_flow_in_flight_count below: a stalled CDP connection must not pin+ # the calling request thread indefinitely.return internal_requests.post(CDP_API_URL + f"/api/projects/{team_id}/hog_flows/{hog_flow_id}/scheduled_invocations",json={"variables": variables},headers=get_internal_api_headers(),+ timeout=10,)diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 86ca2c179a14..9cd3095f402b 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -5268,6 +5268,10 @@ def _list_tasks_queryset(if channel:qs = qs.filter(channel_id=channel)+ hog_flow_id = filters.get("hog_flow_id")+ if hog_flow_id:+ qs = qs.filter(hog_flow_id=hog_flow_id)+if search:search_term = search.strip()if search_term:diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex 47a6b599c9de..e74807130dd6 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -1970,6 +1970,9 @@ class TaskListQuerySerializer(serializers.Serializer):),)channel = serializers.UUIDField(required=False, help_text="Filter tasks to a channel's feed.")+ hog_flow_id = serializers.UUIDField(+ required=False, help_text="Filter tasks to the runs spawned by this workflow's 'Create AI task' action."+ )ordering = serializers.ChoiceField(required=False,choices=sorted(tasks_facade.TASK_LIST_ORDERINGS),diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex aee19b17aa65..85601b55faf5 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -415,13 +415,14 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):200: OpenApiResponse(response=TaskSerializer, description="List of tasks"),},summary="List tasks",- description="Get a list of tasks for the current project, with optional filtering by origin product, stage, organization, repository, and created_by.",+ description="Get a list of tasks for the current project, with optional filtering by origin product, stage, organization, repository, created_by, and the workflow (hog_flow_id) that created the task.",)def list(self, request, *args, **kwargs):filters = {key: request.query_params.get(key) for key in request.query_params}filters["internal"] = getattr(request, "validated_query_data", {}).get("internal")filters["archived"] = getattr(request, "validated_query_data", {}).get("archived")filters["channel"] = getattr(request, "validated_query_data", {}).get("channel")+ filters["hog_flow_id"] = getattr(request, "validated_query_data", {}).get("hog_flow_id")# Staff can opt into seeing every team task; re-check server-side so a client can't# forge the flag to bypass the per-user visibility gate.all_team_tasks = bool(getattr(request, "validated_query_data", {}).get("all_team_tasks"))diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex acdb31821b7c..1481088c5b8d 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -1354,6 +1354,24 @@ class TestTaskAPI(BaseTaskAPITest):self.assertIn("EXISTS", query_sql)self.assertNotIn("SELECT DISTINCT", query_sql)+ def test_list_tasks_hog_flow_id_filter(self):+ hog_flow_id = uuid.uuid4()+ workflow_task = Task.objects.create(+ team=self.team,+ created_by=self.user,+ title="Workflow task",+ description="Test Description",+ origin_product=Task.OriginProduct.WORKFLOW,+ hog_flow_id=hog_flow_id,+ )+ self.create_task("Unrelated task")++ response = self.client.get(f"/api/projects/@current/tasks/?hog_flow_id={hog_flow_id}")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["count"], 1)+ self.assertEqual(response.json()["results"][0]["id"], str(workflow_task.id))+def test_list_tasks_count_matches_queryset(self):for i in range(4):self.create_task(f"Task {i}")diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex 946a6da10a1c..e5a3d85db0f6 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -4919,6 +4919,10 @@ export type TasksListParams = {* @minLength 1*/exclude_origin_product?: TasksListExcludeOriginProduct+ /**+ * Filter tasks to the runs spawned by this workflow's 'Create AI task' action.+ */+ hog_flow_id?: string/*** Filter by the internal flag, which controls whether a task is shown by default, not whether it is accessible. Defaults to excluding internal tasks. Use 'all' to include both internal and user-facing tasks, or 'true' to list only internal tasks. All values are available to any team member; access stays governed by task visibility.*diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.tsindex ba8255c94054..6175e181e9d4 100644--- a/products/tasks/frontend/generated/api.ts+++ b/products/tasks/frontend/generated/api.ts@@ -1244,7 +1244,7 @@ export const getTasksListUrl = (projectId: string, params?: TasksListParams) =>}/**- * Get a list of tasks for the current project, with optional filtering by origin product, stage, organization, repository, and created_by.+ * Get a list of tasks for the current project, with optional filtering by origin product, stage, organization, repository, created_by, and the workflow (hog_flow_id) that created the task.* @summary List tasks*/export const tasksList = async (diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex f36f2797093b..381600d5be50 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -19,11 +19,18 @@ from django.http import Http404, HttpResponsefrom django.utils import timezonefrom django.utils.dateparse import parse_datetime+import requestsimport structlogfrom django_filters import BaseInFilter, CharFilter, FilterSetfrom django_filters.rest_framework import DjangoFilterBackendfrom drf_spectacular.types import OpenApiTypes-from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field, extend_schema_view+from drf_spectacular.utils import (+ OpenApiParameter,+ OpenApiResponse,+ extend_schema,+ extend_schema_field,+ extend_schema_view,+)from rest_framework import exceptions, serializers, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.pagination import LimitOffsetPagination@@ -1763,6 +1770,12 @@ class HogFlowActionSerializer(serializers.Serializer):raise serializers.ValidationError({"config": f"delay_until.expression could not be read as SQL: {e}"})+# Caps both the variable definitions on a workflow and the variable values a single run passes,+# so the two share one number instead of drifting. The runtime also checks dynamically set+# variables against this same limit; each cap here front-runs that check with a clearer error.+HOG_FLOW_VARIABLES_MAX_BYTES = 5120++class HogFlowVariableSerializer(serializers.ListSerializer):child = serializers.DictField(child=serializers.CharField(allow_blank=True),@@ -1779,7 +1792,7 @@ class HogFlowVariableSerializer(serializers.ListSerializer):# This is just a check for massive keys / default values, we also have a check for dynamically# set variables during executiontotal_size = sum(len(json.dumps(item)) for item in attrs)- if total_size > 5120:+ if total_size > HOG_FLOW_VARIABLES_MAX_BYTES:raise serializers.ValidationError("Total size of variables definition must be less than 5KB")return super().validate(attrs)@@ -1969,6 +1982,30 @@ class HogFlowScheduleSerializer(serializers.ModelSerializer):return super().update(instance, validated_data)+class HogFlowRunRequestSerializer(serializers.Serializer):+ variables = serializers.DictField(+ child=serializers.JSONField(allow_null=True, help_text="Override value for one workflow variable."),+ required=False,+ default=dict,+ help_text="Variable value overrides, merged with the workflow's own variable defaults for this run only.",+ )+++class HogFlowRunResponseSerializer(serializers.Serializer):+ status = serializers.CharField(help_text="'queued' once the invocation has been queued for execution.")+ invocation_id = serializers.CharField(help_text="ID of the queued hog flow invocation.")+++# Same window the GitHub webhook delivery dedup uses (posthog/urls.py) — long enough to cover a+# client retrying a slow or timed-out call well after the fact.+HOG_FLOW_RUN_IDEMPOTENCY_TTL_SECONDS = 24 * 60 * 60+HOG_FLOW_RUN_IDEMPOTENCY_IN_PROGRESS = "in_progress"+++def _hog_flow_run_idempotency_cache_key(team_id: int, hog_flow_id: str, idempotency_key: str) -> str:+ return f"hog_flow_run_idempotency:{team_id}:{hog_flow_id}:{idempotency_key}"++def _email_sending_rates(sent: int, bounced: int, complained: int) -> dict[str, float | int]:# Sends are counted at send time but bounces/complaints at webhook time, so feedback arriving# just inside the window for sends just outside it can push the ratio past 1 (worst case: a@@ -3190,6 +3227,7 @@ class HogFlowViewSet("destroy","invocations","schedule_detail",+ "run","bulk_delete","rerun","cancel_invocations",@@ -4941,6 +4979,97 @@ class HogFlowViewSet(self._report_workflow_action("hog_flow_schedule_updated", hog_flow, {"schedule_id": str(schedule.id)})return Response(serializer.data)+ @extend_schema(+ request=HogFlowRunRequestSerializer,+ responses={+ 200: HogFlowRunResponseSerializer,+ 409: OpenApiResponse(description="A run with this Idempotency-Key is already in progress."),+ },+ )+ @action(detail=True, methods=["POST"])+ def run(self, request: Request, *args, **kwargs) -> Response:+ """+ Fire a schedule-triggered workflow immediately, outside its regular schedule.++ Restricted to the `schedule` trigger type: `batch`/`webhook`/etc. triggers have their own+ dedicated entry points (`batch_jobs`, the public webhook URL) with trigger-specific+ guardrails this endpoint doesn't replicate. Requires the workflow to be active, same gate+ the scheduler itself applies in `internal_process_due_schedules`.++ Send an `Idempotency-Key` header to dedupe retries (a double-click, or a client retry+ after a timed-out request): a repeat with the same key returns the first call's result+ instead of firing a second AI task. Without the header, every call fires a new run.+ """+ hog_flow = self.get_object()++ if hog_flow.status != HogFlow.State.ACTIVE:+ raise exceptions.ValidationError("Workflow must be active to run. Enable it first.")++ trigger_type = (hog_flow.trigger or {}).get("type")+ if trigger_type != "schedule":+ raise exceptions.ValidationError(+ f"Only workflows with a 'schedule' trigger can be run this way (this one has '{trigger_type}')."+ )++ serializer = HogFlowRunRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)++ variables = {var.get("key"): var.get("default") for var in hog_flow.variables or []}+ variables.update(serializer.validated_data["variables"])+ if len(json.dumps(variables)) > HOG_FLOW_VARIABLES_MAX_BYTES:+ raise exceptions.ValidationError("Total size of variable overrides must be less than 5KB")++ idempotency_key = request.headers.get("Idempotency-Key")+ cache_key = (+ _hog_flow_run_idempotency_cache_key(self.team_id, str(hog_flow.id), idempotency_key)+ if idempotency_key+ else None+ )+ if cache_key:+ reserved = cache.add(+ cache_key, HOG_FLOW_RUN_IDEMPOTENCY_IN_PROGRESS, timeout=HOG_FLOW_RUN_IDEMPOTENCY_TTL_SECONDS+ )+ if not reserved:+ cached_result = cache.get(cache_key)+ if cached_result == HOG_FLOW_RUN_IDEMPOTENCY_IN_PROGRESS:+ return Response({"detail": "A run with this Idempotency-Key is already in progress."}, status=409)+ return Response(HogFlowRunResponseSerializer(cached_result).data)++ try:+ response = create_hog_flow_scheduled_invocation(+ team_id=self.team_id, hog_flow_id=str(hog_flow.id), variables=variables+ )+ except requests.exceptions.ReadTimeout:+ # CDP already had the request when the timeout fired, so it may already have+ # queued the invocation — unlike a connection failure below, nothing here rules+ # that out. Keep the reservation in place instead of releasing it: a retry with+ # the same key gets a 409 rather than risking a second invocation for a run that+ # already fired. The reservation still expires on its own TTL if CDP never processed it.+ logger.exception(+ "CDP did not respond in time for hog flow run", hog_flow_id=str(hog_flow.id), team_id=self.team_id+ )+ return Response(+ {"detail": "The workflow engine did not respond in time. Wait before retrying with the same key."},+ status=504,+ )+ except requests.RequestException:+ if cache_key:+ cache.delete(cache_key)+ logger.exception("Failed to reach CDP for hog flow run", hog_flow_id=str(hog_flow.id), team_id=self.team_id)+ return Response({"detail": "Could not reach the workflow engine. Try again."}, status=502)++ if response.status_code != 200:+ if cache_key:+ cache.delete(cache_key)+ return Response({"detail": response.text}, status=response.status_code)++ result = response.json()+ if cache_key:+ cache.set(cache_key, result, timeout=HOG_FLOW_RUN_IDEMPOTENCY_TTL_SECONDS)++ self._report_workflow_action("hog_flow_run_now", hog_flow, {})+ return Response(HogFlowRunResponseSerializer(result).data)+class InternalHogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMixin, viewsets.ModelViewSet):"""diff --git a/products/workflows/backend/test/test_hog_flow_schedule.py b/products/workflows/backend/test/test_hog_flow_schedule.pyindex 013b7d3fe87b..fc94d6a998fc 100644--- a/products/workflows/backend/test/test_hog_flow_schedule.py+++ b/products/workflows/backend/test/test_hog_flow_schedule.py@@ -3,12 +3,18 @@ from datetime import UTC, datetime, timedeltaimport unittest.mockfrom posthog.test.base import APIBaseTest+from django.core.cache import cachefrom django.test import override_settingsfrom django.utils import timezone+import requestsfrom parameterized import parameterizedfrom rest_framework import status+from products.workflows.backend.api.hog_flow import (+ HOG_FLOW_RUN_IDEMPOTENCY_IN_PROGRESS,+ _hog_flow_run_idempotency_cache_key,+)from products.workflows.backend.models.hog_flow.hog_flow import HogFlowfrom products.workflows.backend.models.hog_flow_batch_job import HogFlowBatchJobfrom products.workflows.backend.models.hog_flow_schedule import HogFlowSchedule@@ -515,3 +521,193 @@ class TestProcessDueScheduleTriggers(APIBaseTest):assert response.status_code == 200assert str(schedule.id) in response.json()["failed"]assert len(response.json()["processed"]) == 0++[email protected]("products.workflows.backend.api.hog_flow.create_hog_flow_scheduled_invocation")+class TestHogFlowRun(APIBaseTest):+ def _create_workflow(self, workflow_status="active", trigger_type="schedule", variables=None):+ return HogFlow.objects.create(+ team=self.team,+ name="Test Run Workflow",+ status=workflow_status,+ trigger={"type": trigger_type},+ actions=[],+ variables=variables or [],+ )++ def _run_url(self, workflow_id):+ return f"/api/projects/{self.team.id}/hog_flows/{workflow_id}/run/"++ def _mock_success(self, mock_invocation, invocation_id="abc-123"):+ mock_response = unittest.mock.MagicMock()+ mock_response.status_code = 200+ mock_response.json.return_value = {"status": "queued", "invocation_id": invocation_id}+ # Clear a prior side_effect (e.g. from a failure simulated earlier in the same test) —+ # Mock prioritizes side_effect over return_value, so a stale one would keep raising.+ mock_invocation.side_effect = None+ mock_invocation.return_value = mock_response++ def test_run_queues_invocation(self, mock_invocation):+ self._mock_success(mock_invocation)+ workflow = self._create_workflow()++ response = self.client.post(self._run_url(workflow.id))++ assert response.status_code == status.HTTP_200_OK+ assert response.json() == {"status": "queued", "invocation_id": "abc-123"}+ mock_invocation.assert_called_once_with(team_id=self.team.id, hog_flow_id=str(workflow.id), variables={})++ def test_run_merges_variable_defaults_and_overrides(self, mock_invocation):+ # Guards the same variable-resolution contract the scheduler applies in+ # internal_process_due_schedules: run-now must not silently drop a workflow's default+ # variables just because the caller only wants to override one of them.+ self._mock_success(mock_invocation)+ workflow = self._create_workflow(+ variables=[{"key": "greeting", "default": "Hello"}, {"key": "name", "default": "World"}]+ )++ response = self.client.post(self._run_url(workflow.id), {"variables": {"name": "Overridden"}}, format="json")++ assert response.status_code == status.HTTP_200_OK+ mock_invocation.assert_called_once_with(+ team_id=self.team.id,+ hog_flow_id=str(workflow.id),+ variables={"greeting": "Hello", "name": "Overridden"},+ )++ def test_run_rejects_non_schedule_trigger(self, mock_invocation):+ workflow = self._create_workflow(trigger_type="batch")++ response = self.client.post(self._run_url(workflow.id))++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ mock_invocation.assert_not_called()++ def test_run_rejects_inactive_workflow(self, mock_invocation):+ workflow = self._create_workflow(workflow_status="draft")++ response = self.client.post(self._run_url(workflow.id))++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ mock_invocation.assert_not_called()++ def test_run_surfaces_cdp_error(self, mock_invocation):+ mock_response = unittest.mock.MagicMock()+ mock_response.status_code = 502+ mock_response.text = "bad gateway"+ mock_invocation.return_value = mock_response+ workflow = self._create_workflow()++ response = self.client.post(self._run_url(workflow.id))++ assert response.status_code == 502++ def test_run_accepts_null_variable_override(self, mock_invocation):+ # A null override must reach dispatch as None, not be rejected by the child field —+ # matches the schedule path, which stores raw JSON and applies no such restriction.+ self._mock_success(mock_invocation)+ workflow = self._create_workflow(variables=[{"key": "greeting", "default": "Hello"}])++ response = self.client.post(self._run_url(workflow.id), {"variables": {"greeting": None}}, format="json")++ assert response.status_code == status.HTTP_200_OK+ mock_invocation.assert_called_once_with(+ team_id=self.team.id, hog_flow_id=str(workflow.id), variables={"greeting": None}+ )++ def test_run_rejects_oversized_variable_overrides(self, mock_invocation):+ workflow = self._create_workflow()++ response = self.client.post(self._run_url(workflow.id), {"variables": {"blob": "x" * 6000}}, format="json")++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ mock_invocation.assert_not_called()++ def test_run_wraps_connection_error_as_502(self, mock_invocation):+ mock_invocation.side_effect = requests.ConnectionError("boom")+ workflow = self._create_workflow()++ response = self.client.post(self._run_url(workflow.id))++ assert response.status_code == 502++ def test_run_read_timeout_keeps_idempotency_reservation(self, mock_invocation):+ # CDP may already have queued the invocation when the read times out, so a retry+ # under the same key must not dispatch a second one — it should see the reservation+ # still held and get a 409, not a fresh call to CDP.+ mock_invocation.side_effect = requests.exceptions.ReadTimeout("boom")+ workflow = self._create_workflow()++ first = self.client.post(self._run_url(workflow.id), HTTP_IDEMPOTENCY_KEY="timeout-key")+ assert first.status_code == 504++ second = self.client.post(self._run_url(workflow.id), HTTP_IDEMPOTENCY_KEY="timeout-key")+ assert second.status_code == 409+ mock_invocation.assert_called_once()++ def test_run_connection_error_releases_idempotency_reservation(self, mock_invocation):+ # Unlike a read timeout, a connection error means CDP never saw the request, so a+ # retry under the same key must be free to dispatch.+ mock_invocation.side_effect = requests.ConnectionError("boom")+ workflow = self._create_workflow()++ failed = self.client.post(self._run_url(workflow.id), HTTP_IDEMPOTENCY_KEY="conn-error-key")+ assert failed.status_code == 502++ self._mock_success(mock_invocation)+ retried = self.client.post(self._run_url(workflow.id), HTTP_IDEMPOTENCY_KEY="conn-error-key")+ assert retried.status_code == status.HTTP_200_OK+ assert mock_invocation.call_count == 2++ def test_run_with_idempotency_key_dispatches_once(self, mock_invocation):+ self._mock_success(mock_invocation)+ workflow = self._create_workflow()++ first = self.client.post(self._run_url(workflow.id), HTTP_IDEMPOTENCY_KEY="retry-key-1")+ second = self.client.post(self._run_url(workflow.id), HTTP_IDEMPOTENCY_KEY="retry-key-1")++ assert first.status_code == status.HTTP_200_OK+ assert second.status_code == status.HTTP_200_OK+ assert second.json() == first.json()+ mock_invocation.assert_called_once()++ def test_run_with_different_idempotency_keys_dispatches_twice(self, mock_invocation):+ self._mock_success(mock_invocation)+ workflow = self._create_workflow()++ self.client.post(self._run_url(workflow.id), HTTP_IDEMPOTENCY_KEY="retry-key-a")+ self.client.post(self._run_url(workflow.id), HTTP_IDEMPOTENCY_KEY="retry-key-b")++ assert mock_invocation.call_count == 2++ def test_run_rejects_concurrent_call_with_same_idempotency_key(self, mock_invocation):+ # Simulates a request already in flight: the reservation is in place, but the first+ # call hasn't stored a result yet.+ self._mock_success(mock_invocation)+ workflow = self._create_workflow()++ cache_key = _hog_flow_run_idempotency_cache_key(self.team.id, str(workflow.id), "in-flight-key")+ cache.set(cache_key, HOG_FLOW_RUN_IDEMPOTENCY_IN_PROGRESS, timeout=60)+ self.addCleanup(cache.delete, cache_key)++ response = self.client.post(self._run_url(workflow.id), HTTP_IDEMPOTENCY_KEY="in-flight-key")++ assert response.status_code == 409+ mock_invocation.assert_not_called()++ def test_run_releases_idempotency_reservation_on_cdp_error(self, mock_invocation):+ # A failed first attempt must not permanently block retries under the same key.+ mock_response = unittest.mock.MagicMock()+ mock_response.status_code = 502+ mock_response.text = "bad gateway"+ mock_invocation.return_value = mock_response+ workflow = self._create_workflow()++ failed = self.client.post(self._run_url(workflow.id), HTTP_IDEMPOTENCY_KEY="retry-key-2")+ assert failed.status_code == 502++ self._mock_success(mock_invocation)+ retried = self.client.post(self._run_url(workflow.id), HTTP_IDEMPOTENCY_KEY="retry-key-2")++ assert retried.status_code == status.HTTP_200_OK+ assert mock_invocation.call_count == 2diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.tsindex ad02a96a1b17..7d5d1a4771ee 100644--- a/products/workflows/frontend/generated/api.schemas.ts+++ b/products/workflows/frontend/generated/api.schemas.ts@@ -1207,6 +1207,23 @@ export interface HogFlowRevisionRestoreRequestApi {expected_draft_updated_at?: string | null}+/**+ * Variable value overrides, merged with the workflow's own variable defaults for this run only.+ */+export type HogFlowRunRequestApiVariables = { [key: string]: unknown }++export interface HogFlowRunRequestApi {+ /** Variable value overrides, merged with the workflow's own variable defaults for this run only. */+ variables?: HogFlowRunRequestApiVariables+}++export interface HogFlowRunResponseApi {+ /** 'queued' once the invocation has been queued for execution. */+ status: string+ /** ID of the queued hog flow invocation. */+ invocation_id: string+}+export interface PatchedHogFlowScheduleApi {readonly id?: string/** iCalendar RRULE string (e.g. 'FREQ=DAILY;INTERVAL=1'). Must produce occurrences at most once per hour. */diff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.tsindex 9b5d5a7526cb..43bf9f4dfa53 100644--- a/products/workflows/frontend/generated/api.ts+++ b/products/workflows/frontend/generated/api.ts@@ -22,6 +22,8 @@ import type {HogFlowPublishResponseApi,HogFlowRevisionApi,HogFlowRevisionRestoreRequestApi,+ HogFlowRunRequestApi,+ HogFlowRunResponseApi,HogFlowScheduleApi,HogFlowTemplateApi,HogFlowTemplatesListParams,@@ -844,6 +846,36 @@ export const hogFlowsRevisionsRestoreCreate = async (})}+export const getHogFlowsRunCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/hog_flows/${id}/run/`+}++/**+ * Fire a schedule-triggered workflow immediately, outside its regular schedule.+ *+ * Restricted to the `schedule` trigger type: `batch`/`webhook`/etc. triggers have their own+ * dedicated entry points (`batch_jobs`, the public webhook URL) with trigger-specific+ * guardrails this endpoint doesn't replicate. Requires the workflow to be active, same gate+ * the scheduler itself applies in `internal_process_due_schedules`.+ *+ * Send an `Idempotency-Key` header to dedupe retries (a double-click, or a client retry+ * after a timed-out request): a repeat with the same key returns the first call's result+ * instead of firing a second AI task. Without the header, every call fires a new run.+ */+export const hogFlowsRunCreate = async (+ projectId: string,+ id: string,+ hogFlowRunRequestApi?: HogFlowRunRequestApi,+ options?: RequestInit+): Promise<HogFlowRunResponseApi> => {+ return apiMutator<HogFlowRunResponseApi>(getHogFlowsRunCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(hogFlowRunRequestApi),+ })+}+export const getHogFlowsSchedulesListUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/hog_flows/${id}/schedules/`}diff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.tsindex d2c9c6b1eb20..15acc6836b25 100644--- a/products/workflows/frontend/generated/api.zod.ts+++ b/products/workflows/frontend/generated/api.zod.ts@@ -2391,6 +2391,25 @@ export const HogFlowsRevisionsRestoreCreateBody = /* @__PURE__ */ zod.object({),})+/**+ * Fire a schedule-triggered workflow immediately, outside its regular schedule.+ *+ * Restricted to the `schedule` trigger type: `batch`/`webhook`/etc. triggers have their own+ * dedicated entry points (`batch_jobs`, the public webhook URL) with trigger-specific+ * guardrails this endpoint doesn't replicate. Requires the workflow to be active, same gate+ * the scheduler itself applies in `internal_process_due_schedules`.+ *+ * Send an `Idempotency-Key` header to dedupe retries (a double-click, or a client retry+ * after a timed-out request): a repeat with the same key returns the first call's result+ * instead of firing a second AI task. Without the header, every call fires a new run.+ */+export const HogFlowsRunCreateBody = /* @__PURE__ */ zod.object({+ variables: zod+ .record(zod.string(), zod.unknown().describe('Override value for one workflow variable.'))+ .optional()+ .describe("Variable value overrides, merged with the workflow's own variable defaults for this run only."),+})+export const hogFlowsSchedulesCreateBodyTimezoneMax = 64export const HogFlowsSchedulesCreateBody = /* @__PURE__ */ zod.object({diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yamlindex 9dd3b9ac1611..e630ba544acb 100644--- a/products/workflows/mcp/tools.yaml+++ b/products/workflows/mcp/tools.yaml@@ -96,6 +96,9 @@ tools:hog-flows-revisions-retrieve:operation: hog_flows_revisions_retrieveenabled: false+ hog-flows-run-create:+ operation: hog_flows_run_create+ enabled: falsehog-flows-schedules-create:operation: hog_flows_schedules_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex d19cdcbc8c81..c0e354879600 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -42219,6 +42219,23 @@ export namespace Schemas {expected_draft_updated_at?: string | null;}+ /**+ * Variable value overrides, merged with the workflow's own variable defaults for this run only.+ */+ export type HogFlowRunRequestVariables = {[key: string]: unknown};++ export interface HogFlowRunRequest {+ /** Variable value overrides, merged with the workflow's own variable defaults for this run only. */+ variables?: HogFlowRunRequestVariables;+ }++ export interface HogFlowRunResponse {+ /** 'queued' once the invocation has been queued for execution. */+ status: string;+ /** ID of the queued hog flow invocation. */+ invocation_id: string;+ }+/*** @nullable*/@@ -98179,6 +98196,10 @@ export namespace Schemas {* @minLength 1*/exclude_origin_product?: TasksListExcludeOriginProduct;+ /**+ * Filter tasks to the runs spawned by this workflow's 'Create AI task' action.+ */+ hog_flow_id?: string;/*** Filter by the internal flag, which controls whether a task is shown by default, not whether it is accessible. Defaults to excluding internal tasks. Use 'all' to include both internal and user-facing tasks, or 'true' to list only internal tasks. All values are available to any team member; access stays governed by task visibility.*diff --git a/services/mcp/src/generated/tasks/api.ts b/services/mcp/src/generated/tasks/api.tsindex 8f21fd61b51d..bfc488c17420 100644--- a/services/mcp/src/generated/tasks/api.ts+++ b/services/mcp/src/generated/tasks/api.ts@@ -845,7 +845,7 @@ export const TaskChannelsInstructionsUpdateBody = /* @__PURE__ */ zod.describe('Request body for publishing a new instructions version.')/**- * Get a list of tasks for the current project, with optional filtering by origin product, stage, organization, repository, and created_by.+ * Get a list of tasks for the current project, with optional filtering by origin product, stage, organization, repository, created_by, and the workflow (hog_flow_id) that created the task.* @summary List tasks*/export const TasksListParams = /* @__PURE__ */ zod.object({@@ -915,6 +915,10 @@ export const TasksListQueryParams = /* @__PURE__ */ zod.object({.describe('Exclude tasks with this origin product from the results\n\n\* `onboarding` - Onboarding\n\* `error_tracking` - Error Tracking\n\* `eval_clusters` - Eval Clusters\n\* `user_created` - User Created\n\* `slack` - Slack\n\* `support_queue` - Support Queue\n\* `session_summaries` - Session Summaries\n\* `posthog_ai` - PostHog AI\n\* `experiments` - Experiments\n\* `signal_report` - Signal Report\n\* `signals_scout` - Signals Scout\n\* `support_reply` - Support Reply\n\* `hogdesk` - HogDesk\n\* `review_hog` - ReviewHog\n\* `image_builder` - Image Builder\n\* `loop` - Loop\n\* `mcp_analytics` - MCP Analytics\n\* `signals_chat` - Signals Chat\n\* `task_analysis` - Task Analysis\n\* `workflow` - Workflow'),+ hog_flow_id: zod+ .string()+ .optional()+ .describe("Filter tasks to the runs spawned by this workflow's 'Create AI task' action."),internal: zod.enum(['true', 'false', 'all']).optional()diff --git a/services/mcp/src/tools/generated/tasks.ts b/services/mcp/src/tools/generated/tasks.tsindex 1589ef2266ef..215c6d0e3a2d 100644--- a/services/mcp/src/tools/generated/tasks.ts+++ b/services/mcp/src/tools/generated/tasks.ts@@ -584,6 +584,7 @@ const tasksList = (): ToolBase<typeof TasksListSchema, WithPostHogUrl<Schemas.Pacommented_by: params.commented_by,created_by: params.created_by,exclude_origin_product: params.exclude_origin_product,+ hog_flow_id: params.hog_flow_id,internal: params.internal,limit: params.limit,mentions: params.mentions,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-list.jsonindex 14124fba6029..ca49672fb278 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/tasks-list.json@@ -54,6 +54,10 @@],"type": "string"},+ "hog_flow_id": {+ "description": "Filter tasks to the runs spawned by this workflow's 'Create AI task' action.",+ "type": "string"+ },"internal": {"description": "Filter by the internal flag, which controls whether a task is shown by default, not whether it is accessible. Defaults to excluding internal tasks. Use 'all' to include both internal and user-facing tasks, or 'true' to list only internal tasks. All values are available to any team member; access stays governed by task visibility.\n\n* `true` - true\n* `false` - false\n* `all` - all","enum": ["true", "false", "all"],