: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): tag workflows and search or filter the list by tag (#120456)
Meikel Ratz502731151e21
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex aa0ffea70566..bb122aae8c87 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -6288,6 +6288,8 @@ const api = {type?: HogFlowListType[]/** JSON-encoded object the stored trigger must contain, e.g. `{"type":"batch"}`. */trigger?: string+ /** JSON-encoded list of tag names. A workflow matches when it carries at least one. */+ tags?: stringlimit?: numberoffset?: number}): Promise<CountedPaginatedResponse<HogFlow>> {diff --git a/frontend/src/lib/components/ActivityLog/activityDescriptions/tagActivityDescriber.tsx b/frontend/src/lib/components/ActivityLog/activityDescriptions/tagActivityDescriber.tsxindex 3553382ba75c..f6457348c1a2 100644--- a/frontend/src/lib/components/ActivityLog/activityDescriptions/tagActivityDescriber.tsx+++ b/frontend/src/lib/components/ActivityLog/activityDescriptions/tagActivityDescriber.tsx@@ -26,7 +26,7 @@ const getRelatedObjectDescription = (context: any, preposition?: 'to' | 'from'):}const objectType = context.related_object_type- const objectTypeDisplayName = objectType.replace(/_/g, ' ')+ const objectTypeDisplayName = objectType === 'hog_flow' ? 'workflow' : objectType.replace(/_/g, ' ')const objectId = context.related_object_idlet objectName = context.related_object_name || `${objectType} ${objectId}`@@ -86,6 +86,12 @@ const getRelatedObjectDescription = (context: any, preposition?: 'to' | 'from'):<strong>{displayName}</strong></Link>)+ case 'hog_flow':+ return (+ <Link to={urls.workflow(objectId, 'workflow')}>+ <strong>{displayName}</strong>+ </Link>+ )default:return <strong>{displayName}</strong>}diff --git a/posthog/models/activity_logging/signal_handlers.py b/posthog/models/activity_logging/signal_handlers.pyindex dd66319186d2..490ad2390952 100644--- a/posthog/models/activity_logging/signal_handlers.py+++ b/posthog/models/activity_logging/signal_handlers.py@@ -668,6 +668,7 @@ RELATED_OBJECT_ACTIVITY_LOGGERS: dict[str, RelatedObjectActivityLogger] = {),"account": RelatedObjectActivityLogger(scope="Account"),"endpoint": RelatedObjectActivityLogger(scope="Endpoint"),+ "hog_flow": RelatedObjectActivityLogger(scope="HogFlow"),}diff --git a/posthog/models/tagged_item_registry.py b/posthog/models/tagged_item_registry.pyindex 6da61d5d84c8..3141608dcae5 100644--- a/posthog/models/tagged_item_registry.py+++ b/posthog/models/tagged_item_registry.py@@ -76,6 +76,7 @@ TAGGABLE_MODELS: tuple[TaggableModel, ...] = (TaggableModel(model_label="posthog.Project", legacy_field="project", object_field=OBJECT_ID),TaggableModel(model_label="experiments.Experiment", legacy_field="experiment", object_field=OBJECT_ID),TaggableModel(model_label="tasks.Task", legacy_field="task", object_field=OBJECT_UUID),+ TaggableModel(model_label="workflows.HogFlow", legacy_field="hog_flow", object_field=OBJECT_UUID),)_BY_LABEL: dict[str, TaggableModel] = {entry.model_label: entry for entry in TAGGABLE_MODELS}diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.tsindex bf0a3c30c3c6..c14bf27b930a 100644--- a/products/desktop/packages/api-client/src/generated.ts+++ b/products/desktop/packages/api-client/src/generated.ts@@ -15656,6 +15656,10 @@ export namespace Schemas {* Mixin for serializers to add user access control fields*/description?: string | undefined;+ /**+ * Mixin for serializers to add user access control fields+ */+ tags?: Array<string> | undefined;version: number;/*** Mixin for serializers to add user access control fields@@ -15753,6 +15757,10 @@ export namespace Schemas {id: string;name: string | null;description: string;+ /**+ * Tags for organizing workflows, for example by team or use case. Sorted by name.+ */+ tags: Array<string>;version: number;status: HogFlowStateEnum & unknown;origin_product: HogFlowOriginProductEnum | NullEnum;@@ -15816,6 +15824,10 @@ export namespace Schemas {* Mixin for serializers to add user access control fields*/description?: string | undefined;+ /**+ * Mixin for serializers to add user access control fields+ */+ tags?: Array<string> | undefined;version: number;/*** Mixin for serializers to add user access control fields@@ -19272,6 +19284,7 @@ export namespace Schemas {id: string;name: string | null;description: string;+ tags: Array<string>;version: number;status: HogFlowStateEnum;origin_product: HogFlowOriginProductEnum | NullEnum;@@ -22353,6 +22366,7 @@ export namespace Endpoints {origin_product: "broadcasts" | "loops" | "transactional_emails";search: string;status: "active" | "archived" | "draft";+ tags: string;trigger: string;type: string;updated_at: string;diff --git a/products/workflows/backend/facade/contracts.py b/products/workflows/backend/facade/contracts.pyindex c20ef4276fdf..06c0a2860d4c 100644--- a/products/workflows/backend/facade/contracts.py+++ b/products/workflows/backend/facade/contracts.py@@ -534,6 +534,8 @@ class Workflow:email_sending_paused_by: stremail_sending_resumed_at: datetime | Noneuser_access_level: str | None+ # Tag names, sorted.+ tags: tuple[str, ...] = ()# Read on the list only. A single-workflow read leaves both None and ``schedules`` filled.pending_suggestions: int | None = Nonesuggestions_enabled: bool | None = None@@ -619,6 +621,8 @@ class WorkflowListQuery:broadcast_eligible: bool = Falsebroadcast_statuses: frozenset[str] = frozenset()suggestions_first: bool = False+ # A workflow matches when it carries at least one of these tags.+ tags: frozenset[str] = frozenset()field_filters: Mapping[str, str] = field(default_factory=dict)diff --git a/products/workflows/backend/models/hog_flow/hog_flow.py b/products/workflows/backend/models/hog_flow/hog_flow.pyindex 54e45b8269b4..d92884eac16f 100644--- a/products/workflows/backend/models/hog_flow/hog_flow.py+++ b/products/workflows/backend/models/hog_flow/hog_flow.py@@ -8,6 +8,7 @@ from django.utils.functional import Promiseimport structlogfrom posthog.helpers.encrypted_fields import EncryptedJSONStringField+from posthog.models.tagged_items_relation import Taggablefrom posthog.models.team.team import Teamfrom posthog.models.utils import UUIDTModelfrom posthog.plugins.plugin_server_api import reload_hog_flows_on_workers@@ -150,7 +151,8 @@ def hog_flow_origin_product_choices() -> list[tuple[str, str | Promise]]:return list(HogFlow.OriginProduct.choices)-class HogFlow(UUIDTModel):+# nosemgrep: no-new-uuidt-models -- an existing model, and its stored ids cannot change.+class HogFlow(Taggable, UUIDTModel):"""Stores the version, layout and other meta information for each HogFlow"""diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.pyindex 1bf25f0cd858..3487fde25563 100644--- a/products/workflows/backend/presentation/views/hog_flow.py+++ b/products/workflows/backend/presentation/views/hog_flow.py@@ -2936,6 +2936,10 @@ class HogFlowLastRunSerializer(serializers.Serializer):)+# Each tag costs get_or_create round trips in set_tags_on_object, so cap the list.+_MAX_WORKFLOW_TAGS = 10++class HogFlowMinimalSerializer(UserAccessControlSerializerMixin, serializers.Serializer):# The fields the model used to supply. Each is read-only here; the full serializer declares the# writable ones again, so those are typed as any field.@@ -2975,6 +2979,11 @@ class HogFlowMinimalSerializer(UserAccessControlSerializerMixin, serializers.Sersuggestions_enabled = serializers.SerializerMethodField(help_text="Whether someone turned suggestions on for this workflow. Read on the list only.")+ tags = serializers.ListField(+ child=serializers.CharField(),+ read_only=True,+ help_text="Tags for organizing workflows, for example by team or use case. Sorted by name.",+ )class Meta:# The fields each serializer returns, in this order. get_fields applies it.@@ -2982,6 +2991,7 @@ class HogFlowMinimalSerializer(UserAccessControlSerializerMixin, serializers.Ser"id","name","description",+ "tags","version","status","origin_product",@@ -3079,6 +3089,7 @@ class HogFlowSummarySerializer(HogFlowMinimalSerializer):"id","name","description",+ "tags","version","status","origin_product",@@ -3103,6 +3114,15 @@ class HogFlowSerializer(HogFlowMinimalSerializer):max_length=400, required=False, allow_null=True, allow_blank=True, help_text="Workflow name.")description = serializers.CharField(required=False, allow_blank=True, default="", help_text="Optional description.")+ tags = serializers.ListField(+ child=serializers.CharField(max_length=255), # Tag.name column limit.+ required=False,+ max_length=_MAX_WORKFLOW_TAGS,+ help_text=(+ "Tags for organizing workflows, for example by team or use case. Tags are shared with the rest of "+ "the project. Omit to keep the current tags, send an empty list to remove them all."+ ),+ )status = serializers.ChoiceField(choices=HogFlowState.choices,required=False,@@ -3388,6 +3408,7 @@ class HogFlowSerializer(HogFlowMinimalSerializer):"id","name","description",+ "tags","version","status","origin_product",@@ -4688,13 +4709,18 @@ class HogFlowVersionMetricsRequestSerializer(AppMetricsRequestSerializer):OpenApiParameter("search",OpenApiTypes.STR,- description="Case-insensitive search. Matches workflow name and description first; only when nothing matches those, it matches step names and the subject line, preheader and body text of email steps, in both the live workflow and its pending draft.",+ description="Case-insensitive search. Matches workflow name, description and tag names first; only when nothing matches those, it matches step names and the subject line, preheader and body text of email steps, in both the live workflow and its pending draft.",),OpenApiParameter("created_by",OpenApiTypes.UUID,description="Filter to workflows created by the user with this uuid.",),+ OpenApiParameter(+ "tags",+ OpenApiTypes.STR,+ description='JSON-encoded list of tag names, e.g. ["growth", "onboarding"]. Returns workflows that carry at least one of these tags.',+ ),OpenApiParameter("type",OpenApiTypes.STR,@@ -4939,6 +4965,18 @@ class HogFlowViewSet(except (ValueError, KeyError, TypeError):raise exceptions.ValidationError({"trigger": f"Invalid trigger"})+ def _tags_filter(self) -> frozenset[str]:+ raw = self.request.GET.get("tags")+ if not raw:+ return frozenset()+ try:+ tags = json.loads(raw)+ except ValueError:+ raise exceptions.ValidationError({"tags": "Must be a JSON-encoded list of tag names"})+ if not isinstance(tags, list) or not all(isinstance(tag, str) for tag in tags):+ raise exceptions.ValidationError({"tags": "Must be a JSON-encoded list of tag names"})+ return frozenset(tags)+def _list_query(self) -> WorkflowListQuery:"""The list's query parameters, validated in the order the list has always checked them."""params = self.request.GET@@ -4979,6 +5017,7 @@ class HogFlowViewSet()trigger = self._trigger_filter()+ tags = self._tags_filter()search = (params.get("search") or "").strip()if len(search) > 200:@@ -4993,6 +5032,7 @@ class HogFlowViewSet(broadcast_eligible=params.get("broadcast_eligible") == "true",broadcast_statuses=frozenset(broadcast_statuses),suggestions_first=params.get("suggestions_first") in ("true", "1"),+ tags=tags,field_filters={name: params[name] for name in WORKFLOW_FIELD_FILTER_PARAMS if name in params},)diff --git a/products/workflows/backend/services/hog_flow_reads.py b/products/workflows/backend/services/hog_flow_reads.pyindex 9ee32e2bd9e6..b23bc6f650f8 100644--- a/products/workflows/backend/services/hog_flow_reads.py+++ b/products/workflows/backend/services/hog_flow_reads.py@@ -8,12 +8,15 @@ from uuid import UUIDfrom django.core.exceptions import ValidationErrorfrom django.db import models-from django.db.models import Count, F, OuterRef, Q, QuerySet, Subquery, Value+from django.db.models import Count, F, OuterRef, Prefetch, Q, QuerySet, Subquery, Valuefrom django.db.models.expressions import RawSQLfrom django.db.models.functions import Coalescefrom django_filters import BooleanFilter, FilterSet+from posthog.api.tagged_item import current_tag_names+from posthog.models import TaggedItem+from products.workflows.backend.facade.contracts import (Workflow,WorkflowAccessDenied,@@ -235,7 +238,14 @@ def _list_queryset(user_access_control: "UserAccessControl | None",include_all_if_admin: bool,) -> QuerySet:- queryset = HogFlow.objects.filter(team_id=team_id).select_related("created_by")+ queryset = (+ HogFlow.objects.filter(team_id=team_id)+ .select_related("created_by")+ # _to_workflow reads prefetched_tags, so a page costs one tag query rather than one per row.+ .prefetch_related(+ Prefetch("tagged_items", queryset=TaggedItem.objects.select_related("tag"), to_attr="prefetched_tags")+ )+ )pending = (WorkflowProposal.objects.filter(hog_flow=OuterRef("pk"), status=WorkflowProposalStatus.SUGGESTED)@@ -288,6 +298,13 @@ def _list_queryset(if query.trigger:queryset = queryset.filter(trigger__contains=query.trigger)+ if query.tags:+ queryset = queryset.filter(+ id__in=TaggedItem.objects.for_model(HogFlow)+ .filter(tag__team_id=team_id, tag__name__in=query.tags)+ .values("object_uuid")+ )+if user_access_control is not None:queryset = user_access_control.filter_queryset_by_access_level(queryset, include_all_if_admin=include_all_if_admin@@ -316,11 +333,19 @@ def _list_queryset(# so "welcome email" also matches "welcome-email" — same approach as feature flag search.regex_pattern = re.escape(query.search).replace(r"\ ", r"[\s\-_]*")- # Name and description are small columns, while the step search has to read every workflow's `actions`+ # Name, description and tags are small, while the step search has to read every workflow's `actions`# JSON (tens of KB per email step). Only fall through to the step content when nothing matched by# name, so the common search stays cheap and a subject line or body text, which rarely appears in a# workflow name, is still found.- by_name = Q(name__iregex=regex_pattern) | Q(description__iregex=regex_pattern)+ by_name = (+ Q(name__iregex=regex_pattern)+ | Q(description__iregex=regex_pattern)+ | Q(+ id__in=TaggedItem.objects.for_model(HogFlow)+ .filter(tag__team_id=team_id, tag__name__iregex=regex_pattern)+ .values("object_uuid")+ )+ )if queryset.filter(by_name).exists():return queryset.filter(by_name)return queryset.filter(Q(_action_content_matches(regex_pattern)))@@ -377,6 +402,7 @@ def _to_workflow(email_sending_paused_by=flow.email_sending_paused_by,email_sending_resumed_at=flow.email_sending_resumed_at,user_access_level=access_level,+ tags=tuple(sorted(current_tag_names(flow))),pending_suggestions=getattr(flow, "pending_suggestions", None),suggestions_enabled=getattr(flow, "suggestions_enabled", None),)diff --git a/products/workflows/backend/services/hog_flow_writes.py b/products/workflows/backend/services/hog_flow_writes.pyindex 15717ac9c0c1..97599dc6573f 100644--- a/products/workflows/backend/services/hog_flow_writes.py+++ b/products/workflows/backend/services/hog_flow_writes.py@@ -7,6 +7,9 @@ from django.db import transactionfrom django.utils import timezonefrom django.utils.dateparse import parse_datetime+from posthog.api.tagged_item import cleanup_orphan_tags, current_tag_names, set_tags_on_object+from posthog.models.tag import tagify+from products.workflows.backend.facade.contracts import (WorkflowEditState,WorkflowHasNoDraft,@@ -42,9 +45,12 @@ def field_values(flow: HogFlow) -> dict[str, object]:def create_workflow(*, team_id: int, user_id: Optional[int], validated_data: dict) -> WorkflowWriteResult:with transaction.atomic():data = dict(validated_data)+ tags = data.pop("tags", None)if "actions" in data:data["encrypted_inputs"] = strip_secrets_from_content(data, template_cache={})instance = HogFlow.objects.create(team_id=team_id, created_by_id=user_id, **data)+ if tags:+ set_tags_on_object(tags, instance)HogFlowRevision.objects.create(team_id=team_id,hog_flow=instance,@@ -322,6 +328,9 @@ def update_workflow(# avoids false positives from timestamp round-tripping - equal means the client is already current.# Callers that omit `base_updated_at` keep the previous last-writer-wins behavior.base_stamp = _parse_stamp(base_updated_at)+ # Tags are metadata on their own rows: they apply live, never to the draft, and never version the workflow.+ validated_data = dict(validated_data)+ tags = validated_data.pop("tags", None)with transaction.atomic():before_update = HogFlow.objects.select_for_update().get(pk=hog_flow_id, team_id=team_id)@@ -331,6 +340,8 @@ def update_workflow(raise WorkflowStale()# The write target is a second read, so `before_update` keeps the pre-write state.instance = HogFlow.objects.get(pk=hog_flow_id, team_id=team_id)+ # The editor sends the tags with every save, so only write them when they change.+ tags_changed = tags is not None and {tagify(tag) for tag in tags} != current_tag_names(before_update)# Draft edits race against other draft edits, not against the live row (which they don't# touch), so the staleness baseline is the draft's own timestamp once a draft exists.@@ -365,7 +376,8 @@ def update_workflow(for k, v in validated_data.items()if k not in DRAFT_CONTENT_FIELDS and k != "billable_action_types"}- if remaining:+ # A tag change is a live metadata write too, so it takes the same fence and advances the live stamp.+ if remaining or tags_changed:# The draft-stamp guard above doesn't protect this live write: a concurrent# live-metadata edit bumps updated_at but not draft_updated_at, so a staged save# would silently overwrite it. Clients that write metadata alongside a staged@@ -388,6 +400,10 @@ def update_workflow(if bump:_append_revisions(team_id, user_id, instance, before_update)+ if tags_changed:+ set_tags_on_object(tags, instance)+ cleanup_orphan_tags(team_id)+paused = 0if not route_to_draft:_reschedule_timing_edits(team_id, before_update, instance)diff --git a/products/workflows/backend/tests/api/test_hog_flow.py b/products/workflows/backend/tests/api/test_hog_flow.pyindex 11329d190bff..a9cb7643c802 100644--- a/products/workflows/backend/tests/api/test_hog_flow.py+++ b/products/workflows/backend/tests/api/test_hog_flow.py@@ -17,6 +17,7 @@ from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status+from posthog.api.tagged_item import set_tags_on_objectfrom posthog.constants import AvailableFeaturefrom posthog.event_usage import EventSourcefrom posthog.models import Organization, OrganizationMembership, Team, User@@ -251,6 +252,7 @@ class TestHogFlowAPI(APIBaseTest):("name_match", "search=welcome", {"Welcome email"}),("case_insensitive", "search=WELCOME", {"Welcome email"}),("description_match", "search=quarterly", {"Digest"}),+ ("tag_match", "search=retent", {"Digest"}),("space_matches_separators", "search=password reset", {"Password reset"}),("step_name_match", "search=monthly invoice", {"Billing"}),("email_subject_match", "search=for march", {"Billing"}),@@ -279,7 +281,12 @@ class TestHogFlowAPI(APIBaseTest):def test_list_search_matches_name_description_and_step_content(self, _name, query, expected_names):HogFlow.objects.create(team=self.team, name="Welcome email", created_by=self.user)HogFlow.objects.create(team=self.team, name="Password reset", created_by=self.user)- HogFlow.objects.create(team=self.team, name="Digest", description="quarterly summary", created_by=self.user)+ set_tags_on_object(+ ["retention"],+ HogFlow.objects.create(+ team=self.team, name="Digest", description="quarterly summary", created_by=self.user+ ),+ )HogFlow.objects.create(team=self.team, name="March campaign", status=HogFlow.State.ACTIVE, created_by=self.user)HogFlow.objects.create(team=self.team,@@ -406,6 +413,67 @@ class TestHogFlowAPI(APIBaseTest):assert response.status_code == 200, response.json()assert {flow["name"] for flow in response.json()["results"]} == {"Theirs"}+ @parameterized.expand(+ [+ ("one_tag", '["growth"]', {"Onboarding", "Upsell"}),+ ("any_of_several_tags", '["billing", "support"]', {"Upsell", "Refunds"}),+ ("unused_tag", '["unknown"]', set()),+ ]+ )+ def test_list_filter_by_tags(self, _name, tags_param, expected_names):+ for name, tags in (+ ("Onboarding", ["growth"]),+ ("Upsell", ["growth", "billing"]),+ ("Refunds", ["support"]),+ ("Untagged", []),+ ):+ set_tags_on_object(tags, HogFlow.objects.create(team=self.team, name=name, created_by=self.user))++ response = self.client.get(f"/api/projects/{self.team.id}/hog_flows", {"tags": tags_param})+ assert response.status_code == 200, response.json()+ assert {flow["name"] for flow in response.json()["results"]} == expected_names++ @parameterized.expand([("not_json", "growth"), ("not_a_list", '"growth"'), ("not_strings", "[1]")])+ def test_list_rejects_malformed_tags_filter(self, _name, tags_param):+ response = self.client.get(f"/api/projects/{self.team.id}/hog_flows", {"tags": tags_param})+ assert response.status_code == 400, response.json()++ def test_tags_round_trip_through_create_update_and_list(self):+ hog_flow, _ = self._create_hog_flow_with_action(+ {"template_id": "template-webhook", "inputs": {"url": {"value": "https://example.com"}}}+ )+ response = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows", {**hog_flow, "tags": ["Onboarding", "growth"]}, format="json"+ )+ assert response.status_code == 201, response.json()+ flow_id = response.json()["id"]+ assert response.json()["tags"] == ["growth", "onboarding"]++ url = f"/api/projects/{self.team.id}/hog_flows/{flow_id}"+ response = self.client.patch(url, {"name": "Renamed"}, format="json")+ assert response.json()["tags"] == ["growth", "onboarding"]++ response = self.client.patch(url, {"tags": ["growth"]}, format="json")+ assert response.status_code == 200, response.json()+ assert response.json()["tags"] == ["growth"]+ tag_changes = [+ change+ for entry in ActivityLog.objects.filter(scope="HogFlow", item_id=flow_id, activity="updated")+ for change in (entry.detail or {}).get("changes") or []+ if change["field"] == "tag"+ ]+ assert {(change["action"], change["before"], change["after"]) for change in tag_changes} == {+ ("created", None, "growth"),+ ("created", None, "onboarding"),+ ("deleted", "onboarding", None),+ }++ list_response = self.client.get(f"/api/projects/{self.team.id}/hog_flows")+ assert [flow["tags"] for flow in list_response.json()["results"]] == [["growth"]]++ response = self.client.patch(url, {"tags": []}, format="json")+ assert response.json()["tags"] == []+@parameterized.expand([("messaging", "messaging", {"Email drip", "Push blast"}),diff --git a/products/workflows/backend/tests/api/test_hog_flow_draft_publish.py b/products/workflows/backend/tests/api/test_hog_flow_draft_publish.pyindex aa06915c57ab..89d553e96540 100644--- a/products/workflows/backend/tests/api/test_hog_flow_draft_publish.py+++ b/products/workflows/backend/tests/api/test_hog_flow_draft_publish.py@@ -151,6 +151,26 @@ class TestHogFlowDraftPublish(APIBaseTest):assert flow.name == "Renamed live"assert response.json()["draft"] is not None+ def test_web_content_edit_with_stage_draft_applies_tags_live_and_advances_the_live_stamp(self):+ flow_id = self._create_active_flow()+ live_stamp_before = HogFlow.objects.get(pk=flow_id).updated_at++ with time_machine.travel(live_stamp_before + timedelta(minutes=1)):+ response = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",+ {+ "actions": [_trigger_action(), _webhook_action(url="https://changed.example.com")],+ "tags": ["growth"],+ "stage_draft": True,+ },+ )+ assert response.status_code == 200, response.json()++ flow = HogFlow.objects.get(pk=flow_id)+ assert flow.draft is not None+ assert response.json()["tags"] == ["growth"]+ assert flow.updated_at > live_stamp_before+def test_web_stage_draft_saves_incomplete_content_leniently(self):# The builder auto-saves mid-edit, so a staged draft must accept a step whose required# inputs aren't filled in yet; strict validation would 400 every auto-save while thediff --git a/products/workflows/frontend/Workflows/WorkflowScenePanel.tsx b/products/workflows/frontend/Workflows/WorkflowScenePanel.tsxindex 5dd5eaace0f5..c30020637fb3 100644--- a/products/workflows/frontend/Workflows/WorkflowScenePanel.tsx+++ b/products/workflows/frontend/Workflows/WorkflowScenePanel.tsx@@ -4,9 +4,16 @@ import { router } from 'kea-router'import { IconArchive, IconCopy, IconScreen } from '@posthog/icons'import { AccessControlAction } from 'lib/components/AccessControlAction'+import { SceneTags } from 'lib/components/Scenes/SceneTags'import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'+import { accessLevelSatisfied } from 'lib/utils/accessControlUtils'-import { ScenePanel, ScenePanelActionsSection, ScenePanelDivider } from '~/layout/scenes/SceneLayout'+import {+ ScenePanel,+ ScenePanelActionsSection,+ ScenePanelDivider,+ ScenePanelInfoSection,+} from '~/layout/scenes/SceneLayout'import { AccessControlLevel, AccessControlResourceType } from '~/types'import { workflowSuggestionsAvailabilityLogic } from './suggestions/workflowSuggestionsAvailabilityLogic'@@ -17,14 +24,31 @@ import { WorkflowSceneLogicProps } from './workflowSceneLogic'export function WorkflowScenePanel(props: WorkflowSceneLogicProps): JSX.Element {const { workflow, workflowUserAccessLevel } = useValues(workflowLogic)- const { duplicate, archiveWorkflow } = useActions(workflowLogic)+ const { duplicate, archiveWorkflow, setWorkflowValue } = useActions(workflowLogic)const { searchParams } = useValues(router)const editTemplateId = searchParams.editTemplateId as string | undefinedconst { showSaveAsTemplateModal } = useActions(workflowTemplateLogic({ ...props, editTemplateId }))const { suggestionsAvailable } = useValues(workflowSuggestionsAvailabilityLogic)+ const canEdit =+ workflow.status !== 'archived' &&+ (!workflowUserAccessLevel ||+ accessLevelSatisfied(+ AccessControlResourceType.Workflow,+ workflowUserAccessLevel,+ AccessControlLevel.Editor+ ))return (<ScenePanel>+ <ScenePanelInfoSection>+ <SceneTags+ onSave={(tags) => setWorkflowValue('tags', tags)}+ canEdit={canEdit}+ tags={workflow.tags ?? []}+ dataAttrKey="workflow"+ />+ </ScenePanelInfoSection>+ <ScenePanelDivider />{suggestionsAvailable && (<><ScenePanelActionsSection>diff --git a/products/workflows/frontend/Workflows/WorkflowTagsCell.tsx b/products/workflows/frontend/Workflows/WorkflowTagsCell.tsxnew file mode 100644index 000000000000..5bb23ef095fc--- /dev/null+++ b/products/workflows/frontend/Workflows/WorkflowTagsCell.tsx@@ -0,0 +1,66 @@+import { useState } from 'react'++import { IconPencil, IconPlus } from '@posthog/icons'++import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'+import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'++interface WorkflowTagsCellProps {+ tags: string[]+ tagsAvailable: string[]+ canEdit: boolean+ onChange: (tags: string[]) => void+ onTagClick: (tag: string) => void+}++export function WorkflowTagsCell({+ tags,+ tagsAvailable,+ canEdit,+ onChange,+ onTagClick,+}: WorkflowTagsCellProps): JSX.Element | null {+ const [editing, setEditing] = useState(false)++ if (editing) {+ return (+ <LemonInputSelect+ mode="multiple"+ allowCustomValues+ value={tags}+ options={tagsAvailable.map((tag) => ({ key: tag, label: tag }))}+ onChange={onChange}+ onBlur={() => setEditing(false)}+ autoFocus+ size="small"+ className="min-w-48"+ placeholder='try "growth"'+ popoverClassName="click-outside-block"+ data-attr="workflow-list-tags-input"+ />+ )+ }++ if (!tags.length && !canEdit) {+ return null+ }++ return (+ <div className="flex items-center gap-1" data-attr="workflow-list-tags">+ {tags.length > 0 && <ObjectTags tags={tags} staticOnly onTagClick={onTagClick} maxVisibleTags={3} />}+ {canEdit && (+ // Shown on row hover so a long list stays calm. Keyboard focus shows it too.+ <LemonButton+ size="xsmall"+ icon={tags.length ? <IconPencil /> : <IconPlus />}+ tooltip={tags.length ? 'Edit tags' : 'Add tags'}+ aria-label={tags.length ? 'Edit tags' : 'Add tags'}+ onClick={() => setEditing(true)}+ className="opacity-0 group-hover:opacity-100 focus-visible:opacity-100"+ data-attr="workflow-list-edit-tags"+ />+ )}+ </div>+ )+}diff --git a/products/workflows/frontend/Workflows/WorkflowsTable.tsx b/products/workflows/frontend/Workflows/WorkflowsTable.tsxindex c5f2c62563be..3da776396121 100644--- a/products/workflows/frontend/Workflows/WorkflowsTable.tsx+++ b/products/workflows/frontend/Workflows/WorkflowsTable.tsx@@ -15,6 +15,7 @@ import {import { AccessControlAction } from 'lib/components/AccessControlAction'import { AppMetricsSparkline } from 'lib/components/AppMetrics/AppMetricsSparkline'import { MemberSelect } from 'lib/components/MemberSelect'+import { TagSelect } from 'lib/components/TagSelect'import { FEATURE_FLAGS } from 'lib/constants'import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'import { LemonButton } from 'lib/lemon-ui/LemonButton'@@ -24,6 +25,7 @@ import { updatedAtColumn } from 'lib/lemon-ui/LemonTable/columnUtils'import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { accessLevelSatisfied } from 'lib/utils/accessControlUtils'import { capitalizeFirstLetter } from 'lib/utils/strings'import { urls } from 'scenes/urls'@@ -45,6 +47,7 @@ import {workflowsLogic,} from './workflowsLogic'import { WorkflowStepMatches } from './WorkflowStepMatches'+import { WorkflowTagsCell } from './WorkflowTagsCell'import { hasMessagingAction } from './workflowTypeFilters'const STATUS_CONFIG: Record<string, { label: string; type: 'success' | 'default' | 'muted' }> = {@@ -129,6 +132,8 @@ export function WorkflowsTable(): JSX.Element {selectedArchivedWorkflowIds,allArchivedSelected,selectedArchivedCount,+ localWorkflowTags,+ tags: allTags,} = useValues(logic)// Only an unfiltered Automations tab is truly empty. With a search or filter, the plain message fits.const showAutomationEmptyState =@@ -136,7 +141,8 @@ export function WorkflowsTable(): JSX.Element {!filters.search &&filters.createdBy === null &&filters.status === 'all' &&- filters.triggerType === 'all'+ filters.triggerType === 'all' &&+ filters.tags.length === 0const {loadWorkflows,toggleWorkflowStatus,@@ -150,6 +156,9 @@ export function WorkflowsTable(): JSX.Element {toggleArchivedWorkflowSelection,selectAllArchivedWorkflows,clearArchivedWorkflowSelection,+ updateWorkflowTags,+ setTagsFilter,+ loadTagsIfNeeded,} = useActions(logic)useOnMountEffect(() => {@@ -159,6 +168,7 @@ export function WorkflowsTable(): JSX.Element {id: 'new',})newWorkflowLogic?.unmount()+ loadTagsIfNeeded()// Since logic isn't getting unmounted when navigating away from this scene, we need to reload workflows// when the component re-mounts@@ -167,6 +177,12 @@ export function WorkflowsTable(): JSX.Element {const isArchived = filters.status === 'archived'+ const filterByTag = (tag: string): void => {+ if (!filters.tags.includes(tag)) {+ setTagsFilter([...filters.tags, tag], 'tag_click')+ }+ }+const columns: LemonTableColumns<HogFlow> = [...(isArchived? [@@ -198,7 +214,7 @@ export function WorkflowsTable(): JSX.Element {render: (_, item) => {const stepMatches = findMatchingWorkflowSteps(item, filters.search)return (- <>+ <div className="min-w-48">{item.status === 'archived' ? (<Tooltip title="Restore this workflow to make changes"><span className="font-semibold text-sm text-muted">{item.name}</span>@@ -237,7 +253,31 @@ export function WorkflowsTable(): JSX.Element {/>)}{stepMatches.length > 0 && <WorkflowStepMatches workflow={item} matches={stepMatches} />}- </>+ </div>+ )+ },+ },+ {+ title: 'Tags',+ key: 'tags',+ render: (_, item) => {+ const tags = localWorkflowTags[item.id] ?? item.tags ?? []+ const canEdit =+ item.status !== 'archived' &&+ (!item.user_access_level ||+ accessLevelSatisfied(+ AccessControlResourceType.Workflow,+ item.user_access_level,+ AccessControlLevel.Editor+ ))+ return (+ <WorkflowTagsCell+ tags={tags}+ tagsAvailable={allTags.filter((tag) => !tags.includes(tag))}+ canEdit={canEdit}+ onChange={(newTags) => updateWorkflowTags(item, newTags)}+ onTagClick={filterByTag}+ />)},},@@ -466,6 +506,16 @@ export function WorkflowsTable(): JSX.Element {value={filters.createdBy}onChange={(user) => setFilters({ createdBy: user?.uuid || null })}/>+ <span className="ml-1">+ <b>Tags</b>+ </span>+ <TagSelect+ size="small"+ defaultLabel="Any tags"+ value={filters.tags}+ onChange={(tags) => setTagsFilter(tags, 'filter')}+ listDataAttr="workflows-tags-filter-list"+ /></div></div>@@ -484,6 +534,7 @@ export function WorkflowsTable(): JSX.Element {dataSource={workflows.results}loading={workflowsLoading}rowKey="id"+ rowClassName="group"columns={columns}defaultSorting={{ columnKey: 'updatedAt', order: 1 }}pagination={pagination}diff --git a/products/workflows/frontend/Workflows/hogflows/types.ts b/products/workflows/frontend/Workflows/hogflows/types.tsindex c6dd1b4864f5..2e64d5fe89e4 100644--- a/products/workflows/frontend/Workflows/hogflows/types.ts+++ b/products/workflows/frontend/Workflows/hogflows/types.ts@@ -112,6 +112,7 @@ export interface HogFlow extends z.infer<typeof HogFlowSchema> {// Suggested changes waiting for a person. Only the list endpoint counts it.pending_suggestions?: number | nullsuggestions_enabled?: boolean | null+ tags?: string[]}export interface HogFlowEdge extends z.infer<typeof HogFlowEdgeSchema> {}diff --git a/products/workflows/frontend/Workflows/misc/workflowActivityDescriber.tsx b/products/workflows/frontend/Workflows/misc/workflowActivityDescriber.tsxindex 2d5dafa8b602..b52de2a6448a 100644--- a/products/workflows/frontend/Workflows/misc/workflowActivityDescriber.tsx+++ b/products/workflows/frontend/Workflows/misc/workflowActivityDescriber.tsx@@ -168,6 +168,18 @@ function describeWorkflowField(change: ActivityChange): JSX.Element[] {return describeWorkflowItems(change, 'variable')case 'schedule':return [describeScheduleChange(change)]+ case 'tag':+ return [+ change.action === 'created' ? (+ <>+ added the tag <strong>{String(change.after)}</strong>+ </>+ ) : (+ <>+ removed the tag <strong>{String(change.before)}</strong>+ </>+ ),+ ]default:return [<>updated {change.field}</>]}diff --git a/products/workflows/frontend/Workflows/workflowLogic.ts b/products/workflows/frontend/Workflows/workflowLogic.tsindex 3b1a4f2818f2..a214c9bf928c 100644--- a/products/workflows/frontend/Workflows/workflowLogic.ts+++ b/products/workflows/frontend/Workflows/workflowLogic.ts@@ -231,7 +231,7 @@ const WORKFLOW_CONTENT_FIELDS = [// The fields the editor writes through the form. Edits that land while a save is in flight are// re-applied from these after the response rebaselines the form, so the round-trip can't drop them.-const WORKFLOW_EDITABLE_FIELDS = [...WORKFLOW_CONTENT_FIELDS, 'name', 'description'] as const+const WORKFLOW_EDITABLE_FIELDS = [...WORKFLOW_CONTENT_FIELDS, 'name', 'description', 'tags'] as constfunction pickWorkflowEdits(workflow: HogFlow): Partial<HogFlow> {const result: Record<string, unknown> = {}diff --git a/products/workflows/frontend/Workflows/workflowsLogic.test.ts b/products/workflows/frontend/Workflows/workflowsLogic.test.tsindex 1955c170a27b..5d9bb2f6ab34 100644--- a/products/workflows/frontend/Workflows/workflowsLogic.test.ts+++ b/products/workflows/frontend/Workflows/workflowsLogic.test.ts@@ -1,8 +1,10 @@import { router } from 'kea-router'+import { expectLogic } from 'kea-test-utils'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+import type { HogFlow } from './hogflows/types'import { workflowsLogic } from './workflowsLogic'describe('workflowsLogic', () => {@@ -23,7 +25,9 @@ describe('workflowsLogic', () => {afterEach(() => logic.unmount())it.each(['/workflows', '/workflows/workflows'])('fills the filters from the query params on %s', (path) => {- router.actions.push(`${path}?created_by=user-uuid&status=active&trigger_type=event&type=messaging`)+ router.actions.push(+ `${path}?created_by=user-uuid&status=active&trigger_type=event&type=messaging&tags=${encodeURIComponent('["growth","billing"]')}`+ )expect(logic.values.filters).toEqual({search: '',@@ -31,7 +35,60 @@ describe('workflowsLogic', () => {status: 'active',type: 'messaging',triggerType: 'event',+ tags: ['growth', 'billing'],page: 1,})})++ it('saves a row tag edit with only the tags, and shows the name the server stored', async () => {+ const workflow = { id: 'flow-1', name: 'Churn win-back', tags: [] } as unknown as HogFlow+ const bodies: unknown[] = []+ useMocks({+ patch: {+ '/api/projects/:team_id/hog_flows/:id/': async ({ request }) => {+ bodies.push(await request.json())+ return [200, { ...workflow, tags: ['growth'] }]+ },+ },+ })++ await expectLogic(logic, () => logic.actions.updateWorkflowTags(workflow, ['Growth']))+ .toFinishAllListeners()+ .toMatchValues({ localWorkflowTags: { 'flow-1': ['growth'] } })++ expect(bodies).toEqual([{ tags: ['Growth'] }])+ })++ it("sends a row's next tag save only after the one before it lands", async () => {+ const workflow = { id: 'flow-1', name: 'Churn win-back', tags: [] } as unknown as HogFlow+ const bodies: string[][] = []+ let markFirstInFlight = (): void => {}+ let releaseFirst = (): void => {}+ const firstInFlight = new Promise<void>((resolve) => (markFirstInFlight = resolve))+ const firstReleased = new Promise<void>((resolve) => (releaseFirst = resolve))+ let started = 0+ useMocks({+ patch: {+ '/api/projects/:team_id/hog_flows/:id/': async ({ request }) => {+ const { tags } = (await request.json()) as { tags: string[] }+ started += 1+ if (started === 1) {+ markFirstInFlight()+ await firstReleased+ }+ bodies.push(tags)+ return [200, { ...workflow, tags }]+ },+ },+ })++ logic.actions.updateWorkflowTags(workflow, ['growth'])+ logic.actions.updateWorkflowTags(workflow, ['growth', 'billing'])+ await firstInFlight+ releaseFirst()+ await expectLogic(logic).toFinishAllListeners()++ expect(bodies).toEqual([['growth'], ['growth', 'billing']])+ expect(logic.values.localWorkflowTags).toEqual({ 'flow-1': ['growth', 'billing'] })+ })})diff --git a/products/workflows/frontend/Workflows/workflowsLogic.ts b/products/workflows/frontend/Workflows/workflowsLogic.tsindex 7dfa787fedd1..1d2ecd7ca764 100644--- a/products/workflows/frontend/Workflows/workflowsLogic.ts+++ b/products/workflows/frontend/Workflows/workflowsLogic.ts@@ -1,16 +1,18 @@-import { MakeLogicType, actions, kea, key, listeners, path, reducers, selectors } from 'kea'+import { MakeLogicType, actions, connect, kea, key, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'import { actionToUrl, router, urlToAction } from 'kea-router'import posthog from 'posthog-js'import { LemonDialog, PaginationManual, lemonToast } from '@posthog/lemon-ui'-import api, { CountedPaginatedResponse, HogFlowListType } from 'lib/api'+import api, { ApiConfig, CountedPaginatedResponse, HogFlowListType } from 'lib/api'import { objectsEqual } from 'lib/utils/objects'import { urls } from 'scenes/urls'import { deleteFromTree } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'+import { tagsModel } from '~/models/tagsModel'+import { hogFlowsPartialUpdate } from '../generated/api'import type { HogFlow } from './hogflows/types'import { prepareWorkflowDuplicate } from './workflowDuplication'@@ -52,6 +54,7 @@ export interface WorkflowsFilters {status: WorkflowStatusFiltertype: WorkflowTypeFiltertriggerType: WorkflowTriggerTypeFilter+ tags: string[]page: number}@@ -61,6 +64,7 @@ const DEFAULT_FILTERS: WorkflowsFilters = {status: 'all',type: 'all',triggerType: 'all',+ tags: [],page: 1,}@@ -72,6 +76,7 @@ interface WorkflowsListParams {created_by?: stringtype?: HogFlowListType[]trigger?: string+ tags?: stringsuggestions_first?: booleanlimit: numberoffset: number@@ -79,9 +84,11 @@ interface WorkflowsListParams {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface workflowsLogicValues {+ tags: string[] // tagsModelallArchivedSelected: booleanfilters: WorkflowsFiltershasLoadedWorkflows: boolean+ localWorkflowTags: Record<string, string[]>pagination: PaginationManualparamsFromFilters: WorkflowsListParamsselectedArchivedCount: number@@ -92,6 +99,12 @@ export interface workflowsLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface workflowsLogicActions {+ loadTags: () => {+ value: true+ } // tagsModel+ loadTagsIfNeeded: () => {+ value: true+ } // tagsModelarchiveWorkflow: (workflow: HogFlow) => {workflow: HogFlow}@@ -210,6 +223,20 @@ export interface workflowsLogicActions {filters: Partial<WorkflowsFilters>replace: boolean | undefined}+ setSavedWorkflowTags: (+ id: string,+ tags: string[]+ ) => {+ id: string+ tags: string[]+ }+ setTagsFilter: (+ tags: string[],+ source: 'filter' | 'tag_click'+ ) => {+ source: 'filter' | 'tag_click'+ tags: string[]+ }toggleArchivedWorkflowSelection: (id: string) => {id: string}@@ -234,6 +261,13 @@ export interface workflowsLogicActions {workflow: HogFlow}}+ updateWorkflowTags: (+ workflow: HogFlow,+ tags: string[]+ ) => {+ tags: string[]+ workflow: HogFlow+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -257,6 +291,10 @@ export type workflowsLogicType = MakeLogicType<export const workflowsLogic = kea<workflowsLogicType>([key(() => 'workflowsLogic'),path(['products', 'workflows', 'frontend', 'workflowsLogic']),+ connect(() => ({+ values: [tagsModel, ['tags']],+ actions: [tagsModel, ['loadTags', 'loadTagsIfNeeded']],+ })),actions({toggleWorkflowStatus: (workflow: HogFlow) => ({ workflow }),duplicateWorkflow: (workflow: HogFlow) => ({ workflow }),@@ -270,6 +308,9 @@ export const workflowsLogic = kea<workflowsLogicType>([toggleArchivedWorkflowSelection: (id: string) => ({ id }),selectAllArchivedWorkflows: (ids: string[]) => ({ ids }),clearArchivedWorkflowSelection: true,+ updateWorkflowTags: (workflow: HogFlow, tags: string[]) => ({ workflow, tags }),+ setSavedWorkflowTags: (id: string, tags: string[]) => ({ id, tags }),+ setTagsFilter: (tags: string[], source: 'filter' | 'tag_click') => ({ tags, source }),}),reducers({filters: [@@ -309,6 +350,15 @@ export const workflowsLogic = kea<workflowsLogicType>([loadWorkflowsSuccess: () => true,},],+ // Tags edited in a row show at once, before the save returns. A reload brings the saved tags.+ localWorkflowTags: [+ {} as Record<string, string[]>,+ {+ updateWorkflowTags: (state, { workflow, tags }) => ({ ...state, [workflow.id]: tags }),+ setSavedWorkflowTags: (state, { id, tags }) => ({ ...state, [id]: tags }),+ loadWorkflowsSuccess: () => ({}),+ },+ ],}),loaders(({ actions, values }) => ({workflows: [@@ -433,6 +483,7 @@ export const workflowsLogic = kea<workflowsLogicType>([type: filters.type !== 'all' ? [filters.type] : WORKFLOWS_PAGE_TYPES,// The API filters triggers by JSON containment, so the type goes over as a JSON object.trigger: filters.triggerType !== 'all' ? JSON.stringify({ type: filters.triggerType }) : undefined,+ tags: filters.tags.length ? JSON.stringify(filters.tags) : undefined,// Only this page sorts a waiting suggestion above recency; every other reader of the// list keeps recency, so one stale workflow cannot push fresh ones off their first page.suggestions_first: true,@@ -460,7 +511,7 @@ export const workflowsLogic = kea<workflowsLogicType>([(selectedIds: Set<string>): number => selectedIds.size,],}),- listeners(({ actions, values }) => ({+ listeners(({ actions, values, cache }) => ({selectTypeTab: ({ type }) => {actions.setFilters({ type })// pinned: analytics event name - renaming breaks dashboards@@ -471,6 +522,30 @@ export const workflowsLogic = kea<workflowsLogicType>([await breakpoint(300)actions.loadWorkflows()},+ setTagsFilter: ({ tags, source }) => {+ actions.setFilters({ tags })+ posthog.capture('workflows tag filter changed', { tags_count: tags.length, source })+ },+ updateWorkflowTags: async ({ workflow, tags }) => {+ // Every pick in the open picker saves the whole list, so chain a workflow's saves: an+ // earlier list landing last would drop the tags picked after it.+ const pending: Record<string, Promise<void>> = cache.tagSaves ?? (cache.tagSaves = {})+ const save = (pending[workflow.id] ?? Promise.resolve()).then(async () => {+ // Only the tags go over the wire, so a row edit never touches the workflow's content.+ const saved = await hogFlowsPartialUpdate(String(ApiConfig.getCurrentTeamId()), workflow.id, { tags })+ posthog.capture('workflow tags updated', { source: 'workflows_list', tags_count: tags.length })+ // The server lowercases and trims each name, so show what it stored, not what was typed.+ actions.setSavedWorkflowTags(workflow.id, saved.tags ? [...saved.tags] : tags)+ actions.loadTags()+ })+ pending[workflow.id] = save.catch(() => {})+ try {+ await save+ } catch (error: any) {+ lemonToast.error(`Failed to save tags: ${error?.detail || error?.message || 'Unknown error'}`)+ actions.loadWorkflows()+ }+ },loadWorkflowsSuccess: ({ workflows }) => {// A page past the end (stale link, or rows deleted since) would otherwise leave the user on a// blank table with no pagination control to click back with, so land them on the last real page.@@ -521,7 +596,7 @@ export const workflowsLogic = kea<workflowsLogicType>([const buildURL = (): [string, Record<string, any>, Record<string, any>, { replace: boolean }] => {const searchParams = { ...router.values.searchParams }- const setOrDelete = (key: string, value: string | number | null | undefined): void => {+ const setOrDelete = (key: string, value: string | number | string[] | null | undefined): void => {if (value) {searchParams[key] = value} else {@@ -534,6 +609,7 @@ export const workflowsLogic = kea<workflowsLogicType>([setOrDelete('status', values.filters.status !== 'all' ? values.filters.status : null)setOrDelete('type', values.filters.type !== 'all' ? values.filters.type : null)setOrDelete('trigger_type', values.filters.triggerType !== 'all' ? values.filters.triggerType : null)+ setOrDelete('tags', values.filters.tags.length ? values.filters.tags : null)setOrDelete('page', values.filters.page > 1 ? values.filters.page : null)return [router.values.location.pathname, searchParams, router.values.hashParams, { replace: true }]@@ -548,12 +624,15 @@ export const workflowsLogic = kea<workflowsLogicType>([const status = searchParams['status']const type = searchParams['type']const triggerType = searchParams['trigger_type']+ const tags = searchParams['tags']const parsed: WorkflowsFilters = {search: searchParams['search'] ? String(searchParams['search']) : '',createdBy: searchParams['created_by'] ? String(searchParams['created_by']) : null,status: WORKFLOW_STATUS_FILTERS.includes(status) ? status : 'all',type: WORKFLOW_TYPE_FILTERS.includes(type) ? type : 'all',triggerType: WORKFLOW_TRIGGER_TYPE_FILTERS.includes(triggerType) ? triggerType : 'all',+ // kea-router parses a JSON array in the URL back into an array.+ tags: Array.isArray(tags) ? tags.map(String) : typeof tags === 'string' && tags ? [tags] : [],// Anything unparseable, zero, or negative falls back to page 1 rather than reaching// the offset maths as NaN or a negative number.page: Math.max(1, parseInt(String(searchParams['page'])) || 1),diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.tsindex 14e30784039a..780b6c4d0f52 100644--- a/products/workflows/frontend/generated/api.schemas.ts+++ b/products/workflows/frontend/generated/api.schemas.ts@@ -413,6 +413,8 @@ export interface HogFlowMinimalApi {/** @nullable */readonly name: string | nullreadonly description: string+ /** Tags for organizing workflows, for example by team or use case. Sorted by name. */+ readonly tags: readonly string[]readonly version: numberreadonly status: HogFlowStateEnumApireadonly origin_product: HogFlowOriginProductEnumApi | null@@ -668,6 +670,12 @@ export interface HogFlowApi {name?: string | null/** Optional description. */description?: string+ /**+ * Tags for organizing workflows, for example by team or use case. Tags are shared with the rest of the project. Omit to keep the current tags, send an empty list to remove them all.+ * @maxItems 10+ * @items.maxLength 255+ */+ tags?: string[]readonly version: number/** draft (no execution), active (live), archived (disabled).*@@ -770,6 +778,12 @@ export interface HogFlowUpdateApi {name?: string | null/** Optional description. */description?: string+ /**+ * Tags for organizing workflows, for example by team or use case. Tags are shared with the rest of the project. Omit to keep the current tags, send an empty list to remove them all.+ * @maxItems 10+ * @items.maxLength 255+ */+ tags?: string[]readonly version: number/** draft (no execution), active (live), archived (disabled).*@@ -872,6 +886,12 @@ export interface PatchedHogFlowUpdateApi {name?: string | null/** Optional description. */description?: string+ /**+ * Tags for organizing workflows, for example by team or use case. Tags are shared with the rest of the project. Omit to keep the current tags, send an empty list to remove them all.+ * @maxItems 10+ * @items.maxLength 255+ */+ tags?: string[]readonly version?: number/** draft (no execution), active (live), archived (disabled).*@@ -2757,7 +2777,7 @@ export type HogFlowsListParams = {*/origin_product?: HogFlowsListOriginProduct/**- * Case-insensitive search. Matches workflow name and description first; only when nothing matches those, it matches step names and the subject line, preheader and body text of email steps, in both the live workflow and its pending draft.+ * Case-insensitive search. Matches workflow name, description and tag names first; only when nothing matches those, it matches step names and the subject line, preheader and body text of email steps, in both the live workflow and its pending draft.*/search?: string/**@@ -2766,6 +2786,10 @@ export type HogFlowsListParams = {* * `archived` - Archived*/status?: HogFlowsListStatus+ /**+ * JSON-encoded list of tag names, e.g. ["growth", "onboarding"]. Returns workflows that carry at least one of these tags.+ */+ tags?: string/*** Filter by trigger config as a JSON object. Returns workflows whose trigger contains the given object, e.g. {"type": "event"}.*/diff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.tsindex 0ecf5ce2e6d2..4f26b39f0f05 100644--- a/products/workflows/frontend/generated/api.zod.ts+++ b/products/workflows/frontend/generated/api.zod.ts@@ -508,6 +508,10 @@ export const HogFlowTemplatesPartialUpdateBody = /* @__PURE__ */ zodexport const hogFlowsCreateBodyNameMax = 400export const hogFlowsCreateBodyDescriptionDefault = ``+export const hogFlowsCreateBodyTagsItemMax = 255++export const hogFlowsCreateBodyTagsMax = 10+export const hogFlowsCreateBodyTriggerMaskingOneTtlMin = 60export const hogFlowsCreateBodyTriggerMaskingOneTtlMax = 94608000@@ -530,6 +534,13 @@ export const HogFlowsCreateBody = /* @__PURE__ */ zod.object({name: zod.string().max(hogFlowsCreateBodyNameMax).nullish().describe('Workflow name.'),description: zod.string().default(hogFlowsCreateBodyDescriptionDefault).describe('Optional description.'),+ tags: zod+ .array(zod.string().max(hogFlowsCreateBodyTagsItemMax))+ .max(hogFlowsCreateBodyTagsMax)+ .optional()+ .describe(+ 'Tags for organizing workflows, for example by team or use case. Tags are shared with the rest of the project. Omit to keep the current tags, send an empty list to remove them all.'+ ),status: zod.enum(['draft', 'active', 'archived']).describe('\* `draft` - Draft\n\* `active` - Active\n\* `archived` - Archived')@@ -917,6 +928,10 @@ export const HogFlowsCreateBody = /* @__PURE__ */ zodexport const hogFlowsUpdateBodyNameMax = 400export const hogFlowsUpdateBodyDescriptionDefault = ``+export const hogFlowsUpdateBodyTagsItemMax = 255++export const hogFlowsUpdateBodyTagsMax = 10+export const hogFlowsUpdateBodyTriggerMaskingOneTtlMin = 60export const hogFlowsUpdateBodyTriggerMaskingOneTtlMax = 94608000@@ -939,6 +954,13 @@ export const HogFlowsUpdateBody = /* @__PURE__ */ zod.object({name: zod.string().max(hogFlowsUpdateBodyNameMax).nullish().describe('Workflow name.'),description: zod.string().default(hogFlowsUpdateBodyDescriptionDefault).describe('Optional description.'),+ tags: zod+ .array(zod.string().max(hogFlowsUpdateBodyTagsItemMax))+ .max(hogFlowsUpdateBodyTagsMax)+ .optional()+ .describe(+ 'Tags for organizing workflows, for example by team or use case. Tags are shared with the rest of the project. Omit to keep the current tags, send an empty list to remove them all.'+ ),status: zod.enum(['draft', 'active', 'archived']).describe('\* `draft` - Draft\n\* `active` - Active\n\* `archived` - Archived')@@ -1313,6 +1335,10 @@ export const HogFlowsUpdateBody = /* @__PURE__ */ zodexport const hogFlowsPartialUpdateBodyNameMax = 400export const hogFlowsPartialUpdateBodyDescriptionDefault = ``+export const hogFlowsPartialUpdateBodyTagsItemMax = 255++export const hogFlowsPartialUpdateBodyTagsMax = 10+export const hogFlowsPartialUpdateBodyTriggerMaskingOneTtlMin = 60export const hogFlowsPartialUpdateBodyTriggerMaskingOneTtlMax = 94608000@@ -1340,6 +1366,13 @@ export const HogFlowsPartialUpdateBody = /* @__PURE__ */ zod.string().default(hogFlowsPartialUpdateBodyDescriptionDefault).describe('Optional description.'),+ tags: zod+ .array(zod.string().max(hogFlowsPartialUpdateBodyTagsItemMax))+ .max(hogFlowsPartialUpdateBodyTagsMax)+ .optional()+ .describe(+ 'Tags for organizing workflows, for example by team or use case. Tags are shared with the rest of the project. Omit to keep the current tags, send an empty list to remove them all.'+ ),status: zod.enum(['draft', 'active', 'archived']).describe('\* `draft` - Draft\n\* `active` - Active\n\* `archived` - Archived')@@ -1896,6 +1929,10 @@ export const HogFlowsGraphPartialUpdateBody = /* @__PURE__ */ zod.object({export const hogFlowsInvocationsCreateBodyConfigurationOneNameMax = 400export const hogFlowsInvocationsCreateBodyConfigurationOneDescriptionDefault = ``+export const hogFlowsInvocationsCreateBodyConfigurationOneTagsItemMax = 255++export const hogFlowsInvocationsCreateBodyConfigurationOneTagsMax = 10+export const hogFlowsInvocationsCreateBodyConfigurationOneCreatedByOneDistinctIdMax = 200export const hogFlowsInvocationsCreateBodyConfigurationOneCreatedByOneFirstNameMax = 150@@ -1941,6 +1978,13 @@ export const HogFlowsInvocationsCreateBody = /* @__PURE__ */ zod.object({.string().default(hogFlowsInvocationsCreateBodyConfigurationOneDescriptionDefault).describe('Optional description.'),+ tags: zod+ .array(zod.string().max(hogFlowsInvocationsCreateBodyConfigurationOneTagsItemMax))+ .max(hogFlowsInvocationsCreateBodyConfigurationOneTagsMax)+ .optional()+ .describe(+ 'Tags for organizing workflows, for example by team or use case. Tags are shared with the rest of the project. Omit to keep the current tags, send an empty list to remove them all.'+ ),version: zod.number(),status: zod.enum(['draft', 'active', 'archived'])@@ -2801,6 +2845,10 @@ export const HogFlowsSchedulesPartialUpdateBody = /* @__PURE__ */ zod.object({export const hogFlowsBulkDeleteCreateBodyNameMax = 400export const hogFlowsBulkDeleteCreateBodyDescriptionDefault = ``+export const hogFlowsBulkDeleteCreateBodyTagsItemMax = 255++export const hogFlowsBulkDeleteCreateBodyTagsMax = 10+export const hogFlowsBulkDeleteCreateBodyTriggerMaskingOneTtlMin = 60export const hogFlowsBulkDeleteCreateBodyTriggerMaskingOneTtlMax = 94608000@@ -2828,6 +2876,13 @@ export const HogFlowsBulkDeleteCreateBody = /* @__PURE__ */ zod.string().default(hogFlowsBulkDeleteCreateBodyDescriptionDefault).describe('Optional description.'),+ tags: zod+ .array(zod.string().max(hogFlowsBulkDeleteCreateBodyTagsItemMax))+ .max(hogFlowsBulkDeleteCreateBodyTagsMax)+ .optional()+ .describe(+ 'Tags for organizing workflows, for example by team or use case. Tags are shared with the rest of the project. Omit to keep the current tags, send an empty list to remove them all.'+ ),status: zod.enum(['draft', 'active', 'archived']).describe('\* `draft` - Draft\n\* `active` - Active\n\* `archived` - Archived')diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yamlindex fd3e4763869a..d3f0dc16b093 100644--- a/products/workflows/mcp/tools.yaml+++ b/products/workflows/mcp/tools.yaml@@ -301,11 +301,12 @@ tools:title: List workflowsdescription: >List all workflows in the project. Returns workflows with their name, description, status- (draft/active/archived), version, trigger configuration, and timestamps. Pass search=<text> to find a- workflow by its name or description, or, when neither matches, by a step name or the subject, preheader or- body text of an email it sends (live or pending draft), and read its id. Most workflows-* tools take that- value as 'id'; workflows-blast-radius, workflows-run-batch and workflows-schedule-create take it as- 'workflow_id'.+ (draft/active/archived), version, trigger configuration, tags, and timestamps. Pass search=<text> to find a+ workflow by its name, description or a tag, or, when none of those match, by a step name or the subject,+ preheader or body text of an email it sends (live or pending draft), and read its id. Most workflows-* tools+ take that value as 'id'; workflows-blast-radius, workflows-run-batch and workflows-schedule-create take it+ as 'workflow_id'. Pass tags='["growth"]' (a JSON-encoded list) to return only workflows that carry at least+ one of those tags.ui_app: workflow-listworkflows-list-batch-jobs:operation: hog_flows_batch_jobs_list@@ -607,11 +608,12 @@ tools:enrich_url: '{id}/workflow'title: Update workflowdescription: >- Updates workflow fields a graph patch can't express: name, description, exit_condition, conversion,+ Updates workflow fields a graph patch can't express: name, description, tags, exit_condition, conversion,trigger_masking, variables. Graph content (actions/edges) is rejected here - a partial list would silentlydrop every step it omits - so all graph edits go through workflows-patch-graph. On an active workflow,- content fields stage a draft (published with workflows-publish) while name/description apply immediately.- Status changes go through workflows-enable / workflows-archive.+ content fields stage a draft (published with workflows-publish) while name, description and tags apply+ immediately. tags replaces the whole tag list, so send the tags to keep as well as the new ones. Status+ changes go through workflows-enable / workflows-archive.exclude_params:- status- actionsdiff --git a/rust/cyclotron-node/dist/helpers.d.ts b/rust/cyclotron-node/dist/helpers.d.tsnew file mode 100644index 000000000000..5bf697c3555d--- /dev/null+++ b/rust/cyclotron-node/dist/helpers.d.ts@@ -0,0 +1,4 @@+import { CyclotronInternalPoolConfig, CyclotronPoolConfig } from './types';+export declare function convertToInternalPoolConfig(poolConfig: CyclotronPoolConfig): CyclotronInternalPoolConfig;+export declare function serializeObject(name: string, obj: Record<string, any> | null): string | null;+export declare function deserializeObject(name: string, str: any): Record<string, any> | null;diff --git a/rust/cyclotron-node/dist/helpers.js b/rust/cyclotron-node/dist/helpers.jsnew file mode 100644index 000000000000..0e4ea8f8f379--- /dev/null+++ b/rust/cyclotron-node/dist/helpers.js@@ -0,0 +1,34 @@+"use strict";+Object.defineProperty(exports, "__esModule", { value: true });+exports.convertToInternalPoolConfig = convertToInternalPoolConfig;+exports.serializeObject = serializeObject;+exports.deserializeObject = deserializeObject;+function convertToInternalPoolConfig(poolConfig) {+ return {+ db_url: poolConfig.dbUrl,+ max_connections: poolConfig.maxConnections,+ min_connections: poolConfig.minConnections,+ acquire_timeout_seconds: poolConfig.acquireTimeoutSeconds,+ max_lifetime_seconds: poolConfig.maxLifetimeSeconds,+ idle_timeout_seconds: poolConfig.idleTimeoutSeconds,+ };+}+function serializeObject(name, obj) {+ if (obj === null) {+ return null;+ }+ else if (typeof obj === 'object' && obj !== null) {+ return JSON.stringify(obj);+ }+ throw new Error(`${name} must be either an object or null`);+}+function deserializeObject(name, str) {+ if (str === null) {+ return null;+ }+ else if (typeof str === 'string') {+ return JSON.parse(str);+ }+ throw new Error(`${name} must be either a string or null`);+}+//# sourceMappingURL=helpers.js.map\ No newline at end of filediff --git a/rust/cyclotron-node/dist/helpers.js.map b/rust/cyclotron-node/dist/helpers.js.mapnew file mode 100644index 000000000000..2edb2335523b--- /dev/null+++ b/rust/cyclotron-node/dist/helpers.js.map@@ -0,0 +1 @@+{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":";;AAEA,kEASC;AAED,0CAOC;AAED,8CAOC;AA3BD,SAAgB,2BAA2B,CAAC,UAA+B;IACvE,OAAO;QACH,MAAM,EAAE,UAAU,CAAC,KAAK;QACxB,eAAe,EAAE,UAAU,CAAC,cAAc;QAC1C,eAAe,EAAE,UAAU,CAAC,cAAc;QAC1C,uBAAuB,EAAE,UAAU,CAAC,qBAAqB;QACzD,oBAAoB,EAAE,UAAU,CAAC,kBAAkB;QACnD,oBAAoB,EAAE,UAAU,CAAC,kBAAkB;KACtD,CAAA;AACL,CAAC;AAED,SAAgB,eAAe,CAAC,IAAY,EAAE,GAA+B;IACzE,IAAI,GAAG,KAAK,IAAI,EAAE,CAAC;QACf,OAAO,IAAI,CAAA;IACf,CAAC;SAAM,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,GAAG,KAAK,IAAI,EAAE,CAAC;QACjD,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAA;IAC9B,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,GAAG,IAAI,mCAAmC,CAAC,CAAA;AAC/D,CAAC;AAED,SAAgB,iBAAiB,CAAC,IAAY,EAAE,GAAQ;IACpD,IAAI,GAAG,KAAK,IAAI,EAAE,CAAC;QACf,OAAO,IAAI,CAAA;IACf,CAAC;SAAM,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE,CAAC;QACjC,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IAC1B,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,GAAG,IAAI,kCAAkC,CAAC,CAAA;AAC9D,CAAC"}\ No newline at end of filediff --git a/rust/cyclotron-node/dist/index.d.ts b/rust/cyclotron-node/dist/index.d.tsnew file mode 100644index 000000000000..1e45f8a1a493--- /dev/null+++ b/rust/cyclotron-node/dist/index.d.ts@@ -0,0 +1,3 @@+export * from './manager';+export * from './types';+export * from './worker';diff --git a/rust/cyclotron-node/dist/index.js b/rust/cyclotron-node/dist/index.jsnew file mode 100644index 000000000000..3dd6f0d42581--- /dev/null+++ b/rust/cyclotron-node/dist/index.js@@ -0,0 +1,20 @@+"use strict";+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {+ if (k2 === undefined) k2 = k;+ var desc = Object.getOwnPropertyDescriptor(m, k);+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {+ desc = { enumerable: true, get: function() { return m[k]; } };+ }+ Object.defineProperty(o, k2, desc);+}) : (function(o, m, k, k2) {+ if (k2 === undefined) k2 = k;+ o[k2] = m[k];+}));+var __exportStar = (this && this.__exportStar) || function(m, exports) {+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);+};+Object.defineProperty(exports, "__esModule", { value: true });+__exportStar(require("./manager"), exports);+__exportStar(require("./types"), exports);+__exportStar(require("./worker"), exports);+//# sourceMappingURL=index.js.map\ No newline at end of filediff --git a/rust/cyclotron-node/dist/index.js.map b/rust/cyclotron-node/dist/index.js.mapnew file mode 100644index 000000000000..4f97acf25d57--- /dev/null+++ b/rust/cyclotron-node/dist/index.js.map@@ -0,0 +1 @@+{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,4CAAyB;AACzB,0CAAuB;AACvB,2CAAwB"}\ No newline at end of filediff --git a/rust/cyclotron-node/dist/manager.d.ts b/rust/cyclotron-node/dist/manager.d.tsnew file mode 100644index 000000000000..3153a4efbae9--- /dev/null+++ b/rust/cyclotron-node/dist/manager.d.ts@@ -0,0 +1,19 @@+import { CyclotronJobInit, CyclotronPoolConfig, CyclotronInternalPoolConfig } from './types';+type CyclotronManagerInternalConfig = {+ shards: CyclotronInternalPoolConfig[];+ shardDepthLimit?: number;+ shardDepthCheckIntervalSeconds?: number;+ shouldCompressVmState?: boolean;+ shouldUseBulkJobCopy?: boolean;+};+export type CyclotronManagerConfig = Omit<CyclotronManagerInternalConfig, 'shards'> & {+ shards: CyclotronPoolConfig[];+};+export declare class CyclotronManager {+ private config;+ constructor(config: CyclotronManagerConfig);+ connect(): Promise<void>;+ createJob(job: CyclotronJobInit): Promise<string>;+ bulkCreateJobs(jobs: CyclotronJobInit[]): Promise<string[]>;+}+export {};diff --git a/rust/cyclotron-node/dist/manager.js b/rust/cyclotron-node/dist/manager.jsnew file mode 100644index 000000000000..aafa08655656--- /dev/null+++ b/rust/cyclotron-node/dist/manager.js@@ -0,0 +1,75 @@+"use strict";+Object.defineProperty(exports, "__esModule", { value: true });+exports.CyclotronManager = void 0;+const cyclotron = require('../index.node');+const helpers_1 = require("./helpers");+class CyclotronManager {+ config;+ constructor(config) {+ this.config = config;+ this.config = config;+ }+ async connect() {+ const config = {+ shards: this.config.shards.map((shard) => (0, helpers_1.convertToInternalPoolConfig)(shard)),+ shardDepthLimit: this.config.shardDepthLimit,+ shardDepthCheckIntervalSeconds: this.config.shardDepthCheckIntervalSeconds,+ shouldCompressVmState: this.config.shouldCompressVmState,+ shouldUseBulkJobCopy: this.config.shouldUseBulkJobCopy,+ };+ return await cyclotron.maybeInitManager(JSON.stringify(config));+ }+ async createJob(job) {+ job.priority ??= 1;+ job.scheduled ??= new Date().toISOString();+ const jobInitInternal = {+ id: job.id,+ team_id: job.teamId,+ function_id: job.functionId,+ queue_name: job.queueName,+ priority: job.priority,+ scheduled: job.scheduled,+ vm_state: job.vmState ? (0, helpers_1.serializeObject)('vmState', job.vmState) : null,+ parameters: job.parameters ? (0, helpers_1.serializeObject)('parameters', job.parameters) : null,+ metadata: job.metadata ? (0, helpers_1.serializeObject)('metadata', job.metadata) : null,+ };+ const json = JSON.stringify(jobInitInternal);+ return await cyclotron.createJob(json, job.blob ? job.blob : undefined);+ }+ async bulkCreateJobs(jobs) {+ const jobInitsInternal = jobs.map((job) => {+ job.priority ??= 1;+ job.scheduled ??= new Date().toISOString();+ return {+ id: job.id,+ team_id: job.teamId,+ function_id: job.functionId,+ queue_name: job.queueName,+ priority: job.priority,+ scheduled: job.scheduled,+ vm_state: job.vmState ? (0, helpers_1.serializeObject)('vmState', job.vmState) : null,+ parameters: job.parameters ? (0, helpers_1.serializeObject)('parameters', job.parameters) : null,+ metadata: job.metadata ? (0, helpers_1.serializeObject)('metadata', job.metadata) : null,+ };+ });+ const json = JSON.stringify(jobInitsInternal);+ const totalBytes = jobs.reduce((total, job) => total + (job.blob ? job.blob.byteLength : 0), 0);+ const blobs = new Uint8Array(totalBytes);+ const blobLengths = new Uint32Array(jobs.length);+ let offset = 0;+ for (let i = 0; i < jobs.length; i++) {+ const blob = jobs[i].blob;+ if (blob) {+ blobLengths[i] = blob.byteLength;+ blobs.set(blob, offset);+ offset += blob.byteLength;+ }+ else {+ blobLengths[i] = 0;+ }+ }+ return await cyclotron.bulkCreateJobs(json, blobs, blobLengths);+ }+}+exports.CyclotronManager = CyclotronManager;+//# sourceMappingURL=manager.js.map\ No newline at end of filediff --git a/rust/cyclotron-node/dist/manager.js.map b/rust/cyclotron-node/dist/manager.js.mapnew file mode 100644index 000000000000..541eac7c587f--- /dev/null+++ b/rust/cyclotron-node/dist/manager.js.map@@ -0,0 +1 @@+{"version":3,"file":"manager.js","sourceRoot":"","sources":["../src/manager.ts"],"names":[],"mappings":";;;AACA,MAAM,SAAS,GAAG,OAAO,CAAC,eAAe,CAAC,CAAA;AAE1C,uCAAwE;AAexE,MAAa,gBAAgB;IACL;IAApB,YAAoB,MAA8B;QAA9B,WAAM,GAAN,MAAM,CAAwB;QAC9C,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;IACxB,CAAC;IAED,KAAK,CAAC,OAAO;QACT,MAAM,MAAM,GAAmC;YAC3C,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,IAAA,qCAA2B,EAAC,KAAK,CAAC,CAAC;YAC7E,eAAe,EAAE,IAAI,CAAC,MAAM,CAAC,eAAe;YAC5C,8BAA8B,EAAE,IAAI,CAAC,MAAM,CAAC,8BAA8B;YAC1E,qBAAqB,EAAE,IAAI,CAAC,MAAM,CAAC,qBAAqB;YACxD,oBAAoB,EAAE,IAAI,CAAC,MAAM,CAAC,oBAAoB;SACzD,CAAA;QACD,OAAO,MAAM,SAAS,CAAC,gBAAgB,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAA;IACnE,CAAC;IAED,KAAK,CAAC,SAAS,CAAC,GAAqB;QACjC,GAAG,CAAC,QAAQ,KA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,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;YACzB,IAAI,IAAI,EAAE,CAAC;gBACP,WAAW,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,UAAU,CAAA;gBAChC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,CAAA;gBACvB,MAAM,IAAI,IAAI,CAAC,UAAU,CAAA;YAC7B,CAAC;iBAAM,CAAC;gBACJ,WAAW,CAAC,CAAC,CAAC,GAAG,CAAC,CAAA;YACtB,CAAC;QACL,CAAC;QAED,OAAO,MAAM,SAAS,CAAC,cAAc,CAAC,IAAI,EAAE,KAAK,EAAE,WAAW,CAAC,CAAA;IACnE,CAAC;CACJ;AA7ED,4CA6EC"}\ No newline at end of filediff --git a/rust/cyclotron-node/dist/types.d.ts b/rust/cyclotron-node/dist/types.d.tsnew file mode 100644index 000000000000..10c00c35d926--- /dev/null+++ b/rust/cyclotron-node/dist/types.d.ts@@ -0,0 +1,39 @@+export type CyclotronPoolConfig = {+ dbUrl: string;+ maxConnections?: number;+ minConnections?: number;+ acquireTimeoutSeconds?: number;+ maxLifetimeSeconds?: number;+ idleTimeoutSeconds?: number;+};+export type CyclotronInternalPoolConfig = {+ db_url: string;+ max_connections?: number;+ min_connections?: number;+ acquire_timeout_seconds?: number;+ max_lifetime_seconds?: number;+ idle_timeout_seconds?: number;+};+export type CyclotronJobState = 'available' | 'running' | 'completed' | 'failed' | 'paused' | 'canceled';+export type CyclotronJob = {+ id: string;+ teamId: number;+ functionId: string | null;+ created: Date;+ lockId: string | null;+ lastHeartbeat: Date | null;+ janitorTouchCount: number;+ transitionCount: number;+ lastTransition: Date;+ queueName: string;+ state: CyclotronJobState;+ priority: number;+ scheduled: string | null;+ parentRunId: string | null;+ vmState: object | null;+ metadata: object | null;+ parameters: object | null;+ blob: Uint8Array | null;+};+export type CyclotronJobInit = Pick<CyclotronJob, 'teamId' | 'functionId' | 'queueName' | 'priority'> & Pick<Partial<CyclotronJob>, 'id' | 'scheduled' | 'parentRunId' | 'vmState' | 'parameters' | 'metadata' | 'blob'>;+export type CyclotronJobUpdate = Pick<Partial<CyclotronJob>, 'queueName' | 'priority' | 'parentRunId' | 'vmState' | 'parameters' | 'metadata' | 'blob' | 'scheduled'>;diff --git a/rust/cyclotron-node/dist/types.js b/rust/cyclotron-node/dist/types.jsnew file mode 100644index 000000000000..11e638d1ee44--- /dev/null+++ b/rust/cyclotron-node/dist/types.js@@ -0,0 +1,3 @@+"use strict";+Object.defineProperty(exports, "__esModule", { value: true });+//# sourceMappingURL=types.js.map\ No newline at end of filediff --git a/rust/cyclotron-node/dist/types.js.map b/rust/cyclotron-node/dist/types.js.mapnew file mode 100644index 000000000000..c768b7900261--- /dev/null+++ b/rust/cyclotron-node/dist/types.js.map@@ -0,0 +1 @@+{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}\ No newline at end of filediff --git a/rust/cyclotron-node/dist/worker.d.ts b/rust/cyclotron-node/dist/worker.d.tsnew file mode 100644index 000000000000..d49995ecb919--- /dev/null+++ b/rust/cyclotron-node/dist/worker.d.ts@@ -0,0 +1,34 @@+import { CyclotronJob, CyclotronJobState, CyclotronJobUpdate, CyclotronPoolConfig } from './types';+type CyclotronWorkerNodeConfig = {+ pool: CyclotronPoolConfig;+ queueName: string;+ batchMaxSize?: number;+ includeVmState?: boolean;+ pollDelayMs?: number;+ heartbeatTimeoutMs?: number;+ includeEmptyBatches?: boolean;+};+type CyclotronWorkerInternalConfig = {+ heartbeatTimeoutMs?: number;+ heartbeatWindowSeconds?: number;+ lingerTimeMs?: number;+ maxUpdatesBuffered?: number;+ maxBytesBuffered?: number;+ flushLoopIntervalMs?: number;+ shouldCompressVmState?: boolean;+};+export type CyclotronWorkerConfig = CyclotronWorkerNodeConfig & CyclotronWorkerInternalConfig;+export declare class CyclotronWorker {+ private config;+ isConsuming: boolean;+ lastHeartbeat: Date;+ private consumerLoopPromise;+ constructor(config: CyclotronWorkerConfig);+ isHealthy(): boolean;+ connect(processBatch: (jobs: CyclotronJob[]) => Promise<void>): Promise<void>;+ private startConsumerLoop;+ disconnect(): Promise<void>;+ releaseJob(jobId: string): Promise<void>;+ updateJob(id: CyclotronJob['id'], state: CyclotronJobState, updates?: CyclotronJobUpdate): void;+}+export {};diff --git a/rust/cyclotron-node/dist/worker.js b/rust/cyclotron-node/dist/worker.jsnew file mode 100644index 000000000000..ee56e3e5756c--- /dev/null+++ b/rust/cyclotron-node/dist/worker.js@@ -0,0 +1,102 @@+"use strict";+Object.defineProperty(exports, "__esModule", { value: true });+exports.CyclotronWorker = void 0;+const cyclotron = require('../index.node');+const helpers_1 = require("./helpers");+const parseJob = (job) => {+ return {+ ...job,+ vmState: (0, helpers_1.deserializeObject)('vmState', job.vmState),+ metadata: (0, helpers_1.deserializeObject)('metadata', job.metadata),+ parameters: (0, helpers_1.deserializeObject)('parameters', job.parameters),+ };+};+class CyclotronWorker {+ config;+ isConsuming = false;+ lastHeartbeat = new Date();+ consumerLoopPromise = null;+ constructor(config) {+ this.config = config;+ }+ isHealthy() {+ return (this.isConsuming &&+ new Date().getTime() - this.lastHeartbeat.getTime() < (this.config.heartbeatTimeoutMs ?? 30000));+ }+ async connect(processBatch) {+ if (this.isConsuming) {+ throw new Error('Already consuming');+ }+ const config = {+ heartbeatWindowSeconds: this.config.heartbeatWindowSeconds ?? 5,+ lingerTimeMs: this.config.lingerTimeMs ?? 500,+ maxUpdatesBuffered: this.config.maxUpdatesBuffered ?? 100,+ maxBytesBuffered: this.config.maxBytesBuffered ?? 10000000,+ flushLoopIntervalMs: this.config.flushLoopIntervalMs ?? 10,+ shouldCompressVmState: this.config.shouldCompressVmState ?? false,+ };+ await cyclotron.maybeInitWorker(JSON.stringify((0, helpers_1.convertToInternalPoolConfig)(this.config.pool)), JSON.stringify(config));+ this.isConsuming = true;+ this.consumerLoopPromise = this.startConsumerLoop(processBatch).finally(() => {+ this.isConsuming = false;+ this.consumerLoopPromise = null;+ });+ }+ async startConsumerLoop(processBatch) {+ try {+ this.isConsuming = true;+ const batchMaxSize = this.config.batchMaxSize ?? 100;+ const pollDelayMs = this.config.pollDelayMs ?? 50;+ while (this.isConsuming) {+ this.lastHeartbeat = new Date();+ const jobs = (this.config.includeVmState+ ? await cyclotron.dequeueJobsWithVmState(this.config.queueName, batchMaxSize)+ : await cyclotron.dequeueJobs(this.config.queueName, batchMaxSize)).map(parseJob);+ if (!jobs.length) {+ await new Promise((resolve) => setTimeout(resolve, pollDelayMs));+ if (this.config.includeEmptyBatches) {+ await processBatch(jobs);+ }+ continue;+ }+ await processBatch(jobs);+ }+ }+ catch (e) {+ console.error('[Cyclotron] Error in worker loop', e);+ }+ }+ async disconnect() {+ this.isConsuming = false;+ await (this.consumerLoopPromise ?? Promise.resolve());+ }+ async releaseJob(jobId) {+ return cyclotron.releaseJob(jobId);+ }+ updateJob(id, state, updates) {+ cyclotron.setState(id, state);+ if (updates?.queueName !== undefined) {+ cyclotron.setQueue(id, updates.queueName);+ }+ if (updates?.priority !== undefined) {+ cyclotron.setPriority(id, updates.priority);+ }+ if (updates?.parameters !== undefined) {+ cyclotron.setParameters(id, (0, helpers_1.serializeObject)('parameters', updates.parameters));+ }+ if (updates?.metadata !== undefined) {+ cyclotron.setMetadata(id, (0, helpers_1.serializeObject)('metadata', updates.metadata));+ }+ if (updates?.vmState !== undefined) {+ cyclotron.setVmState(id, (0, helpers_1.serializeObject)('vmState', updates.vmState));+ }+ if (updates?.blob !== undefined) {+ cyclotron.setBlob(id, updates.blob);+ }+ if (updates?.scheduled !== undefined) {+ cyclotron.setScheduledAt(id, updates.scheduled);+ }+ }+}+exports.CyclotronWorker = CyclotronWorker;+//# sourceMappingURL=worker.js.map\ No newline at end of filediff --git a/rust/cyclotron-node/dist/worker.js.map b/rust/cyclotron-node/dist/worker.js.mapnew file mode 100644index 000000000000..2287073fb09d--- /dev/null+++ b/rust/cyclotron-node/dist/worker.js.map@@ -0,0 +1 @@+{"version":3,"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U,KAAK,SAAS,EAAE,CAAC;YACpC,SAAS,CAAC,aAAa,CAAC,EAAE,EAAE,IAAA,yBAAe,EAAC,YAAY,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC,CAAA;QAClF,CAAC;QACD,IAAI,OAAO,EAAE,QAAQ,KAAK,SAAS,EAAE,CAAC;YAClC,SAAS,CAAC,WAAW,CAAC,EAAE,EAAE,IAAA,yBAAe,EAAC,UAAU,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAA;QAC5E,CAAC;QACD,IAAI,OAAO,EAAE,OAAO,KAAK,SAAS,EAAE,CAAC;YACjC,SAAS,CAAC,UAAU,CAAC,EAAE,EAAE,IAAA,yBAAe,EAAC,SAAS,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC,CAAA;QACzE,CAAC;QACD,IAAI,OAAO,EAAE,IAAI,KAAK,SAAS,EAAE,CAAC;YAC9B,SAAS,CAAC,OAAO,CAAC,EAAE,EAAE,OAAO,CAAC,IAAI,CAAC,CAAA;QACvC,CAAC;QACD,IAAI,OAAO,EAAE,SAAS,KAAK,SAAS,EAAE,CAAC;YACnC,SAAS,CAAC,cAAc,CAAC,EAAE,EAAE,OAAO,CAAC,SAAS,CAAC,CAAA;QACnD,CAAC;IACL,CAAC;CACJ;AA5GD,0CA4GC"}\ No newline at end of filediff --git a/rust/cyclotron-node/index.node b/rust/cyclotron-node/index.nodenew file mode 100755index 000000000000..ea697c78d1cdBinary files /dev/null and b/rust/cyclotron-node/index.node differdiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex afe021780e12..6f247ba1eb54 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -15187,7 +15187,7 @@}},"workflows-list": {- "description": "List all workflows in the project. Returns workflows with their name, description, status (draft/active/archived), version, trigger configuration, and timestamps. Pass search=<text> to find a workflow by its name or description, or, when neither matches, by a step name or the subject, preheader or body text of an email it sends (live or pending draft), and read its id. Most workflows-* tools take that value as 'id'; workflows-blast-radius, workflows-run-batch and workflows-schedule-create take it as 'workflow_id'.",+ "description": "List all workflows in the project. Returns workflows with their name, description, status (draft/active/archived), version, trigger configuration, tags, and timestamps. Pass search=<text> to find a workflow by its name, description or a tag, or, when none of those match, by a step name or the subject, preheader or body text of an email it sends (live or pending draft), and read its id. Most workflows-* tools take that value as 'id'; workflows-blast-radius, workflows-run-batch and workflows-schedule-create take it as 'workflow_id'. Pass tags='[\"growth\"]' (a JSON-encoded list) to return only workflows that carry at least one of those tags.","category": "Workflows","feature": "workflows","summary": "List workflows",@@ -15472,7 +15472,7 @@}},"workflows-update": {- "description": "Updates workflow fields a graph patch can't express: name, description, exit_condition, conversion, trigger_masking, variables. Graph content (actions/edges) is rejected here - a partial list would silently drop every step it omits - so all graph edits go through workflows-patch-graph. On an active workflow, content fields stage a draft (published with workflows-publish) while name/description apply immediately. Status changes go through workflows-enable / workflows-archive.",+ "description": "Updates workflow fields a graph patch can't express: name, description, tags, exit_condition, conversion, trigger_masking, variables. Graph content (actions/edges) is rejected here - a partial list would silently drop every step it omits - so all graph edits go through workflows-patch-graph. On an active workflow, content fields stage a draft (published with workflows-publish) while name, description and tags apply immediately. tags replaces the whole tag list, so send the tags to keep as well as the new ones. Status changes go through workflows-enable / workflows-archive.","category": "Workflows","feature": "workflows","summary": "Update workflow",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 71ceb7e562a8..818f95876ce3 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -15923,7 +15923,7 @@}},"workflows-list": {- "description": "List all workflows in the project. Returns workflows with their name, description, status (draft/active/archived), version, trigger configuration, and timestamps. Pass search=<text> to find a workflow by its name or description, or, when neither matches, by a step name or the subject, preheader or body text of an email it sends (live or pending draft), and read its id. Most workflows-* tools take that value as 'id'; workflows-blast-radius, workflows-run-batch and workflows-schedule-create take it as 'workflow_id'.",+ "description": "List all workflows in the project. Returns workflows with their name, description, status (draft/active/archived), version, trigger configuration, tags, and timestamps. Pass search=<text> to find a workflow by its name, description or a tag, or, when none of those match, by a step name or the subject, preheader or body text of an email it sends (live or pending draft), and read its id. Most workflows-* tools take that value as 'id'; workflows-blast-radius, workflows-run-batch and workflows-schedule-create take it as 'workflow_id'. Pass tags='[\"growth\"]' (a JSON-encoded list) to return only workflows that carry at least one of those tags.","category": "Workflows","feature": "workflows","summary": "List workflows",@@ -16236,7 +16236,7 @@}},"workflows-update": {- "description": "Updates workflow fields a graph patch can't express: name, description, exit_condition, conversion, trigger_masking, variables. Graph content (actions/edges) is rejected here - a partial list would silently drop every step it omits - so all graph edits go through workflows-patch-graph. On an active workflow, content fields stage a draft (published with workflows-publish) while name/description apply immediately. Status changes go through workflows-enable / workflows-archive.",+ "description": "Updates workflow fields a graph patch can't express: name, description, tags, exit_condition, conversion, trigger_masking, variables. Graph content (actions/edges) is rejected here - a partial list would silently drop every step it omits - so all graph edits go through workflows-patch-graph. On an active workflow, content fields stage a draft (published with workflows-publish) while name, description and tags apply immediately. tags replaces the whole tag list, so send the tags to keep as well as the new ones. Status changes go through workflows-enable / workflows-archive.","category": "Workflows","feature": "workflows","summary": "Update workflow",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex d53d8b56141c..bf97ec7c1478 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -56089,6 +56089,12 @@ export namespace Schemas {name?: string | null;/** Optional description. */description?: string;+ /**+ * Tags for organizing workflows, for example by team or use case. Tags are shared with the rest of the project. Omit to keep the current tags, send an empty list to remove them all.+ * @maxItems 10+ * @items.maxLength 255+ */+ tags?: string[];readonly version: number;/** draft (no execution), active (live), archived (disabled).*@@ -56339,6 +56345,8 @@ export namespace Schemas {/** @nullable */readonly name: string | null;readonly description: string;+ /** Tags for organizing workflows, for example by team or use case. Sorted by name. */+ readonly tags: readonly string[];readonly version: number;readonly status: HogFlowStateEnum;readonly origin_product: HogFlowOriginProductEnum | null;@@ -56694,6 +56702,12 @@ export namespace Schemas {name?: string | null;/** Optional description. */description?: string;+ /**+ * Tags for organizing workflows, for example by team or use case. Tags are shared with the rest of the project. Omit to keep the current tags, send an empty list to remove them all.+ * @maxItems 10+ * @items.maxLength 255+ */+ tags?: string[];readonly version: number;/** draft (no execution), active (live), archived (disabled).*@@ -83365,6 +83379,12 @@ export namespace Schemas {name?: string | null;/** Optional description. */description?: string;+ /**+ * Tags for organizing workflows, for example by team or use case. Tags are shared with the rest of the project. Omit to keep the current tags, send an empty list to remove them all.+ * @maxItems 10+ * @items.maxLength 255+ */+ tags?: string[];readonly version?: number;/** draft (no execution), active (live), archived (disabled).*@@ -128373,7 +128393,7 @@ export namespace Schemas {*/origin_product?: HogFlowsListOriginProduct;/**- * Case-insensitive search. Matches workflow name and description first; only when nothing matches those, it matches step names and the subject line, preheader and body text of email steps, in both the live workflow and its pending draft.+ * Case-insensitive search. Matches workflow name, description and tag names first; only when nothing matches those, it matches step names and the subject line, preheader and body text of email steps, in both the live workflow and its pending draft.*/search?: string;/**@@ -128382,6 +128402,10 @@ export namespace Schemas {* * `archived` - Archived*/status?: HogFlowsListStatus;+ /**+ * JSON-encoded list of tag names, e.g. ["growth", "onboarding"]. Returns workflows that carry at least one of these tags.+ */+ tags?: string;/*** Filter by trigger config as a JSON object. Returns workflows whose trigger contains the given object, e.g. {"type": "event"}.*/diff --git a/services/mcp/src/generated/workflows/api.ts b/services/mcp/src/generated/workflows/api.tsindex 4a38faa18f30..d49a50a76e7f 100644--- a/services/mcp/src/generated/workflows/api.ts+++ b/services/mcp/src/generated/workflows/api.ts@@ -43,12 +43,18 @@ export const HogFlowsListQueryParams = () => zod.object({.string().optional().describe(- 'Case-insensitive search. Matches workflow name and description first; only when nothing matches those, it matches step names and the subject line, preheader and body text of email steps, in both the live workflow and its pending draft.'+ 'Case-insensitive search. Matches workflow name, description and tag names first; only when nothing matches those, it matches step names and the subject line, preheader and body text of email steps, in both the live workflow and its pending draft.'),status: zod.enum(['active', 'archived', 'draft']).optional().describe('\* `draft` - Draft\n\* `active` - Active\n\* `archived` - Archived'),+ tags: zod+ .string()+ .optional()+ .describe(+ 'JSON-encoded list of tag names, e.g. [\"growth\", \"onboarding\"]. Returns workflows that carry at least one of these tags.'+ ),trigger: zod.string().optional()@@ -75,6 +81,10 @@ export const HogFlowsCreateParams = () => zod.object({export const hogFlowsCreateBodyNameMax = 400export const hogFlowsCreateBodyDescriptionDefault = ``+export const hogFlowsCreateBodyTagsItemMax = 255++export const hogFlowsCreateBodyTagsMax = 10+export const hogFlowsCreateBodyTriggerMaskingOneTtlMin = 60export const hogFlowsCreateBodyTriggerMaskingOneTtlMax = 94608000@@ -97,6 +107,13 @@ export const HogFlowsCreateBody = () => zod.object({name: zod.string().max(hogFlowsCreateBodyNameMax).nullish().describe('Workflow name.'),description: zod.string().default(hogFlowsCreateBodyDescriptionDefault).describe('Optional description.'),+ tags: zod+ .array(zod.string().max(hogFlowsCreateBodyTagsItemMax))+ .max(hogFlowsCreateBodyTagsMax)+ .optional()+ .describe(+ 'Tags for organizing workflows, for example by team or use case. Tags are shared with the rest of the project. Omit to keep the current tags, send an empty list to remove them all.'+ ),status: zod.enum(['draft', 'active', 'archived']).describe('\* `draft` - Draft\n\* `active` - Active\n\* `archived` - Archived')@@ -501,6 +518,10 @@ export const HogFlowsPartialUpdateParams = () => zod.object({export const hogFlowsPartialUpdateBodyNameMax = 400+export const hogFlowsPartialUpdateBodyTagsItemMax = 255++export const hogFlowsPartialUpdateBodyTagsMax = 10+export const hogFlowsPartialUpdateBodyTriggerMaskingOneTtlMin = 60export const hogFlowsPartialUpdateBodyTriggerMaskingOneTtlMax = 94608000@@ -516,6 +537,13 @@ export const HogFlowsPartialUpdateBody = () => zod.object({name: zod.string().max(hogFlowsPartialUpdateBodyNameMax).nullish().describe('Workflow name.'),description: zod.string().optional().describe('Optional description.'),+ tags: zod+ .array(zod.string().max(hogFlowsPartialUpdateBodyTagsItemMax))+ .max(hogFlowsPartialUpdateBodyTagsMax)+ .optional()+ .describe(+ 'Tags for organizing workflows, for example by team or use case. Tags are shared with the rest of the project. Omit to keep the current tags, send an empty list to remove them all.'+ ),trigger_masking: zod.union([zod.object({diff --git a/services/mcp/src/tools/generated/workflows.ts b/services/mcp/src/tools/generated/workflows.tsindex d1885b236176..508f5dd4becd 100644--- a/services/mcp/src/tools/generated/workflows.ts+++ b/services/mcp/src/tools/generated/workflows.ts@@ -30,6 +30,9 @@ const broadcastsCreate = (): ToolBase<ReturnType<typeof BroadcastsCreateSchema>,if (params.description !== undefined) {body['description'] = params.description}+ if (params.tags !== undefined) {+ body['tags'] = params.tags+ }if (params.status !== undefined) {body['status'] = params.status}@@ -108,6 +111,9 @@ const workflowsCreate = (): ToolBase<ReturnType<typeof WorkflowsCreateSchema>, Wif (params.description !== undefined) {body['description'] = params.description}+ if (params.tags !== undefined) {+ body['tags'] = params.tags+ }if (params.status !== undefined) {body['status'] = params.status}@@ -385,6 +391,7 @@ const workflowsList = (): ToolBase<origin_product: params.origin_product,search: params.search,status: params.status,+ tags: params.tags,trigger: params.trigger,type: params.type,updated_at: params.updated_at,@@ -846,6 +853,9 @@ const workflowsUpdate = (): ToolBase<ReturnType<typeof WorkflowsUpdateSchema>, Wif (params.description !== undefined) {body['description'] = params.description}+ if (params.tags !== undefined) {+ body['tags'] = params.tags+ }if (params.trigger_masking !== undefined) {body['trigger_masking'] = params.trigger_masking}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/broadcasts-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/broadcasts-create.jsonindex 0cf0f8fddf35..a1a871b72d7b 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/broadcasts-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/broadcasts-create.json@@ -559,6 +559,15 @@"enum": ["draft", "active", "archived"],"type": "string"},+ "tags": {+ "description": "Tags for organizing workflows, for example by team or use case. Tags are shared with the rest of the project. Omit to keep the current tags, send an empty list to remove them all.",+ "items": {+ "maxLength": 255,+ "type": "string"+ },+ "maxItems": 10,+ "type": "array"+ },"trigger_masking": {"anyOf": [{diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create.jsonindex 0cf0f8fddf35..a1a871b72d7b 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-create.json@@ -559,6 +559,15 @@"enum": ["draft", "active", "archived"],"type": "string"},+ "tags": {+ "description": "Tags for organizing workflows, for example by team or use case. Tags are shared with the rest of the project. Omit to keep the current tags, send an empty list to remove them all.",+ "items": {+ "maxLength": 255,+ "type": "string"+ },+ "maxItems": 10,+ "type": "array"+ },"trigger_masking": {"anyOf": [{diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list.jsonindex 18e5d2c3544e..71d1e66fd5c4 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list.json@@ -39,7 +39,7 @@"type": "string"},"search": {- "description": "Case-insensitive search. Matches workflow name and description first; only when nothing matches those, it matches step names and the subject line, preheader and body text of email steps, in both the live workflow and its pending draft.",+ "description": "Case-insensitive search. Matches workflow name, description and tag names first; only when nothing matches those, it matches step names and the subject line, preheader and body text of email steps, in both the live workflow and its pending draft.","type": "string"},"status": {@@ -47,6 +47,10 @@"enum": ["active", "archived", "draft"],"type": "string"},+ "tags": {+ "description": "JSON-encoded list of tag names, e.g. [\"growth\", \"onboarding\"]. Returns workflows that carry at least one of these tags.",+ "type": "string"+ },"trigger": {"description": "Filter by trigger config as a JSON object. Returns workflows whose trigger contains the given object, e.g. {\"type\": \"event\"}.","type": "string"diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update.jsonindex 3b586e05d7da..1edeb4bc77ec 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-update.json@@ -175,6 +175,15 @@],"description": "Workflow name."},+ "tags": {+ "description": "Tags for organizing workflows, for example by team or use case. Tags are shared with the rest of the project. Omit to keep the current tags, send an empty list to remove them all.",+ "items": {+ "maxLength": 255,+ "type": "string"+ },+ "maxItems": 10,+ "type": "array"+ },"trigger_masking": {"anyOf": [{