Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(workflows): search workflows by step name and email subject (#102918)

Meikel Ratze32bfbddf674
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.py
index 2fba414aec0e..bc7c11c3fbf2 100644
--- a/products/workflows/backend/api/hog_flow.py
+++ b/products/workflows/backend/api/hog_flow.py
@@ -15,6 +15,7 @@ from django.core.exceptions import ValidationError as DjangoValidationError
from django.core.signing import BadSignature, SignatureExpired, TimestampSigner
from django.db import models, transaction
from django.db.models import Q, QuerySet
+from django.db.models.expressions import RawSQL
from django.http import Http404, HttpResponse
from django.utils import timezone
from django.utils.dateparse import parse_datetime
@@ -2757,6 +2758,14 @@ class WorkflowEmailPauseStatusSerializer(serializers.Serializer):
class HogFlowMinimalSerializer(UserAccessControlSerializerMixin, serializers.ModelSerializer):
created_by = UserBasicSerializer(read_only=True)
+ draft = serializers.JSONField(
+ read_only=True,
+ help_text=(
+ "Staged content changes awaiting publish — a full snapshot of the workflow's actions, edges and "
+ "settings. Null when there's nothing staged. Test it with a use_draft test run, then promote it "
+ "with the publish endpoint or throw it away with discard_draft."
+ ),
+ )
class Meta:
model = HogFlow
@@ -2777,6 +2786,9 @@ class HogFlowMinimalSerializer(UserAccessControlSerializerMixin, serializers.Mod
"email_sending_rate_limit",
"edges",
"actions",
+ # Search matches pending draft content too, so the list carries the draft for the row to
+ # show which staged step matched.
+ "draft",
"abort_action",
"variables",
"billable_action_types",
@@ -2924,14 +2936,6 @@ class HogFlowSerializer(HogFlowMinimalSerializer):
),
)
- draft = serializers.JSONField(
- read_only=True,
- help_text=(
- "Staged content changes awaiting publish — a full snapshot of the workflow's actions, edges and "
- "settings. Null when there's nothing staged. Test it with a use_draft test run, then promote it "
- "with the publish endpoint or throw it away with discard_draft."
- ),
- )
draft_updated_at = serializers.DateTimeField(
read_only=True,
allow_null=True,
@@ -3755,6 +3759,46 @@ class HogFlowPagination(LimitOffsetPagination):
max_limit = 500
+# The email body as a person reads it: the editor's plain-text export when it exists, otherwise the HTML
+# with style and script blocks and tags removed, so CSS, script and markup never match a search term.
+# The block patterns start with a non-greedy quantifier because Postgres gives a whole regex the
+# greediness of its first quantifier. The tag pattern skips over quoted attribute values, so a '>' inside
+# one (a liquid comparison, say) does not end the tag early and leak the rest of the attribute into the
+# searchable text. Mirrored by emailBodyText in the frontend's workflowSearchMatches.ts.
+_EMAIL_BODY_TEXT_SQL = (
+ "COALESCE(NULLIF(action #>> '{config,inputs,email,value,text}', ''), "
+ "regexp_replace(regexp_replace(regexp_replace(action #>> '{config,inputs,email,value,html}', "
+ "'<style[^>]*?>.*?</style>', ' ', 'gi'), '<script[^>]*?>.*?</script>', ' ', 'gi'), "
+ "'<[^>\"'']*((\"[^\"]*\"|''[^'']*'')[^>\"'']*)*>', ' ', 'g'))"
+)
+
+# What a person remembers about a message they received or authored.
+_ACTION_SEARCH_TEXT_SQL = (
+ "action ->> 'name'",
+ "action #>> '{config,inputs,email,value,subject}'",
+ "action #>> '{config,inputs,email,value,preheader}'",
+ _EMAIL_BODY_TEXT_SQL,
+)
+
+
+def _action_content_matches(regex_pattern: str) -> RawSQL:
+ """A predicate that is true when a step in the live actions or the pending draft matches the search."""
+ table = HogFlow._meta.db_table
+ step_matches = " OR ".join(f"{text} ~* %s" for text in _ACTION_SEARCH_TEXT_SQL)
+ clauses = []
+ for source in (f'"{table}"."actions"', f'"{table}"."draft" -> \'actions\''):
+ # `actions` defaults to {} on a workflow that never got a graph, and jsonb_array_elements raises on
+ # anything but an array, so guard the source rather than let one such row fail the whole list.
+ clauses.append(
+ "EXISTS (SELECT 1 FROM jsonb_array_elements("
+ f"CASE WHEN jsonb_typeof({source}) = 'array' THEN {source} ELSE '[]'::jsonb END"
+ f") AS action WHERE {step_matches})"
+ )
+ params = [regex_pattern] * (len(clauses) * len(_ACTION_SEARCH_TEXT_SQL))
+ # nosemgrep: python.django.security.audit.raw-query.avoid-raw-sql (the search term is bound via params; only constant SQL and the table name from _meta are interpolated)
+ return RawSQL(" OR ".join(clauses), params, output_field=models.BooleanField())
+
+
class StaleWorkflowUpdateError(exceptions.APIException):
status_code = status.HTTP_409_CONFLICT
default_detail = (
@@ -3823,7 +3867,7 @@ WRITABLE_DRAFT_CONTENT_FIELDS = frozenset(DRAFT_CONTENT_FIELDS) - frozenset(HogF
OpenApiParameter(
"search",
OpenApiTypes.STR,
- description="Case-insensitive search across workflow name and description.",
+ 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.",
),
OpenApiParameter(
"created_by",
@@ -3969,17 +4013,6 @@ class HogFlowViewSet(
# otherwise repeat on one page and never appear on another.
queryset = queryset.order_by("-updated_at", "-id")
- search = self.request.GET.get("search")
- if search is not None:
- search = search.strip()
- if search:
- if len(search) > 200:
- raise exceptions.ValidationError({"search": "Search term cannot exceed 200 characters"})
- # Escape regex metacharacters, then let spaces match any run of space/dash/underscore
- # so "welcome email" also matches "welcome-email" — same approach as feature flag search.
- regex_pattern = re.escape(search).replace(r"\ ", r"[\s\-_]*")
- queryset = queryset.filter(Q(name__iregex=regex_pattern) | Q(description__iregex=regex_pattern))
-
created_by = self.request.GET.get("created_by")
if created_by:
try:
@@ -4025,6 +4058,31 @@ class HogFlowViewSet(
return queryset
+ def filter_queryset(self, queryset: QuerySet) -> QuerySet:
+ # Search runs after the filter backends so the tier decision below sees the same rows the response
+ # will: a name match that the `status` filter then drops must not stop the step search from running.
+ queryset = super().filter_queryset(queryset)
+ if self.action != "list":
+ return queryset
+
+ search = (self.request.GET.get("search") or "").strip()
+ if not search:
+ return queryset
+ if len(search) > 200:
+ raise exceptions.ValidationError({"search": "Search term cannot exceed 200 characters"})
+ # Escape regex metacharacters, then let spaces match any run of space/dash/underscore
+ # so "welcome email" also matches "welcome-email" — same approach as feature flag search.
+ regex_pattern = re.escape(search).replace(r"\ ", r"[\s\-_]*")
+
+ # Name and description are small columns, 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)
+ if queryset.filter(by_name).exists():
+ return queryset.filter(by_name)
+ return queryset.filter(Q(_action_content_matches(regex_pattern)))
+
def safely_get_object(self, queryset):
# TODO(team-workflows): Somehow implement version lookups
return super().safely_get_object(queryset)
diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.py
index 6a7b3ba20d56..273339df41e7 100644
--- a/products/workflows/backend/api/test/test_hog_flow.py
+++ b/products/workflows/backend/api/test/test_hog_flow.py
@@ -116,6 +116,15 @@ def _raw_encrypted_inputs(model_id) -> Optional[str]:
return row[0] if row else None
+def _email_step(step_id: str, name: str, **email_value: Any) -> dict[str, Any]:
+ return {
+ "id": step_id,
+ "name": name,
+ "type": "function_email",
+ "config": {"template_id": "template-email", "inputs": {"email": {"value": email_value}}},
+ }
+
+
class TestHogFlowAPI(APIBaseTest):
def setUp(self):
super().setUp()
@@ -219,22 +228,155 @@ class TestHogFlowAPI(APIBaseTest):
@parameterized.expand(
[
- ("name_match", "welcome", {"Welcome email"}),
- ("case_insensitive", "WELCOME", {"Welcome email"}),
- ("description_match", "quarterly", {"Digest"}),
- ("space_matches_separators", "password reset", {"Password reset"}),
- ("no_match", "nonexistent", set()),
+ ("name_match", "search=welcome", {"Welcome email"}),
+ ("case_insensitive", "search=WELCOME", {"Welcome email"}),
+ ("description_match", "search=quarterly", {"Digest"}),
+ ("space_matches_separators", "search=password reset", {"Password reset"}),
+ ("step_name_match", "search=monthly invoice", {"Billing"}),
+ ("email_subject_match", "search=for march", {"Billing"}),
+ ("email_preheader_match", "search=billing page", {"Billing"}),
+ ("email_body_text_match", "search=is attached", {"Billing"}),
+ ("email_markup_not_searched", "search=footer-links", set()),
+ ("email_html_only_body_match", "search=for your payment", {"Receipts"}),
+ ("email_css_not_searched", "search=111111", set()),
+ ("draft_email_subject_match", "search=beta access", {"Onboarding"}),
+ ("email_in_later_step_matches", "search=final reminder", {"Nurture"}),
+ ("liquid_subject_matches_beside_the_tag", "search=your seat is ready", {"Nurture"}),
+ ("liquid_subject_not_matched_by_rendered_wording", "search=hi jane, your seat", set()),
+ ("regex_characters_match_literally", "search=[vip] early access", {"Nurture"}),
+ ("percent_and_parentheses_match_literally", "search=50%25 off (today only)!", {"Nurture"}),
+ ("body_phrase_across_newlines", "search=upgrade now to keep", {"Nurture"}),
+ ("shared_subject_returns_every_workflow", "search=seat is confirmed", {"Alpha", "Beta"}),
+ ("html_with_liquid_in_attribute_still_matches_content", "search=thanks for your order", {"Promo"}),
+ ("html_attribute_css_not_searched", "search=color:%23ffffff", set()),
+ ("html_script_not_searched", "search=trackVisit", set()),
+ ("name_tier_hides_step_matches", "search=march", {"March campaign"}),
+ ("tier_decision_respects_status_filter", "search=march&status=draft", {"Billing"}),
+ ("tier_decision_respects_type_filter", "search=march&type=messaging", {"Billing"}),
+ ("no_match", "search=nonexistent", set()),
]
)
- def test_list_search_matches_name_and_description(self, _name, search, expected_names):
+ 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)
+ HogFlow.objects.create(team=self.team, name="March campaign", status=HogFlow.State.ACTIVE, created_by=self.user)
+ HogFlow.objects.create(
+ team=self.team,
+ name="Billing",
+ created_by=self.user,
+ actions=[
+ _email_step(
+ "email_1",
+ "Monthly invoice email",
+ subject="Your invoice for March is ready",
+ preheader="Download it from your billing page",
+ text="Your invoice is attached.",
+ html='<table class="footer-links"><tr><td>Your invoice is attached.</td></tr></table>',
+ )
+ ],
+ )
+ HogFlow.objects.create(
+ team=self.team,
+ name="Receipts",
+ created_by=self.user,
+ actions=[
+ _email_step(
+ "email_1",
+ "Receipt email",
+ subject="Your receipt",
+ html='<style type="text/css">.footer { color: #111111; }</style><p>Thanks for your <strong>payment</strong></p>',
+ )
+ ],
+ )
+ HogFlow.objects.create(
+ team=self.team,
+ name="Promo",
+ created_by=self.user,
+ actions=[
+ _email_step(
+ "email_1",
+ "Order email",
+ subject="Order update",
+ html=(
+ "<script>trackVisit()</script>"
+ '<td style="{% if person.properties.orders > 1 %}color:#ffffff{% endif %}">Thanks for your order</td>'
+ ),
+ )
+ ],
+ )
+ # A realistic multi-step graph: the searched text sits in the third email, behind non-email steps.
+ HogFlow.objects.create(
+ team=self.team,
+ name="Nurture",
+ status=HogFlow.State.ACTIVE,
+ created_by=self.user,
+ actions=[
+ {"id": "trigger_node", "name": "Trigger", "type": "trigger", "config": {"type": "event"}},
+ _email_step("email_1", "Day 1", subject="Hi {{ person.properties.first_name }}, your seat is ready"),
+ {"id": "delay_1", "name": "Wait 3 days", "type": "delay", "config": {"delay_duration": "3d"}},
+ _email_step(
+ "email_2",
+ "Day 4",
+ subject="50% off (today only)! Upgrade before Friday",
+ text="Upgrade now\n\nto keep your dashboards and alerts.",
+ ),
+ {"id": "branch_1", "name": "Has upgraded?", "type": "conditional_branch", "config": {}},
+ _email_step("email_3", "Day 10", subject="[VIP] early access: final reminder"),
+ {"id": "exit_node", "name": "Exit", "type": "exit", "config": {}},
+ ],
+ )
+ for name in ("Alpha", "Beta"):
+ HogFlow.objects.create(
+ team=self.team,
+ name=name,
+ created_by=self.user,
+ actions=[_email_step("email_1", "Confirmation", subject="Your seat is confirmed")],
+ )
+ HogFlow.objects.create(
+ team=self.team,
+ name="Onboarding",
+ status=HogFlow.State.ACTIVE,
+ created_by=self.user,
+ draft={"actions": [_email_step("email_1", "Access email", subject="Your beta access starts today")]},
+ )
- response = self.client.get(f"/api/projects/{self.team.id}/hog_flows?search={search}")
+ response = self.client.get(f"/api/projects/{self.team.id}/hog_flows?{query}")
assert response.status_code == 200, response.json()
assert {flow["name"] for flow in response.json()["results"]} == expected_names
+ def test_list_search_step_tier_counts_every_match_across_pages(self):
+ for name in ("Alpha", "Beta"):
+ HogFlow.objects.create(
+ team=self.team,
+ name=name,
+ created_by=self.user,
+ actions=[_email_step("email_1", "Confirmation", subject="Your seat is confirmed")],
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.id}/hog_flows?search=seat is confirmed&limit=1")
+ assert response.status_code == 200, response.json()
+ assert response.json()["count"] == 2
+ assert len(response.json()["results"]) == 1
+ assert response.json()["next"] is not None
+
+ def test_list_includes_the_pending_draft(self):
+ HogFlow.objects.create(
+ team=self.team,
+ name="Onboarding",
+ status=HogFlow.State.ACTIVE,
+ created_by=self.user,
+ draft={"actions": [_email_step("email_1", "Access email", subject="Your beta access starts today")]},
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.id}/hog_flows?search=beta access")
+ assert response.status_code == 200, response.json()
+ (flow,) = response.json()["results"]
+ assert (
+ flow["draft"]["actions"][0]["config"]["inputs"]["email"]["value"]["subject"]
+ == "Your beta access starts today"
+ )
+
def test_list_filter_by_created_by_uuid(self):
other_user = User.objects.create_and_join(self.organization, "[email protected]", None)
HogFlow.objects.create(team=self.team, name="Mine", created_by=self.user)
diff --git a/products/workflows/frontend/Workflows/WorkflowStepMatches.tsx b/products/workflows/frontend/Workflows/WorkflowStepMatches.tsx
new file mode 100644
index 000000000000..bcaf57865acf
--- /dev/null
+++ b/products/workflows/frontend/Workflows/WorkflowStepMatches.tsx
@@ -0,0 +1,43 @@
+import { Link } from '@posthog/lemon-ui'
+
+import { pluralize } from 'lib/utils/strings'
+import { urls } from 'scenes/urls'
+
+import { HogFlow } from './hogflows/types'
+import { WorkflowStepMatch } from './workflowSearchMatches'
+
+const MAX_VISIBLE_STEP_MATCHES = 3
+
+export function WorkflowStepMatches({
+ workflow,
+ matches,
+}: {
+ workflow: HogFlow
+ matches: WorkflowStepMatch[]
+}): JSX.Element {
+ const hiddenCount = matches.length - MAX_VISIBLE_STEP_MATCHES
+ // An archived workflow has to be restored before it can be edited, so its name is not a link either.
+ const canOpenStep = workflow.status !== 'archived'
+ return (
+ <div className="mt-1 max-w-sm text-xs text-secondary">
+ {matches.slice(0, MAX_VISIBLE_STEP_MATCHES).map((match) => {
+ const label = `${match.field}: ${match.value}`
+ return canOpenStep ? (
+ <Link
+ key={match.actionId}
+ to={`${urls.workflow(workflow.id, 'workflow')}?node=${encodeURIComponent(match.actionId)}`}
+ className="block truncate"
+ data-attr="workflow-search-step-match"
+ >
+ {label}
+ </Link>
+ ) : (
+ <span key={match.actionId} className="block truncate" data-attr="workflow-search-step-match">
+ {label}
+ </span>
+ )
+ })}
+ {hiddenCount > 0 && <span>{pluralize(hiddenCount, 'more matching step')}</span>}
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/WorkflowsTable.tsx b/products/workflows/frontend/Workflows/WorkflowsTable.tsx
index 55443d13d1df..3222ab3ef6d7 100644
--- a/products/workflows/frontend/Workflows/WorkflowsTable.tsx
+++ b/products/workflows/frontend/Workflows/WorkflowsTable.tsx
@@ -21,6 +21,7 @@ import { AccessControlLevel, AccessControlResourceType } from '~/types'
import { getHogFlowStep } from './hogflows/steps/HogFlowSteps'
import { HogFlow } from './hogflows/types'
import { workflowLogic } from './workflowLogic'
+import { findMatchingWorkflowSteps } from './workflowSearchMatches'
import {
WORKFLOW_TRIGGER_TYPE_OPTIONS,
WorkflowStatusFilter,
@@ -28,6 +29,7 @@ import {
WorkflowTypeFilter,
workflowsLogic,
} from './workflowsLogic'
+import { WorkflowStepMatches } from './WorkflowStepMatches'
const STATUS_CONFIG: Record<string, { label: string; type: 'success' | 'default' | 'muted' }> = {
active: { label: 'Active', type: 'success' },
@@ -173,17 +175,23 @@ export function WorkflowsTable(): JSX.Element {
key: 'name',
sorter: (a, b) => (a.name || '').localeCompare(b.name || ''),
render: (_, item) => {
- return item.status === 'archived' ? (
- <Tooltip title="Restore this workflow to make changes">
- <span className="font-semibold text-sm text-muted">{item.name}</span>
- </Tooltip>
- ) : (
- <LemonTableLink
- to={urls.workflow(item.id, 'workflow')}
- title={item.name}
- description={item.description}
- truncateDescription
- />
+ const stepMatches = findMatchingWorkflowSteps(item, filters.search)
+ return (
+ <>
+ {item.status === 'archived' ? (
+ <Tooltip title="Restore this workflow to make changes">
+ <span className="font-semibold text-sm text-muted">{item.name}</span>
+ </Tooltip>
+ ) : (
+ <LemonTableLink
+ to={urls.workflow(item.id, 'workflow')}
+ title={item.name}
+ description={item.description}
+ truncateDescription
+ />
+ )}
+ {stepMatches.length > 0 && <WorkflowStepMatches workflow={item} matches={stepMatches} />}
+ </>
)
},
},
diff --git a/products/workflows/frontend/Workflows/workflowSearchMatches.test.ts b/products/workflows/frontend/Workflows/workflowSearchMatches.test.ts
new file mode 100644
index 000000000000..eee5ec9bdea0
--- /dev/null
+++ b/products/workflows/frontend/Workflows/workflowSearchMatches.test.ts
@@ -0,0 +1,138 @@
+import type { HogFlow, HogFlowAction } from './hogflows/types'
+import { findMatchingWorkflowSteps } from './workflowSearchMatches'
+
+function workflowWith(overrides: Partial<HogFlow>): HogFlow {
+ return {
+ id: 'flow-1',
+ team_id: 1,
+ version: 1,
+ name: 'Billing',
+ description: '',
+ status: 'active',
+ exit_condition: 'exit_only_at_end',
+ actions: [],
+ edges: [],
+ created_at: '2026-01-01T00:00:00Z',
+ updated_at: '2026-01-01T00:00:00Z',
+ ...overrides,
+ }
+}
+
+function emailAction(id: string, name: string, value: Record<string, unknown>): HogFlowAction {
+ return {
+ id,
+ name,
+ description: '',
+ type: 'function_email',
+ config: { template_id: 'template-email', inputs: { email: { value } } },
+ }
+}
+
+const invoiceEmail = emailAction('email_1', 'Monthly invoice email', {
+ subject: 'Your invoice for March is ready',
+ preheader: 'Download it from your billing page',
+ text: 'Your invoice is attached. Reply to this email if a line item looks wrong.',
+ html: '<table class="footer-links"><tr><td>Your invoice is attached.</td></tr></table>',
+})
+
+const receiptEmail = emailAction('email_2', 'Receipt email', {
+ subject: 'Your receipt',
+ html: '<style type="text/css">.footer { color: #111111; }</style><p>Thanks for your <strong>payment</strong></p>',
+})
+
+const orderEmail = emailAction('email_3', 'Order email', {
+ subject: 'Order update',
+ html: '<script>trackVisit()</script><td style="{% if orders > 1 %}color:#ffffff{% endif %}">Thanks for your order</td>',
+})
+
+describe('findMatchingWorkflowSteps', () => {
+ test.each([
+ ['step name', 'monthly invoice', { actionId: 'email_1', field: 'Step', value: 'Monthly invoice email' }],
+ [
+ 'email subject',
+ 'FOR MARCH',
+ { actionId: 'email_1', field: 'Email subject', value: 'Your invoice for March is ready' },
+ ],
+ [
+ 'email preheader',
+ 'billing page',
+ { actionId: 'email_1', field: 'Email preheader', value: 'Download it from your billing page' },
+ ],
+ [
+ 'email body text, excerpted around the match',
+ 'line item',
+ {
+ actionId: 'email_1',
+ field: 'Email body',
+ value: '…is attached. Reply to this email if a line item looks wrong.',
+ },
+ ],
+ [
+ 'email body text, excerpt cut at a word boundary',
+ 'attached',
+ {
+ actionId: 'email_1',
+ field: 'Email body',
+ value: 'Your invoice is attached. Reply to this email if a line item…',
+ },
+ ],
+ [
+ 'email HTML with the markup stripped when there is no plain text',
+ 'for your payment',
+ { actionId: 'email_2', field: 'Email body', value: 'Thanks for your payment' },
+ ],
+ [
+ 'email HTML content after an attribute that contains a literal >',
+ 'for your order',
+ { actionId: 'email_3', field: 'Email body', value: 'Thanks for your order' },
+ ],
+ ])('matches the %s', (_field, search, expected) => {
+ const workflow = workflowWith({ actions: [invoiceEmail, receiptEmail, orderEmail] })
+ expect(findMatchingWorkflowSteps(workflow, search)).toEqual([expected])
+ })
+
+ test.each([
+ ['the search is blank', ' '],
+ ['only the HTML markup matched', 'footer-links'],
+ ['only a style block matched', '111111'],
+ ['only a script block matched', 'trackVisit'],
+ ['only an attribute value with a literal > in it matched', 'color:#ffffff'],
+ ['the search has regex characters that appear nowhere', 'invoice (march)'],
+ ])('returns nothing when %s', (_reason, search) => {
+ const workflow = workflowWith({ actions: [invoiceEmail, receiptEmail, orderEmail] })
+ expect(findMatchingWorkflowSteps(workflow, search)).toEqual([])
+ })
+
+ it('treats a space in the search as any separator, like the list API does', () => {
+ const workflow = workflowWith({
+ actions: [emailAction('email_1', 'Step', { subject: 'Your invoice_for-March' })],
+ })
+ expect(findMatchingWorkflowSteps(workflow, 'invoice for march')).toHaveLength(1)
+ })
+
+ it('returns nothing when the workflow name or description already explains the match', () => {
+ const workflow = workflowWith({ name: 'Invoice reminders', actions: [invoiceEmail] })
+ expect(findMatchingWorkflowSteps(workflow, 'invoice')).toEqual([])
+ })
+
+ it('includes a step staged in the draft once, preferring the live version when both match', () => {
+ const workflow = workflowWith({
+ actions: [invoiceEmail],
+ draft: {
+ actions: [
+ emailAction('email_1', 'Monthly invoice email', { subject: 'Your invoice for April is ready' }),
+ emailAction('email_2', 'Access email', { subject: 'Your beta access starts today' }),
+ ],
+ },
+ })
+ expect(findMatchingWorkflowSteps(workflow, 'invoice for')).toEqual([
+ { actionId: 'email_1', field: 'Email subject', value: 'Your invoice for March is ready' },
+ ])
+ expect(findMatchingWorkflowSteps(workflow, 'beta access')).toEqual([
+ { actionId: 'email_2', field: 'Email subject', value: 'Your beta access starts today' },
+ ])
+ expect(findMatchingWorkflowSteps(workflow, 'for april')).toEqual([
+ { actionId: 'email_1', field: 'Email subject', value: 'Your invoice for April is ready' },
+ ])
+ })
+})
diff --git a/products/workflows/frontend/Workflows/workflowSearchMatches.ts b/products/workflows/frontend/Workflows/workflowSearchMatches.ts
new file mode 100644
index 000000000000..937472c5e9a7
--- /dev/null
+++ b/products/workflows/frontend/Workflows/workflowSearchMatches.ts
@@ -0,0 +1,114 @@
+import { isEmailAction } from './hogflows/steps/types'
+import { HogFlow, HogFlowAction } from './hogflows/types'
+
+export type WorkflowStepMatchField = 'Step' | 'Email subject' | 'Email preheader' | 'Email body'
+
+export interface WorkflowStepMatch {
+ actionId: string
+ field: WorkflowStepMatchField
+ value: string
+}
+
+const EXCERPT_PADDING = 40
+
+// Mirrors _EMAIL_BODY_TEXT_SQL in the list API (products/workflows/backend/api/hog_flow.py), so the hint
+// shows the text the API matched. The tag pattern skips over quoted attribute values, so a '>' inside
+// one does not end the tag early and leak the rest of the attribute into the searchable text.
+const HTML_STYLE_BLOCK = /<style[^>]*>[\s\S]*?<\/style>/gi
+const HTML_SCRIPT_BLOCK = /<script[^>]*>[\s\S]*?<\/script>/gi
+const HTML_TAG = /<[^>"']*(?:(?:"[^"]*"|'[^']*')[^>"']*)*>/g
+
+function escapeRegExp(value: string): string {
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+}
+
+/** The body as a person reads it: the editor's plain-text export, else the HTML without styles, scripts and tags. */
+function emailBodyText(email: Record<string, unknown> | undefined): string | null {
+ if (typeof email?.text === 'string' && email.text.trim()) {
+ return email.text
+ }
+ if (typeof email?.html === 'string') {
+ return email.html.replace(HTML_STYLE_BLOCK, ' ').replace(HTML_SCRIPT_BLOCK, ' ').replace(HTML_TAG, ' ')
+ }
+ return null
+}
+
+function excerptAround(text: string, regex: RegExp): string | null {
+ const collapsed = text.replace(/\s+/g, ' ').trim()
+ const match = regex.exec(collapsed)
+ if (!match) {
+ return null
+ }
+ const matchEnd = match.index + match[0].length
+ let start = Math.max(0, match.index - EXCERPT_PADDING)
+ let end = Math.min(collapsed.length, matchEnd + EXCERPT_PADDING)
+ // Snap to word boundaries so the excerpt does not open or close mid-word.
+ const firstSpace = collapsed.indexOf(' ', start)
+ if (start > 0 && firstSpace !== -1 && firstSpace < match.index) {
+ start = firstSpace + 1
+ }
+ const lastSpace = collapsed.lastIndexOf(' ', end)
+ if (end < collapsed.length && lastSpace > matchEnd) {
+ end = lastSpace
+ }
+ return `${start > 0 ? '…' : ''}${collapsed.slice(start, end)}${end < collapsed.length ? '…' : ''}`
+}
+
+/**
+ * The same matching the list API applies server-side: a case-insensitive literal match where a space in
+ * the search term also matches dashes and underscores. Null when the term is blank.
+ */
+export function workflowSearchRegex(search: string): RegExp | null {
+ const term = search.trim()
+ if (!term) {
+ return null
+ }
+ return new RegExp(escapeRegExp(term).replace(/ /g, '[\\s\\-_]*'), 'i')
+}
+
+function matchStep(action: HogFlowAction, regex: RegExp): WorkflowStepMatch | null {
+ if (regex.test(action.name)) {
+ return { actionId: action.id, field: 'Step', value: action.name }
+ }
+ if (!isEmailAction(action)) {
+ return null
+ }
+ const email: Record<string, unknown> | undefined = action.config.inputs?.email?.value
+ const candidates: [WorkflowStepMatchField, unknown][] = [
+ ['Email subject', email?.subject],
+ ['Email preheader', email?.preheader],
+ ]
+ for (const [field, value] of candidates) {
+ if (typeof value === 'string' && regex.test(value)) {
+ return { actionId: action.id, field, value }
+ }
+ }
+ const body = emailBodyText(email)
+ const excerpt = body ? excerptAround(body, regex) : null
+ return excerpt ? { actionId: action.id, field: 'Email body', value: excerpt } : null
+}
+
+/**
+ * The steps that put a workflow in the search results when its own name and description did not.
+ * A step staged in the draft is checked only when its live version did not match, so a step
+ * appears once with the text the person is most likely looking at.
+ */
+export function findMatchingWorkflowSteps(workflow: HogFlow, search: string): WorkflowStepMatch[] {
+ const regex = workflowSearchRegex(search)
+ if (!regex || regex.test(workflow.name) || regex.test(workflow.description ?? '')) {
+ return []
+ }
+ const matches: WorkflowStepMatch[] = []
+ const matchedActionIds = new Set<string>()
+ for (const action of [...workflow.actions, ...(workflow.draft?.actions ?? [])]) {
+ if (matchedActionIds.has(action.id)) {
+ continue
+ }
+ const match = matchStep(action, regex)
+ if (match) {
+ matchedActionIds.add(action.id)
+ matches.push(match)
+ }
+ }
+ return matches
+}
diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.ts
index 83179de94b9b..9161204324ff 100644
--- a/products/workflows/frontend/generated/api.schemas.ts
+++ b/products/workflows/frontend/generated/api.schemas.ts
@@ -323,6 +323,8 @@ export interface HogFlowMinimalApi {
readonly email_sending_rate_limit: unknown
readonly edges: unknown
readonly actions: unknown
+ /** Staged content changes awaiting publish — a full snapshot of the workflow's actions, edges and settings. Null when there's nothing staged. Test it with a use_draft test run, then promote it with the publish endpoint or throw it away with discard_draft. */
+ readonly draft: unknown
/** @nullable */
readonly abort_action: string | null
readonly variables: unknown
@@ -1792,7 +1794,7 @@ export type HogFlowsListParams = {
*/
origin_product?: HogFlowsListOriginProduct
/**
- * Case-insensitive search across workflow name and 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.
*/
search?: string
/**
diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yaml
index 2550a7ec4aba..c93550b9b4c8 100644
--- a/products/workflows/mcp/tools.yaml
+++ b/products/workflows/mcp/tools.yaml
@@ -261,9 +261,11 @@ tools:
title: List workflows
description: >
List all workflows in the project. Returns workflows with their name, description, status
- (draft/active/archived), version, trigger configuration, and timestamps. Pass search=<name> to find a
- workflow by name 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, 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'.
ui_app: workflow-list
workflows-list-batch-jobs:
operation: hog_flows_batch_jobs_list
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 29a47d14a1ee..693d97f91fca 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -13057,7 +13057,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=<name> to find a workflow by name 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, 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'.",
"category": "Workflows",
"feature": "workflows",
"summary": "List workflows",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 5546e7e14d78..49f3ecb4c590 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -13744,7 +13744,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=<name> to find a workflow by name 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, 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'.",
"category": "Workflows",
"feature": "workflows",
"summary": "List workflows",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index fe7d1dc716d8..6913c8949f2b 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -46264,6 +46264,8 @@ export namespace Schemas {
readonly email_sending_rate_limit: unknown;
readonly edges: unknown;
readonly actions: unknown;
+ /** Staged content changes awaiting publish — a full snapshot of the workflow's actions, edges and settings. Null when there's nothing staged. Test it with a use_draft test run, then promote it with the publish endpoint or throw it away with discard_draft. */
+ readonly draft: unknown;
/** @nullable */
readonly abort_action: string | null;
readonly variables: unknown;
@@ -104367,7 +104369,7 @@ export namespace Schemas {
*/
origin_product?: HogFlowsListOriginProduct;
/**
- * Case-insensitive search across workflow name and 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.
*/
search?: string;
/**
diff --git a/services/mcp/src/generated/workflows/api.ts b/services/mcp/src/generated/workflows/api.ts
index 05ef94567e97..2d8ecd5321a0 100644
--- a/services/mcp/src/generated/workflows/api.ts
+++ b/services/mcp/src/generated/workflows/api.ts
@@ -26,7 +26,12 @@ export const HogFlowsListQueryParams = () => zod.object({
.enum(['loops'])
.optional()
.describe('Filter to workflows owned by a product surface, e.g. `loops` for Desktop loops.'),
- search: zod.string().optional().describe('Case-insensitive search across workflow name and description.'),
+ search: zod
+ .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.'
+ ),
status: zod
.enum(['active', 'archived', 'draft'])
.optional()
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list.json
index 4a4c73dabd4e..7f80f146ac74 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-list.json
@@ -27,7 +27,7 @@
"type": "string"
},
"search": {
- "description": "Case-insensitive search across workflow name and description.",
+ "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.",
"type": "string"
},
"status": {