: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): redesign the workflow template picker (#94113)
Harley Alexander994b4bbed785
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 8925eb43d220..75f9e9dd817f 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5960,6 +5960,30 @@ snapshots:hash: v1.k794b7964.9e7a12c3094416ddf703121095bc7eba5189420cab88d6967618bf43139069fe.UZSvEld_DwpzTPi6QpbRfxOtDYP7S_gR0F03DJcFMpMproducts-workflows-steps-delay--fixed-duration--light:hash: v1.k794b7964.f394f1e00c55c84136a291d5acb646dc12e0b27951a99e493137f7bad05a2082.zj4h9BHlkIR9RBHiB6nkO0QjDgPC1UKa08uSHemhjSQ+ products-workflows-template-card--ai--dark:+ hash: v1.k794b7964.5ca1cd71851625754d87c675688f56c0feb039ade940912f8df2ddd171d89d83.5SQmAn1fsl5RQ572BttZHT0wNAtJeZRNP0OqajxrUMc+ products-workflows-template-card--ai--light:+ hash: v1.k794b7964.5a31f5a57fe751ed5a9ec04bca6f2d5f62e2fbd86179cee3454db11924f21be1.GEdQ_SUwmnx3J9sqhog7T_uNJYnC5ph5eiKOwoYui-A+ products-workflows-template-card--basic--dark:+ hash: v1.k794b7964.5e92df62c57af26cdce62c752d1520bc51346a86f584de4915711155f46c30ef.9yCP2MeM_W_Gw2LyPZV1mkP_IvvWpHDA1e-sna1BFSw+ products-workflows-template-card--basic--light:+ hash: v1.k794b7964.fcad6a84112c48e0c1178e59477421d96950329743fce424d13a9798a207bd75.WQYkIoH-tZPH9NEwyfbOyEm79f7bcqGlX9DUaxNGcgE+ products-workflows-template-card--blank--dark:+ hash: v1.k794b7964.23ca3e9c4eb925a659ce4553dda6c27955f48bafba4fc1355c3d7c0cefcec862.M-USb6QCbLNLEHpio3NNncnc1FRh-JSo7oV0XEosD1Y+ products-workflows-template-card--blank--light:+ hash: v1.k794b7964.10249e46871b8b2f8382d2af9c62214098bf6a1a8f4baed3f2cdea8a43d45914.pDn78avyYvuB8i7MQotDOvokbWJUDneghYCfxxv7M0Q+ products-workflows-template-card--longest-description--dark:+ hash: v1.k794b7964.11dc07a26fd819ad4c9c5b41131c626fe54262f12a0fe8b033fdbbb694bc9988.WdUl8hdamKaJUeScrYS9KGkYYv1r0sUApsJRzZBsZo4+ products-workflows-template-card--longest-description--light:+ hash: v1.k794b7964.8ca8ae54cf847387bcab9cdea9a3f313158da6f3cf091b551e42cf21dd13e2df._bJpmDR8Vk8OSIsYIzzDA0Ip_q9y1c5hwwcC06giQWA+ products-workflows-template-card--narrow--dark:+ hash: v1.k794b7964.02cd68ad28118eef7360a8d93cdb71a3aa80b3bf23d71788bb4c1cd02b647a98.YodJ5IXVT3EoRbzZ0Zw52XiuRcb0hUV8BJbxi3gu3YY+ products-workflows-template-card--narrow--light:+ hash: v1.k794b7964.f14ce1bd1533072e19f0dd4136807a43502ba958d1c01970552955bb0bd16505.BRimZEFm-Oh0wDZSnWuwP_gCiXgS6mV9DhkaUopQxFI+ products-workflows-template-card--picker--dark:+ hash: v1.k794b7964.ded75abe4e8eb09bccf9b970188d13b022bf0c43636e887273791b72a4636ee2.R28mwGSEfFH1ZxrFl4cRA-zpg5RprlDTRSu96cg-v20+ products-workflows-template-card--picker--light:+ hash: v1.k794b7964.59e165d7ede2cc4e3138b95c64a7329134a16e722ff2fe224f8bf700e81d544c.SRWbL89CbOMgwObgHB8qGt_63Lh4SB0-2of7YS3PlQwqueries-webvitals--web-vitals--dark:hash: v1.k794b7964.2ae778a0c5fdba3c69dfcbd3e9589c3c3d9cc2f0fef2eefd304c565be7e9a7c9.hH71byl33sIAdRCgaPk1lDOev0qooW1xhv0AL_yrIvgqueries-webvitals--web-vitals--light:diff --git a/products/workflows/backend/templates/announce_a_new_feature_template.json b/products/workflows/backend/templates/announce_a_new_feature_template.jsonindex 009ac8748abd..d12e54e4bb48 100644--- a/products/workflows/backend/templates/announce_a_new_feature_template.json+++ b/products/workflows/backend/templates/announce_a_new_feature_template.json@@ -1,7 +1,7 @@{"id": "019b6fc4-282c-0000-50c9-aef7a834102d","name": "Announce a new feature",- "description": "Use this workflow when you release a new feature and want to notify only the users it actually applies to. This avoids blanket announcements and keeps feature messaging relevant. This pattern is especially useful when features are gated by:\n\n- plan or account type\n- role or permissions\n- rollout conditions\n- product usage level\n\nWe've left the event points empty so you can add your own events, but feel free to use the suggested email copy we've added.",+ "description": "Tell people about a new feature, but only the ones who can actually use it.","image_url": "https://res.cloudinary.com/dmukukwp6/image/upload/posthog_mobile_sessions_1aa340c741.jpg","scope": "global","created_at": "2025-12-30T14:58:04.972674Z",diff --git a/products/workflows/backend/templates/celebrate-milestone.json b/products/workflows/backend/templates/celebrate-milestone.jsonindex 45ef6bd87dfe..59a4baf2b602 100644--- a/products/workflows/backend/templates/celebrate-milestone.json+++ b/products/workflows/backend/templates/celebrate-milestone.json@@ -1,7 +1,7 @@{"id": "019cd30c-1652-0000-5ef1-980212d928fc","name": "Send congrats for a milestone reached",- "description": "Celebrate when users reach an important milestone in your product and encourage them to keep going. This can be when they: create a new project, workflow, complete a task, generate a report, etc.",+ "description": "Congratulate someone when they reach a milestone, and point them at the next one.","version": 1,"created_at": "2026-03-09T14:41:50.674613Z","created_by": {diff --git a/products/workflows/backend/templates/feature-adoption-tips.json b/products/workflows/backend/templates/feature-adoption-tips.jsonindex 117532716828..e7a6d5d70e63 100644--- a/products/workflows/backend/templates/feature-adoption-tips.json+++ b/products/workflows/backend/templates/feature-adoption-tips.json@@ -1,7 +1,7 @@{"id": "019cd2d3-79ae-0000-ebc6-28c983eb1e23","name": "Feature adoption tips",- "description": "Guide users after they adopt a feature by sending a short series of tips that help them reach key activation milestones. We're using PostHog Workflows as an example in this template.",+ "description": "Send a short series of tips after someone starts using a feature, so they reach the point where it pays off.","version": 1,"created_at": "2026-03-09T13:40:00.559123Z","created_by": {diff --git a/products/workflows/backend/templates/heavy-usage-detected.json b/products/workflows/backend/templates/heavy-usage-detected.jsonindex 3272fa584b6a..b4770d49ba34 100644--- a/products/workflows/backend/templates/heavy-usage-detected.json+++ b/products/workflows/backend/templates/heavy-usage-detected.json@@ -1,7 +1,7 @@{"id": "019cd31c-d834-0000-f997-6b771682bce7","name": "Heavy usage levels detected",- "description": "Notify users when they are close to their usage limit so they can upgrade or adjust usage before hitting the limit.",+ "description": "Warn someone when they get close to their usage limit, so they can upgrade or cut back in time.","version": 1,"created_at": "2026-03-09T15:00:08.884504Z","created_by": {diff --git a/products/workflows/backend/templates/high-intent-notification.json b/products/workflows/backend/templates/high-intent-notification.jsonindex c5b31e89f871..74eae46014c0 100644--- a/products/workflows/backend/templates/high-intent-notification.json+++ b/products/workflows/backend/templates/high-intent-notification.json@@ -1,7 +1,7 @@{"id": "019cd707-fd5b-0000-3090-053cbd91f8da","name": "Notify sales for high intent users",- "description": "Detect when a user shows strong buying intent and alert your sales team so they can follow up quickly. High intent actions can involve: visited pricing page, clicked upgrade, started checkout, requested demo, invited teammates, etc. In the conditional branch, set a filter that rules out free users who are just exploring, internal users, or very small accounts.",+ "description": "Alert your sales team in Slack when someone shows strong buying intent, so they can follow up while it is warm.","version": 1,"created_at": "2026-03-10T09:15:51.003952Z","created_by": {diff --git a/products/workflows/backend/templates/negative-survey-response.json b/products/workflows/backend/templates/negative-survey-response.jsonindex 64af8a438a27..ae2b3ee9d3d1 100644--- a/products/workflows/backend/templates/negative-survey-response.json+++ b/products/workflows/backend/templates/negative-survey-response.json@@ -1,7 +1,7 @@{"id": "019cc379-c4c6-0000-9aee-d5efa598d0f4","name": "Negative survey response -> alert team",- "description": "Get notified when a user submits negative survey feedback. This workflow detects low survey scores and sends a Slack alert so your team can quickly review the response and follow up with the user.",+ "description": "Alert your team in Slack when someone leaves negative survey feedback, so they can follow up.","version": 1,"created_at": "2026-03-06T14:07:43.302433Z","created_by": {diff --git a/products/workflows/backend/templates/onboarding_started_but_not_completed_template.json b/products/workflows/backend/templates/onboarding_started_but_not_completed_template.jsonindex 13a105e7aa0d..bb55ed42971f 100644--- a/products/workflows/backend/templates/onboarding_started_but_not_completed_template.json+++ b/products/workflows/backend/templates/onboarding_started_but_not_completed_template.json@@ -1,7 +1,7 @@{"id": "019b6fc7-ab48-0000-e2ac-82b2f714513a","name": "Onboarding started but not completed",- "description": "Remind users to finish onboarding if they start but don’t complete setup. Use this workflow to catch users who start onboarding but drop off, and send them a timely reminder to finish setting up your product – without bothering users who already completed onboarding.",+ "description": "Remind people who start onboarding but do not finish, without bothering the ones who did.","image_url": "https://res.cloudinary.com/dmukukwp6/image/upload/Hoggies_cover_thumbnail_94a9b19d5a.png","scope": "global","created_at": "2025-12-30T15:01:55.145037Z",diff --git a/products/workflows/backend/templates/re-engagement-workflow.json b/products/workflows/backend/templates/re-engagement-workflow.jsonindex f8a8d485233e..3248c7f3933d 100644--- a/products/workflows/backend/templates/re-engagement-workflow.json+++ b/products/workflows/backend/templates/re-engagement-workflow.json@@ -1,7 +1,7 @@{"id": "019cd2a2-1f48-0000-3c3a-b665db575806","name": "Re-engagement workflow for inactive users",- "description": "Detect when a user hasn’t returned to your product for a while and send a friendly reminder encouraging them to come back.",+ "description": "Win back people who have not opened your product for a while, with a friendly reminder.","version": 1,"created_at": "2026-03-09T12:46:06.152325Z","created_by": {diff --git a/products/workflows/backend/templates/repeated-failure-alert.json b/products/workflows/backend/templates/repeated-failure-alert.jsonindex 460c02c61c55..3b6424f15381 100644--- a/products/workflows/backend/templates/repeated-failure-alert.json+++ b/products/workflows/backend/templates/repeated-failure-alert.json@@ -1,7 +1,7 @@{"id": "019cc330-b1cc-0000-85a3-4f18ffa9f2ee","name": "Alert team in case of a repeated failure",- "description": "Alert your team when a user action fails so you can investigate potential issues quickly. This workflow waits briefly before notifying Slack to avoid triggering alerts for temporary errors.",+ "description": "Alert your team in Slack when an action keeps failing, after a short wait that skips one-off errors.","version": 1,"created_at": "2026-03-06T12:47:54.317218Z","created_by": {diff --git a/products/workflows/backend/templates/support-ticket-notification.json b/products/workflows/backend/templates/support-ticket-notification.jsonindex aa1ff230f72a..123c913f8880 100644--- a/products/workflows/backend/templates/support-ticket-notification.json+++ b/products/workflows/backend/templates/support-ticket-notification.json@@ -1,7 +1,7 @@{"id": "019ce1f1-5d12-0000-e318-4b3ebd4b2aea","name": "New support ticket notification",- "description": "Automatically notify your support team in Slack whenever a new support ticket is created so they can quickly review and respond.",+ "description": "Notify your support team in Slack as soon as a new ticket comes in.","version": 1,"created_at": "2026-03-12T12:06:57.554838Z","created_by": {diff --git a/products/workflows/backend/templates/ticket-unresolved-alert.json b/products/workflows/backend/templates/ticket-unresolved-alert.jsonindex 438ef5f5d75f..e36c83bec502 100644--- a/products/workflows/backend/templates/ticket-unresolved-alert.json+++ b/products/workflows/backend/templates/ticket-unresolved-alert.json@@ -1,7 +1,7 @@{"id": "019ce1ff-cff1-0000-c9b5-6efb8119db5d","name": "Alert for unresolved tickets",- "description": "Escalate support tickets that remain unresolved after a set time. The workflow waits (for example 24 hours) and then checks whether the ticket status has changed. To enable this check, make sure your ticket events include a ticket ID or status property. This lets the workflow determine whether the ticket is still open and send a Slack alert if it hasn’t been updated.",+ "description": "Escalate a support ticket in Slack when it is still open after the time you set.","version": 1,"created_at": "2026-03-12T12:22:44.465478Z","created_by": {diff --git a/products/workflows/backend/templates/trial-ending-reminder.json b/products/workflows/backend/templates/trial-ending-reminder.jsonindex dc9307bec7ae..c7a71ddfdc43 100644--- a/products/workflows/backend/templates/trial-ending-reminder.json+++ b/products/workflows/backend/templates/trial-ending-reminder.json@@ -1,7 +1,7 @@{"id": "019cc3b0-fd7d-0000-017d-c6e8ca4f737f","name": "Reminder for trial ending soon",- "description": "Automatically remind users before their trial ends. This workflow triggers when a trial starts, waits until the trial is nearly over, and sends an email encouraging the user to upgrade or continue using the product.",+ "description": "Email trial users before their trial runs out, and invite them to upgrade.","version": 1,"created_at": "2026-03-06T15:08:02.302329Z","created_by": {diff --git a/products/workflows/backend/templates/trial_started_upgrade_nudge_template.json b/products/workflows/backend/templates/trial_started_upgrade_nudge_template.jsonindex 7bb5915f177f..93dea4a4c04c 100644--- a/products/workflows/backend/templates/trial_started_upgrade_nudge_template.json+++ b/products/workflows/backend/templates/trial_started_upgrade_nudge_template.json@@ -1,7 +1,7 @@{"id": "019b6fc6-ad68-0000-2c21-f701205f3f5c","name": "Trial started → upgrade nudge",- "description": "Use this workflow to convert trial users based on intent, not deadlines.\n\nInstead of blasting everyone with “your trial ends soon” emails, this workflow waits for signs that a user is actually using the product, then nudges them to upgrade, with a few well-timed reminders and a clear stop.",+ "description": "Nudge trial users to upgrade when they show real usage, instead of when the clock runs down.","image_url": "https://res.cloudinary.com/dmukukwp6/image/upload/Elon_53dbe00271.jpg","scope": "global","created_at": "2025-12-30T15:00:50.152615Z",diff --git a/products/workflows/backend/templates/unlocking_advanced_features.json b/products/workflows/backend/templates/unlocking_advanced_features.jsonindex 658a4334de21..37af4ed189d7 100644--- a/products/workflows/backend/templates/unlocking_advanced_features.json+++ b/products/workflows/backend/templates/unlocking_advanced_features.json@@ -1,7 +1,7 @@{"id": "019cc2c0-99f0-0000-b510-b3774bc75c7e","name": "Unlocking advanced features",- "description": "Unlock features automatically when users complete a key action in your product. This workflow updates a user property that can be used to target feature flags or personalize the experience.",+ "description": "Unlock a feature when someone completes a key action, by setting a property you can target.","version": 1,"created_at": "2026-03-06T10:45:28.176584Z","created_by": {diff --git a/products/workflows/backend/templates/unused-features-education.json b/products/workflows/backend/templates/unused-features-education.jsonindex 0a1adc37068d..16b1b46c59cf 100644--- a/products/workflows/backend/templates/unused-features-education.json+++ b/products/workflows/backend/templates/unused-features-education.json@@ -1,7 +1,7 @@{"id": "019cd710-ccd4-0000-a139-aa4f6f8b9a29","name": "Educate users for unused features",- "description": "Detect when users haven’t tried an important feature yet and send a helpful tip encouraging them to explore it. In this workflow, we're using PostHog Workflows as an example.",+ "description": "Find people who have not tried an important feature yet, and send them a tip that gets them started.","version": 1,"created_at": "2026-03-10T09:25:28.405138Z","created_by": {diff --git a/products/workflows/backend/templates/user-stuck-onboarding.json b/products/workflows/backend/templates/user-stuck-onboarding.jsonindex c821ee8a8405..a632e209461e 100644--- a/products/workflows/backend/templates/user-stuck-onboarding.json+++ b/products/workflows/backend/templates/user-stuck-onboarding.json@@ -1,7 +1,7 @@{"id": "019ce221-942b-0000-6929-15f99a355144","name": "User stuck in onboarding alert",- "description": "Detect users who start onboarding but don’t complete it and alert your team so they can reach out and help. Configure the delay to give new users time to finish onboarding (for example 24 hours), then set the conditional step to check whether the user has not completed your activation event (such as onboarding_completed, first_project_created, or another key milestone). If the event hasn’t happened, the workflow sends a Slack alert so the team can investigate.",+ "description": "Alert your team in Slack when someone starts onboarding and then gets stuck, so they can help.","version": 1,"created_at": "2026-03-12T12:59:37.387738Z","created_by": {diff --git a/products/workflows/backend/templates/user-upgrade-webhook.json b/products/workflows/backend/templates/user-upgrade-webhook.jsonindex 3b79f0c634c4..a92b3b71f587 100644--- a/products/workflows/backend/templates/user-upgrade-webhook.json+++ b/products/workflows/backend/templates/user-upgrade-webhook.json@@ -1,7 +1,7 @@{"id": "019ce206-1ef1-0000-f1c1-3f9c433294c6","name": "Send a webhook when a user upgrades",- "description": "Send a webhook when a user upgrades so other systems like your CRM, billing tool, or internal backend can react to the change. You can connect this to your internal system, HubSpot, Zapier, etc. ",+ "description": "Send a webhook when someone upgrades, so your CRM, billing tool, or backend can react.","version": 1,"created_at": "2026-03-12T12:29:37.905693Z","created_by": {diff --git a/products/workflows/backend/templates/welcome_email_sequence_template.json b/products/workflows/backend/templates/welcome_email_sequence_template.jsonindex bf521affe86a..28e7cf27e059 100644--- a/products/workflows/backend/templates/welcome_email_sequence_template.json+++ b/products/workflows/backend/templates/welcome_email_sequence_template.json@@ -1,7 +1,7 @@{"id": "019b6f44-f9a3-0000-c4a7-b8050d25d690",- "name": "Welcome Email Sequence",- "description": "This is a simple workflow you can use when a user signs up for your product, and you want to send an email introducing the product, followed up by emails checking in on how your users are doing.",+ "name": "Welcome email sequence",+ "description": "Welcome new signups with an intro email, then check in on how they are getting on.","image_url": "https://res.cloudinary.com/dmukukwp6/image/upload/f_webp,h_270,w_480,c_fill,g_auto,q_auto/growth_think_905cd0fa65?_a=AXAH4nI0","scope": "global","created_at": "2025-12-30T12:39:09.987406Z",diff --git a/products/workflows/frontend/Workflows/templates/WorkflowTemplateAiBadge.tsx b/products/workflows/frontend/Workflows/templates/WorkflowTemplateAiBadge.tsxnew file mode 100644index 000000000000..0b95029501f2--- /dev/null+++ b/products/workflows/frontend/Workflows/templates/WorkflowTemplateAiBadge.tsx@@ -0,0 +1,11 @@+import { IconSparkles } from '@posthog/icons'++/** Marks a template that hands work to an AI agent. Uses the same purple as AI surfaces elsewhere. */+export function WorkflowTemplateAiBadge(): JSX.Element {+ return (+ <span className="flex items-center gap-1 shrink-0 px-1.5 py-0.5 rounded text-xs font-semibold text-ai bg-ai/10">+ <IconSparkles />+ AI+ </span>+ )+}diff --git a/products/workflows/frontend/Workflows/templates/WorkflowTemplateBlankPreview.tsx b/products/workflows/frontend/Workflows/templates/WorkflowTemplateBlankPreview.tsxnew file mode 100644index 000000000000..c74b36c559c9--- /dev/null+++ b/products/workflows/frontend/Workflows/templates/WorkflowTemplateBlankPreview.tsx@@ -0,0 +1,10 @@+import { IconPlus } from '@posthog/icons'++/** Stands in for the step icons on the "blank workflow" card, which has no steps yet. */+export function WorkflowTemplateBlankPreview(): JSX.Element {+ return (+ <div className="flex items-center justify-center rounded size-6 shrink-0 border border-dashed text-secondary">+ <IconPlus />+ </div>+ )+}diff --git a/products/workflows/frontend/Workflows/templates/WorkflowTemplateCard.stories.tsx b/products/workflows/frontend/Workflows/templates/WorkflowTemplateCard.stories.tsxnew file mode 100644index 000000000000..7d2b87be40cc--- /dev/null+++ b/products/workflows/frontend/Workflows/templates/WorkflowTemplateCard.stories.tsx@@ -0,0 +1,185 @@+import './WorkflowTemplateChooser.scss'++import { Meta, StoryFn } from '@storybook/react'++import type { HogFlowAction, HogFlowTemplate } from '../hogflows/types'+import { WorkflowTemplateAiBadge } from './WorkflowTemplateAiBadge'+import { WorkflowTemplateBlankPreview } from './WorkflowTemplateBlankPreview'+import { WorkflowTemplateCard, WorkflowTemplateCardProps } from './WorkflowTemplateCard'+import { isAiTemplate } from './workflowTemplateDisplay'+import { WorkflowTemplateMeta } from './WorkflowTemplateMeta'+import { WorkflowTemplateSteps } from './WorkflowTemplateSteps'++const meta: Meta<typeof WorkflowTemplateCard> = {+ title: 'Products/Workflows/Template card',+ component: WorkflowTemplateCard,+}+export default meta++type StepSpec = HogFlowAction['type'] | [HogFlowAction['type'], string]++function template(+ name: string,+ description: string,+ trigger: string,+ steps: StepSpec[],+ tags: string[] = []+): HogFlowTemplate {+ const actions = [+ { id: 'trigger', type: 'trigger', name: 'Trigger', config: { type: trigger, filters: {} } },+ ...steps.map((step, index) => {+ const [type, templateId] = Array.isArray(step) ? step : [step, undefined]+ return { id: `${type}_${index}`, type, name: type, config: templateId ? { template_id: templateId } : {} }+ }),+ { id: 'exit', type: 'exit', name: 'Exit', config: {} },+ ]+ // The shipped templates chain their steps with `continue` edges, and the card reads that chain+ const edges = actions.slice(0, -1).map((action, index) => ({+ from: action.id,+ to: actions[index + 1].id,+ type: 'continue',+ }))+ return { id: name, name, description, actions, edges, tags, scope: 'global' } as unknown as HogFlowTemplate+}++// Copied from the templates that ship in products/workflows/backend/templates, so the card is+// measured against the copy people actually see+const TEMPLATES: HogFlowTemplate[] = [+ template(+ 'New support ticket notification',+ 'Notify your support team in Slack as soon as a new ticket comes in.',+ 'event',+ [['function', 'template-slack']],+ ['slack', 'support ticket', 'support']+ ),+ template(+ 'Welcome email sequence',+ 'Welcome new signups with an intro email, then check in on how they are getting on.',+ 'event',+ [['function_email', 'template-email'], 'delay', ['function_email', 'template-email']]+ ),+ template(+ 'Educate users for unused features',+ 'Find people who have not tried an important feature yet, and send them a tip that gets them started.',+ 'schedule',+ [+ 'delay',+ 'conditional_branch',+ ['function_email', 'template-email'],+ 'delay',+ 'conditional_branch',+ ['function_email', 'template-email'],+ ],+ ['product usage']+ ),+ template(+ 'Notify sales for high intent users',+ 'Alert your sales team in Slack when someone shows strong buying intent, so they can follow up while it is warm.',+ 'event',+ ['conditional_branch', ['function', 'template-slack']],+ ['sales', 'slack']+ ),+ // Stands in for the AI template on the way, so the badge has something to sit on+ template(+ 'Triage a new error with an agent',+ 'Hand a new error to an AI agent. It reads the stack trace, finds the change that caused it, and opens a draft pull request.',+ 'internal-event',+ [['function', 'template-posthog-create-task']],+ ['error tracking']+ ),+ template(+ 'Trial started → upgrade nudge',+ 'Nudge trial users to upgrade when they show real usage, instead of when the clock runs down.',+ 'event',+ [+ 'conditional_branch',+ ['function_email', 'template-email'],+ 'conditional_branch',+ ['function_email', 'template-email'],+ 'conditional_branch',+ 'delay',+ ['function_email', 'template-email'],+ 'delay',+ ]+ ),+ template(+ 'Announce a new feature',+ 'Tell people about a new feature, but only the ones who can actually use it.',+ 'event',+ [+ 'conditional_branch',+ ['function_email', 'template-email'],+ 'conditional_branch',+ ['function_email', 'template-email'],+ 'delay',+ ]+ ),+ template(+ 'Send a webhook when a user upgrades',+ 'Send a webhook when someone upgrades, so your CRM, billing tool, or backend can react.',+ 'event',+ [['function', 'template-webhook']],+ ['webhook', 'upgrade']+ ),+]++function templateArgs(source: HogFlowTemplate): WorkflowTemplateCardProps {+ return {+ name: source.name,+ description: source.description,+ preview: <WorkflowTemplateSteps actions={source.actions} edges={source.edges} />,+ badge: isAiTemplate(source) ? <WorkflowTemplateAiBadge /> : null,+ footer: <WorkflowTemplateMeta template={source} />,+ onClick: () => {},+ 'data-attr': 'create-workflow-from-template',+ }+}++const BLANK_ARGS: WorkflowTemplateCardProps = {+ name: 'Blank workflow',+ description: 'Start from scratch and add your own trigger and steps.',+ preview: <WorkflowTemplateBlankPreview />,+ footer: null,+ onClick: () => {},+ 'data-attr': 'create-workflow-blank',+}++const Template: StoryFn<WorkflowTemplateCardProps> = (props) => (+ <div className="w-[26rem]">+ <WorkflowTemplateCard {...props} />+ </div>+)++export const Basic: StoryFn<WorkflowTemplateCardProps> = Template.bind({})+Basic.args = templateArgs(TEMPLATES[1])++// The longest description that ships, next to the menu a team template shows+export const LongestDescription: StoryFn<WorkflowTemplateCardProps> = Template.bind({})+LongestDescription.args = { ...templateArgs(TEMPLATES[3]), onEdit: () => {}, onDelete: () => {} }++// A template that hands work to an agent, so the AI badge shows+export const Ai: StoryFn = () => (+ <div className="w-[26rem]">+ <WorkflowTemplateCard {...templateArgs(TEMPLATES[4])} />+ </div>+)++export const Blank: StoryFn<WorkflowTemplateCardProps> = Template.bind({})+Blank.args = BLANK_ARGS++// The picker drops to one column in a narrow modal, so the card has to hold up at this width+export const Narrow: StoryFn = () => (+ <div className="w-64">+ <WorkflowTemplateCard {...templateArgs(TEMPLATES[3])} />+ </div>+)++// The picker's own layout: columns, so a long description makes one card taller and nothing else+export const Picker: StoryFn = () => (+ <div className="WorkflowTemplateChooser w-[54rem]">+ <WorkflowTemplateCard {...BLANK_ARGS} />+ {TEMPLATES.map((source) => (+ <WorkflowTemplateCard key={source.id} {...templateArgs(source)} />+ ))}+ </div>+)diff --git a/products/workflows/frontend/Workflows/templates/WorkflowTemplateCard.tsx b/products/workflows/frontend/Workflows/templates/WorkflowTemplateCard.tsxnew file mode 100644index 000000000000..3aec0d61a08f--- /dev/null+++ b/products/workflows/frontend/Workflows/templates/WorkflowTemplateCard.tsx@@ -0,0 +1,102 @@+import clsx from 'clsx'+import { useState } from 'react'++import { IconPencil, IconTrash } from '@posthog/icons'++import { More } from 'lib/lemon-ui/LemonButton/More'+import { LemonMenuOverlay } from 'lib/lemon-ui/LemonMenu/LemonMenu'++export interface WorkflowTemplateCardProps {+ name: string+ description?: string | null+ /** Icons that show what the template does, drawn above the name. */+ preview: JSX.Element+ /** Marker next to the name, such as the AI badge. */+ badge?: JSX.Element | null+ /** Short line under the description, such as how the workflow starts. */+ footer?: JSX.Element | null+ onClick: () => void+ onEdit?: (e: React.MouseEvent) => void+ onDelete?: (e: React.MouseEvent) => void+ 'data-attr': string+}++export function WorkflowTemplateCard({+ name,+ description,+ preview,+ badge,+ footer,+ onClick,+ onEdit,+ onDelete,+ 'data-attr': dataAttr,+}: WorkflowTemplateCardProps): JSX.Element {+ const [isMenuOpen, setIsMenuOpen] = useState(false)+ const hasMenu = !!onEdit || !!onDelete++ return (+ <div className="relative">+ <button+ type="button"+ onClick={onClick}+ data-attr={dataAttr}+ className="flex flex-col gap-2 w-full h-full p-4 text-left border rounded bg-surface-primary hover:border-primary hover:bg-surface-secondary transition-colors"+ >+ {preview}+ <div className="flex flex-col gap-1 grow">+ <div className={clsx('flex items-start gap-2', hasMenu && 'pr-6')}>+ <span className="font-semibold">{name}</span>+ {badge}+ </div>+ {/* Descriptions are authored with paragraphs and lists, so keep the line breaks */}+ {description && <p className="mb-0 text-sm text-secondary whitespace-pre-line">{description}</p>}+ </div>+ {footer}+ </button>+ {hasMenu && (+ <div className="absolute top-2.5 right-2.5">+ <More+ size="xsmall"+ dropdown={{+ visible: isMenuOpen,+ onVisibilityChange: setIsMenuOpen,+ closeOnClickInside: true,+ }}+ overlay={+ <LemonMenuOverlay+ items={[+ ...(onEdit+ ? [+ {+ label: 'Edit',+ icon: <IconPencil />,+ onClick: (e: any) => {+ setIsMenuOpen(false)+ onEdit(e)+ },+ },+ ]+ : []),+ ...(onDelete+ ? [+ {+ label: 'Delete',+ status: 'danger' as const,+ icon: <IconTrash />,+ onClick: (e: any) => {+ setIsMenuOpen(false)+ onDelete(e)+ },+ },+ ]+ : []),+ ]}+ />+ }+ />+ </div>+ )}+ </div>+ )+}diff --git a/products/workflows/frontend/Workflows/templates/WorkflowTemplateChooser.scss b/products/workflows/frontend/Workflows/templates/WorkflowTemplateChooser.scssindex c6ec32b109dd..1209d8deda92 100644--- a/products/workflows/frontend/Workflows/templates/WorkflowTemplateChooser.scss+++ b/products/workflows/frontend/Workflows/templates/WorkflowTemplateChooser.scss@@ -1,9 +1,8 @@.WorkflowTemplateChooser {display: grid;- grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));- gap: 0.5em;- .TemplateItem {- height: 210px;- }+ // Wide enough that a template description reads in two lines without being cut+ grid-template-columns: repeat(auto-fill, minmax(26rem, 1fr));+ gap: 0.5rem;+ align-items: stretch;}diff --git a/products/workflows/frontend/Workflows/templates/WorkflowTemplateChooser.tsx b/products/workflows/frontend/Workflows/templates/WorkflowTemplateChooser.tsxindex 50fe505caf73..60134a156fe7 100644--- a/products/workflows/frontend/Workflows/templates/WorkflowTemplateChooser.tsx+++ b/products/workflows/frontend/Workflows/templates/WorkflowTemplateChooser.tsx@@ -1,32 +1,29 @@import './WorkflowTemplateChooser.scss'-import clsx from 'clsx'import { useActions, useValues } from 'kea'import { router } from 'kea-router'-import { useState } from 'react'-import { IconPencil, IconTrash } from '@posthog/icons'-import { LemonDialog, LemonTag } from '@posthog/lemon-ui'+import { LemonDialog } from '@posthog/lemon-ui'-import { FallbackCoverImage } from 'lib/components/FallbackCoverImage/FallbackCoverImage'-import { More } from 'lib/lemon-ui/LemonButton/More'-import { LemonMenuOverlay } from 'lib/lemon-ui/LemonMenu/LemonMenu'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { Spinner } from 'lib/lemon-ui/Spinner'import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'-import BlankWorkflowHog from 'public/blank-dashboard-hog.png'-import type { HogFlowTemplate } from '../hogflows/types'import { newWorkflowLogic } from '../newWorkflowLogic'+import { WorkflowTemplateAiBadge } from './WorkflowTemplateAiBadge'+import { WorkflowTemplateBlankPreview } from './WorkflowTemplateBlankPreview'+import { WorkflowTemplateCard } from './WorkflowTemplateCard'+import { isAiTemplate } from './workflowTemplateDisplay'+import { WorkflowTemplateMeta } from './WorkflowTemplateMeta'import { workflowTemplatesLogic } from './workflowTemplatesLogic'+import { WorkflowTemplateSteps } from './WorkflowTemplateSteps'interface WorkflowTemplateChooserProps {showEmptyWorkflow?: boolean}-// Adapted from DashboardTemplateChooser.tsx; try to keep parity for a consistent user experienceexport function WorkflowTemplateChooser(props: WorkflowTemplateChooserProps): JSX.Element {const { filteredTemplates, workflowTemplatesLoading } = useValues(workflowTemplatesLogic)const { deleteHogflowTemplate } = useActions(workflowTemplatesLogic)@@ -48,34 +45,29 @@ export function WorkflowTemplateChooser(props: WorkflowTemplateChooserProps): JS}return (- <div className="WorkflowTemplateChooser">- {props.showEmptyWorkflow && (- <TemplateItem- key={0}- template={{- name: 'Empty workflow',- description: 'Create a blank workflow from scratch',- image_url: BlankWorkflowHog,- scope: 'team',- tags: [],- }}- onClick={createEmptyWorkflow}- index={0}- data-attr="create-workflow-blank"- />- )}- {workflowTemplatesLoading ? (- <Spinner className="text-6xl" />- ) : (- filteredTemplates.map((template: HogFlowTemplate, index: number) => (- <TemplateItem+ <div className="flex flex-col gap-3">+ <div className="WorkflowTemplateChooser">+ {props.showEmptyWorkflow && (+ <WorkflowTemplateCard+ name="Blank workflow"+ description="Start from scratch and add your own trigger and steps."+ preview={<WorkflowTemplateBlankPreview />}+ onClick={createEmptyWorkflow}+ data-attr="create-workflow-blank"+ />+ )}+ {filteredTemplates.map((template: HogFlowTemplate) => (+ <WorkflowTemplateCardkey={template.id}- template={template}+ name={template.name || 'Unnamed template'}+ description={template.description}+ preview={<WorkflowTemplateSteps actions={template.actions} edges={template.edges} />}+ badge={isAiTemplate(template) ? <WorkflowTemplateAiBadge /> : null}+ footer={<WorkflowTemplateMeta template={template} />}onClick={() => createWorkflowFromTemplate(template)}onEdit={canEditTemplate(template)- ? (e) => {- e.stopPropagation()+ ? () => {router.actions.push(urls.workflowNew(), {editTemplateId: template.id,})@@ -84,8 +76,7 @@ export function WorkflowTemplateChooser(props: WorkflowTemplateChooserProps): JS}onDelete={canDeleteTemplate(template)- ? (e) => {- e.stopPropagation()+ ? () => {LemonDialog.open({title: 'Delete template?',description: (@@ -114,123 +105,21 @@ export function WorkflowTemplateChooser(props: WorkflowTemplateChooserProps): JS}: undefined}- index={props.showEmptyWorkflow ? index + 1 : index}data-attr="create-workflow-from-template"/>- ))- )}- </div>- )-}--function TemplateItem({- template,- onClick,- onEdit,- onDelete,- index,- 'data-attr': dataAttr,-}: {- template: Pick<HogFlowTemplate, 'name' | 'description' | 'image_url' | 'scope' | 'tags'>- onClick: () => void- onEdit?: (e: React.MouseEvent) => void- onDelete?: (e: React.MouseEvent) => void- index: number- 'data-attr': string-}): JSX.Element {- const [isHovering, setIsHovering] = useState(false)- const [isMenuOpen, setIsMenuOpen] = useState(false)-- const scopeTag =- template.scope === 'global'- ? 'official'- : template.scope === 'organization'- ? 'organization'- : template.scope === 'team'- ? 'team'- : null-- return (- <div- className="cursor-pointer border rounded TemplateItem flex flex-col transition-all relative overflow-hidden"- onClick={onClick}- onMouseEnter={() => setIsHovering(true)}- onMouseLeave={() => setIsHovering(false)}- data-attr={dataAttr}- >- {(onEdit || onDelete) && (- <div className="absolute top-2 right-2 z-10" onClick={(e) => e.stopPropagation()}>- <More- size="small"- className="bg-white/20 dark:bg-white/10 backdrop-blur-sm hover:bg-white/40 dark:hover:bg-white/20 transition-colors"- dropdown={{- visible: isMenuOpen,- onVisibilityChange: setIsMenuOpen,- closeOnClickInside: true,- }}- overlay={- <LemonMenuOverlay- items={[- ...(onEdit- ? [- {- label: 'Edit',- icon: <IconPencil />,- onClick: (e: any) => {- setIsMenuOpen(false)- onEdit(e)- },- },- ]- : []),- ...(onDelete- ? [- {- label: 'Delete',- status: 'danger' as const,- icon: <IconTrash />,- onClick: (e: any) => {- setIsMenuOpen(false)- onDelete(e)- },- },- ]- : []),- ]}- />- }- />- </div>- )}- <div- className={clsx('transition-all w-full overflow-hidden', isHovering ? 'h-4 min-h-4' : 'h-30 min-h-30')}- >- <FallbackCoverImage- src={template?.image_url || undefined}- alt="cover photo"- index={index}- imageClassName="h-30"- />- </div>-- <h5 className="px-2 mb-1">{template?.name || 'Unnamed template'}</h5>- <div className="flex gap-x-1 gap-y-0.5 px-2 mb-1 flex-wrap">- {scopeTag && (- <LemonTag key="scope" type="option" className="shrink-0">- {scopeTag}- </LemonTag>- )}- {template.tags.map((tag) => (- <LemonTag key={tag} type="default" className="shrink-0">- {tag}- </LemonTag>))}</div>- <div className={clsx('px-2 py-1 grow', isHovering ? 'overflow-y-auto' : 'overflow-hidden')}>- <p className={clsx('text-secondary text-xs', isHovering ? '' : 'line-clamp-2')}>- {template?.description ?? ' '}- </p>- </div>+ {workflowTemplatesLoading ? (+ <div className="flex justify-center py-6">+ <Spinner className="text-3xl" />+ </div>+ ) : (+ filteredTemplates.length === 0 && (+ <p className="mb-0 py-6 text-center text-secondary">+ No templates match your filters. Clear the search or choose another category.+ </p>+ )+ )}</div>)}diff --git a/products/workflows/frontend/Workflows/templates/WorkflowTemplateMeta.tsx b/products/workflows/frontend/Workflows/templates/WorkflowTemplateMeta.tsxnew file mode 100644index 000000000000..d569cdaccf22--- /dev/null+++ b/products/workflows/frontend/Workflows/templates/WorkflowTemplateMeta.tsx@@ -0,0 +1,32 @@+import { IconBolt, IconClock, IconPeople } from '@posthog/icons'++import type { HogFlowTemplate } from '../hogflows/types'+import { getTemplateScopeLabel, getTemplateTrigger } from './workflowTemplateDisplay'++/** The facts under a template's description: how it starts, and who it belongs to. */+export function WorkflowTemplateMeta({ template }: { template: HogFlowTemplate }): JSX.Element | null {+ const trigger = getTemplateTrigger(template)+ const scopeLabel = getTemplateScopeLabel(template.scope)++ if (!trigger && !scopeLabel) {+ return null+ }++ return (+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-accent">+ {trigger && (+ <MetaFact icon={trigger.type === 'schedule' ? <IconClock /> : <IconBolt />} label={trigger.label} />+ )}+ {scopeLabel && <MetaFact icon={<IconPeople />} label={`${scopeLabel} template`} />}+ </div>+ )+}++function MetaFact({ icon, label }: { icon: JSX.Element; label: string }): JSX.Element {+ return (+ <span className="flex items-center gap-1 min-w-0">+ <span className="shrink-0">{icon}</span>+ <span className="truncate">{label}</span>+ </span>+ )+}diff --git a/products/workflows/frontend/Workflows/templates/WorkflowTemplateSteps.tsx b/products/workflows/frontend/Workflows/templates/WorkflowTemplateSteps.tsxnew file mode 100644index 000000000000..8a0c42456a5c--- /dev/null+++ b/products/workflows/frontend/Workflows/templates/WorkflowTemplateSteps.tsx@@ -0,0 +1,66 @@+import { useValues } from 'kea'+import { Fragment, useMemo } from 'react'++import { themeLogic } from '~/layout/navigation-3000/themeLogic'++import { getHogFlowStep } from '../hogflows/steps/HogFlowSteps'+import type { HogFlowAction, HogFlowEdge } from '../hogflows/types'+import { getOrderedActions } from './workflowTemplateDisplay'++const MAX_VISIBLE_STEPS = 4++/** The steps of a workflow template, drawn as the same icon tiles the editor canvas uses. */+export function WorkflowTemplateSteps({+ actions,+ edges,+}: {+ actions: HogFlowAction[]+ edges?: HogFlowEdge[]+}): JSX.Element | null {+ const { isDarkModeOn } = useValues(themeLogic)++ const steps = useMemo(+ () =>+ getOrderedActions(actions, edges)+ // The exit step closes every workflow, so it says nothing about this one+ .filter((action) => action.type !== 'exit')+ .map((action) => getHogFlowStep(action, {}, isDarkModeOn))+ .filter((step) => !!step),+ [actions, edges, isDarkModeOn]+ )++ if (steps.length === 0) {+ return null+ }++ const visibleSteps = steps.slice(0, MAX_VISIBLE_STEPS)+ const hiddenStepCount = steps.length - visibleSteps.length++ return (+ <div className="flex items-center">+ {visibleSteps.map((step, index) => (+ <Fragment key={index}>+ {index > 0 && <StepConnector />}+ <div+ className="flex items-center justify-center rounded size-6 shrink-0"+ style={{ backgroundColor: `${step.color}20`, color: step.color }}+ >+ {step.icon}+ </div>+ </Fragment>+ ))}+ {hiddenStepCount > 0 && (+ <>+ <StepConnector />+ <div className="flex items-center justify-center rounded h-6 px-1.5 shrink-0 text-xs text-secondary bg-fill-primary">+ +{hiddenStepCount}+ </div>+ </>+ )}+ </div>+ )+}++function StepConnector(): JSX.Element {+ return <div className="w-2 shrink-0 border-t border-dashed" />+}diff --git a/products/workflows/frontend/Workflows/templates/workflowTemplateDisplay.test.ts b/products/workflows/frontend/Workflows/templates/workflowTemplateDisplay.test.tsnew file mode 100644index 000000000000..850fa4c894e2--- /dev/null+++ b/products/workflows/frontend/Workflows/templates/workflowTemplateDisplay.test.ts@@ -0,0 +1,105 @@+import type { HogFlowTemplate } from '../hogflows/types'+import { getOrderedActions, getTemplateTrigger, isAiTemplate } from './workflowTemplateDisplay'++describe('workflowTemplateDisplay', () => {+ function templateWith(partial: Partial<HogFlowTemplate>): HogFlowTemplate {+ return { actions: [], tags: [], ...partial } as unknown as HogFlowTemplate+ }++ describe('isAiTemplate', () => {+ it.each([+ ['template-posthog-create-task', true],+ ['template-posthog-run-scout', true],+ ['template-slack', false],+ ])('reads a %s step as AI: %s', (templateId, expected) => {+ const template = templateWith({+ actions: [{ id: 'a', type: 'function', name: 'a', config: { template_id: templateId } }] as any,+ })+ expect(isAiTemplate(template)).toBe(expected)+ })++ it('reads the ai tag as AI, for a template that reaches an agent another way', () => {+ expect(isAiTemplate(templateWith({ tags: ['AI', 'support'] }))).toBe(true)+ })++ it('does not read a step without a template_id as AI', () => {+ const template = templateWith({+ actions: [{ id: 'a', type: 'delay', name: 'a', config: { delay_duration: '1d' } }] as any,+ })+ expect(isAiTemplate(template)).toBe(false)+ })+ })++ describe('getTemplateTrigger', () => {+ it('reads the trigger from the action graph, which is where the editor keeps it', () => {+ const template = templateWith({+ actions: [{ id: 't', type: 'trigger', name: 't', config: { type: 'schedule' } }] as any,+ })+ expect(getTemplateTrigger(template)).toEqual({ type: 'schedule', label: 'Starts on a schedule' })+ })++ it('labels a trigger type it does not know, rather than dropping the line', () => {+ const template = templateWith({+ actions: [{ id: 't', type: 'trigger', name: 't', config: { type: 'brand-new' } }] as any,+ })+ expect(getTemplateTrigger(template)?.label).toEqual('Starts on a trigger')+ })+ })++ describe('getOrderedActions', () => {+ const actions = [+ { id: 'trigger', type: 'trigger', name: 'trigger', config: {} },+ { id: 'email', type: 'function_email', name: 'email', config: {} },+ { id: 'delay', type: 'delay', name: 'delay', config: {} },+ { id: 'exit', type: 'exit', name: 'exit', config: {} },+ ] as any++ it('walks the edges rather than the array, which is creation order', () => {+ const edges = [+ { from: 'trigger', to: 'delay', type: 'continue' },+ { from: 'delay', to: 'email', type: 'continue' },+ { from: 'email', to: 'exit', type: 'continue' },+ ] as any+ expect(getOrderedActions(actions, edges).map((action) => action.id)).toEqual([+ 'trigger',+ 'delay',+ 'email',+ 'exit',+ ])+ })++ it('takes a met condition before the default path, which usually just exits', () => {+ const branching = [+ { id: 'trigger', type: 'trigger', name: 'trigger', config: {} },+ { id: 'branch', type: 'conditional_branch', name: 'branch', config: {} },+ { id: 'email', type: 'function_email', name: 'email', config: {} },+ { id: 'exit', type: 'exit', name: 'exit', config: {} },+ ] as any+ const edges = [+ { from: 'trigger', to: 'branch', type: 'continue' },+ { from: 'branch', to: 'exit', type: 'continue' },+ { from: 'branch', to: 'email', type: 'branch', index: 0 },+ ] as any+ expect(getOrderedActions(branching, edges).map((action) => action.id)).toEqual([+ 'trigger',+ 'branch',+ 'email',+ 'exit',+ ])+ })++ it('keeps an action the edges never reach', () => {+ const edges = [{ from: 'trigger', to: 'exit', type: 'continue' }] as any+ expect(getOrderedActions(actions, edges).map((action) => action.id)).toEqual([+ 'trigger',+ 'exit',+ 'email',+ 'delay',+ ])+ })++ it('falls back to the array when there is no trigger to walk from', () => {+ expect(getOrderedActions(actions.slice(1), [])).toEqual(actions.slice(1))+ })+ })+})diff --git a/products/workflows/frontend/Workflows/templates/workflowTemplateDisplay.ts b/products/workflows/frontend/Workflows/templates/workflowTemplateDisplay.tsnew file mode 100644index 000000000000..b6166d567c67--- /dev/null+++ b/products/workflows/frontend/Workflows/templates/workflowTemplateDisplay.ts@@ -0,0 +1,111 @@+import type { HogFlowAction, HogFlowEdge, HogFlowTemplate } from '../hogflows/types'++const TRIGGER_LABELS: Record<string, string> = {+ event: 'Starts on an event',+ 'internal-event': 'Starts on an event',+ webhook: 'Starts on a webhook',+ manual: 'Starts manually',+ schedule: 'Starts on a schedule',+ tracking_pixel: 'Starts on a tracking pixel',+ batch: 'Starts for an audience',+ 'data-warehouse-table': 'Starts on warehouse data',+ 'data-warehouse-view': 'Starts on warehouse data',+}++const SCOPE_LABELS: Record<string, string> = {+ organization: 'Organization',+ team: 'Team',+}++type TriggerAction = Extract<HogFlowAction, { type: 'trigger' }>++export interface TemplateTrigger {+ type: string+ label: string+}++export function getTemplateTrigger(template: Pick<HogFlowTemplate, 'trigger' | 'actions'>): TemplateTrigger | null {+ const triggerAction = template.actions?.find((action): action is TriggerAction => action.type === 'trigger')+ const type = triggerAction?.config.type ?? template.trigger?.type+ if (!type) {+ return null+ }+ return { type, label: TRIGGER_LABELS[type] ?? 'Starts on a trigger' }+}++// Global templates are the majority, so only the narrower scopes are worth a label.+export function getTemplateScopeLabel(scope: HogFlowTemplate['scope']): string | null {+ return scope ? (SCOPE_LABELS[scope] ?? null) : null+}++// Hog function templates for the steps that hand work to an AI agent.+const AI_STEP_TEMPLATE_IDS = new Set(['template-posthog-create-task', 'template-posthog-run-scout'])++const AI_TAG = 'ai'++/**+ * A template counts as AI if it runs an AI step, or if an author tagged it `ai`. The tag covers+ * templates that reach an agent another way, such as a webhook to a service the team runs.+ */+export function isAiTemplate(template: Pick<HogFlowTemplate, 'actions' | 'tags'>): boolean {+ if (template.tags?.some((tag) => tag.toLowerCase() === AI_TAG)) {+ return true+ }+ return (template.actions ?? []).some(+ (action) => 'template_id' in action.config && AI_STEP_TEMPLATE_IDS.has(action.config.template_id)+ )+}++// A branch edge is the path a met condition takes, so it says more than the default `continue` edge.+function compareEdges(a: HogFlowEdge, b: HogFlowEdge): number {+ if (a.type !== b.type) {+ return a.type === 'branch' ? -1 : 1+ }+ return (a.index ?? 0) - (b.index ?? 0)+}++function getSortedEdgesByFrom(edges: HogFlowEdge[]): Map<string, HogFlowEdge[]> {+ const byFrom = new Map<string, HogFlowEdge[]>()+ for (const edge of edges) {+ const group = byFrom.get(edge.from) ?? []+ group.push(edge)+ byFrom.set(edge.from, group)+ }+ for (const group of byFrom.values()) {+ group.sort(compareEdges)+ }+ return byFrom+}++/**+ * Orders actions the way the canvas reads, top to bottom, by walking `edges` from the trigger.+ * The stored `actions` array is creation order, which is a different sequence for most templates.+ */+export function getOrderedActions(actions: HogFlowAction[], edges: HogFlowEdge[] | undefined): HogFlowAction[] {+ const trigger = actions.find((action) => action.type === 'trigger')+ if (!trigger) {+ return actions+ }++ const actionsById = new Map(actions.map((action) => [action.id, action]))+ const edgesByFrom = getSortedEdgesByFrom(edges ?? [])++ const reached: string[] = []+ const visited = new Set<string>([trigger.id])+ const queue: string[] = [trigger.id]+ // A cursor rather than `shift()`, so a template with many edges stays linear.+ for (let cursor = 0; cursor < queue.length; cursor++) {+ const id = queue[cursor]+ reached.push(id)+ for (const edge of edgesByFrom.get(id) ?? []) {+ if (!visited.has(edge.to)) {+ visited.add(edge.to)+ queue.push(edge.to)+ }+ }+ }++ // Keep any action the edges never reach, so a broken graph hides nothing+ const ordered = reached.map((id) => actionsById.get(id)).filter((action) => !!action)+ return [...ordered, ...actions.filter((action) => !visited.has(action.id))]+}