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): track how far people get in the workflow builder (#127106)

Michael Reichenbachbc119460ed40
diff --git a/products/workflows/frontend/Workflows/WorkflowEditorVisitTracker.tsx b/products/workflows/frontend/Workflows/WorkflowEditorVisitTracker.tsx
new file mode 100644
index 000000000000..0bc2d352c1ec
--- /dev/null
+++ b/products/workflows/frontend/Workflows/WorkflowEditorVisitTracker.tsx
@@ -0,0 +1,9 @@
+import { useMountedLogic } from 'kea'
+
+import { workflowEditorVisitLogic } from './workflowEditorVisitLogic'
+import { WorkflowLogicProps } from './workflowLogic'
+
+export function WorkflowEditorVisitTracker(props: WorkflowLogicProps): null {
+ useMountedLogic(workflowEditorVisitLogic(props))
+ return null
+}
diff --git a/products/workflows/frontend/Workflows/WorkflowScene.tsx b/products/workflows/frontend/Workflows/WorkflowScene.tsx
index 92f80a876be8..11ea71a15366 100644
--- a/products/workflows/frontend/Workflows/WorkflowScene.tsx
+++ b/products/workflows/frontend/Workflows/WorkflowScene.tsx
@@ -45,6 +45,7 @@ import {
import { WorkflowAiEmailDraftStatus } from './WorkflowAiEmailDraftStatus'
import { WorkflowAssets } from './WorkflowAssets'
import { WorkflowBroadcastMoveBanner } from './WorkflowBroadcastMoveBanner'
+import { WorkflowEditorVisitTracker } from './WorkflowEditorVisitTracker'
import { WorkflowEmailPauseBanner } from './WorkflowEmailPauseBanner'
import { WorkflowInvocations } from './WorkflowInvocations'
import { WorkflowLogicProps, workflowLogic } from './workflowLogic'
@@ -245,9 +246,12 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {
// A deep link to a tab the flag hides would leave LemonTabs with no active tab and a blank page.
const activeTab = tabs.some((tab) => tab?.key === currentTab) ? currentTab : 'workflow'
+ const showsBuilder = !editTemplateId && (!isSavedWorkflow || activeTab === 'workflow')
+
return (
<SceneContent className="h-full flex flex-col grow" data-attr="workflow-scene">
<BindLogic logic={workflowLogic} props={workflowProps}>
+ {showsBuilder && <WorkflowEditorVisitTracker {...workflowProps} />}
<WorkflowSceneHeader {...props} />
<WorkflowEmailPauseBanner />
{isSavedWorkflow && <WorkflowImportNotesBanner id={props.id!} />}
diff --git a/products/workflows/frontend/Workflows/workflowBuilderProgress.ts b/products/workflows/frontend/Workflows/workflowBuilderProgress.ts
new file mode 100644
index 000000000000..5990a02c8d72
--- /dev/null
+++ b/products/workflows/frontend/Workflows/workflowBuilderProgress.ts
@@ -0,0 +1,103 @@
+import { objectsEqual } from 'lib/utils/objects'
+
+import type { HogFlow, HogFlowAction, HogFlowActionValidationResult } from './hogflows/types'
+import type { WorkflowLogicProps } from './workflowLogic'
+
+export type WorkflowStartPath = 'template' | 'prefilled' | 'blank' | 'existing'
+
+export type WorkflowBuilderEdit = 'trigger' | 'step_added' | 'step_edited' | 'variables' | 'none'
+
+export type ValidationById = Record<string, HogFlowActionValidationResult | null>
+
+export function workflowStartPath(props: WorkflowLogicProps): WorkflowStartPath {
+ if (props.id && props.id !== 'new') {
+ return 'existing'
+ }
+ if (props.templateId) {
+ return 'template'
+ }
+ return props.triggerPrefill ? 'prefilled' : 'blank'
+}
+
+function isStep(action: HogFlowAction): boolean {
+ return action.type !== 'trigger' && action.type !== 'exit'
+}
+
+function triggerOf(workflow: HogFlow): HogFlowAction | undefined {
+ return workflow.actions.find((action) => action.type === 'trigger')
+}
+
+function stepKind(action: HogFlowAction): string {
+ return action.type === 'function' ? `function:${action.config.template_id}` : action.type
+}
+
+function countBy(values: string[]): Record<string, number> {
+ const counts: Record<string, number> = {}
+ for (const value of values) {
+ counts[value] = (counts[value] ?? 0) + 1
+ }
+ return counts
+}
+
+function branchCount(workflow: HogFlow): number {
+ const outgoing = countBy(workflow.edges.map((edge) => edge.from))
+ return Object.values(outgoing).filter((count) => count > 1).length
+}
+
+function isValid(action: HogFlowAction, validationById: ValidationById): boolean {
+ return validationById[action.id]?.valid ?? true
+}
+
+export interface BuilderProgress {
+ trigger_type: string | null
+ trigger_valid: boolean
+ step_count: number
+ invalid_step_count: number
+ invalid_step_types: string[]
+ step_types: Record<string, number>
+ branch_count: number
+}
+
+export function builderProgress(workflow: HogFlow, validationById: ValidationById): BuilderProgress {
+ const trigger = triggerOf(workflow)
+ const steps = workflow.actions.filter(isStep)
+ const invalidSteps = steps.filter((step) => !isValid(step, validationById))
+ return {
+ trigger_type: trigger?.type === 'trigger' ? (trigger.config.type ?? null) : null,
+ trigger_valid: !!trigger && isValid(trigger, validationById),
+ step_count: steps.length,
+ invalid_step_count: invalidSteps.length,
+ invalid_step_types: [...new Set(invalidSteps.map(stepKind))],
+ step_types: countBy(steps.map(stepKind)),
+ branch_count: branchCount(workflow),
+ }
+}
+
+function triggerSettings(workflow: HogFlow): Record<string, unknown> {
+ return {
+ config: triggerOf(workflow)?.config,
+ trigger_masking: workflow.trigger_masking,
+ conversion: workflow.conversion,
+ exit_condition: workflow.exit_condition,
+ email_sending_rate_limit: workflow.email_sending_rate_limit,
+ }
+}
+
+export function classifyEdit(before: HogFlow, after: HogFlow): WorkflowBuilderEdit | null {
+ if (after.actions.filter(isStep).length > before.actions.filter(isStep).length) {
+ return 'step_added'
+ }
+ if (!objectsEqual(triggerSettings(before), triggerSettings(after))) {
+ return 'trigger'
+ }
+ if (!objectsEqual(before.actions, after.actions) || !objectsEqual(before.edges, after.edges)) {
+ return 'step_edited'
+ }
+ return objectsEqual(before.variables, after.variables) ? null : 'variables'
+}
+
+export function addedStepKind(before: HogFlow, after: HogFlow): string | null {
+ const existingIds = new Set(before.actions.map((action) => action.id))
+ const added = after.actions.find((action) => isStep(action) && !existingIds.has(action.id))
+ return added ? stepKind(added) : null
+}
diff --git a/products/workflows/frontend/Workflows/workflowEditorVisitLogic.test.ts b/products/workflows/frontend/Workflows/workflowEditorVisitLogic.test.ts
new file mode 100644
index 000000000000..342b2827fcff
--- /dev/null
+++ b/products/workflows/frontend/Workflows/workflowEditorVisitLogic.test.ts
@@ -0,0 +1,434 @@
+import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
+
+import { urls } from 'scenes/urls'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { confirmCreateAsBroadcast } from '../Broadcasts/broadcastLifecycle'
+import { DEFAULT_STATE } from './hogflows/steps/components/rrule-helpers'
+import type { HogFlow, HogFlowAction } from './hogflows/types'
+import { workflowEditorVisitLogic } from './workflowEditorVisitLogic'
+import { NEW_WORKFLOW, TriggerAction, WorkflowLogicProps, workflowLogic } from './workflowLogic'
+
+jest.mock('../Broadcasts/broadcastLifecycle', () => ({
+ ...jest.requireActual('../Broadcasts/broadcastLifecycle'),
+ confirmCreateAsBroadcast: jest.fn(),
+}))
+
+const delayStep = (id: string, config: Record<string, unknown>): HogFlowAction =>
+ ({
+ id,
+ type: 'delay',
+ name: 'Wait',
+ description: '',
+ created_at: 0,
+ updated_at: 0,
+ config,
+ }) as HogFlowAction
+
+const branchStep = (id: string): HogFlowAction =>
+ ({
+ id,
+ type: 'conditional_branch',
+ name: 'Split',
+ description: '',
+ created_at: 0,
+ updated_at: 0,
+ config: { conditions: [{ filters: {} }] },
+ }) as HogFlowAction
+
+const slackStep = (id: string): HogFlowAction =>
+ ({
+ id,
+ type: 'function',
+ name: 'Slack',
+ description: '',
+ created_at: 0,
+ updated_at: 0,
+ config: { template_id: 'template-slack', inputs: {} },
+ }) as HogFlowAction
+
+const batchEmailSteps = (): Pick<HogFlow, 'actions' | 'edges'> => ({
+ actions: [
+ { ...delayStep('trigger_node', { type: 'batch', filters: {} }), type: 'trigger' },
+ { ...delayStep('email_node', { template_id: 'template-email', inputs: {} }), type: 'function_email' },
+ { ...delayStep('exit_node', { reason: 'Default exit' }), type: 'exit' },
+ ] as HogFlowAction[],
+ edges: [
+ { from: 'trigger_node', to: 'email_node', type: 'continue' },
+ { from: 'email_node', to: 'exit_node', type: 'continue' },
+ ],
+})
+
+const SAVED_ID = 'wf-visit-1'
+
+const PAGEVIEW_TRIGGER: TriggerAction['config'] = {
+ type: 'event',
+ filters: { events: [{ id: '$pageview', name: '$pageview', type: 'events', order: 0 }] },
+}
+
+describe('workflowEditorVisitLogic', () => {
+ let captureSpy: jest.SpyInstance
+
+ const captured = (event: string): Record<string, unknown>[] =>
+ captureSpy.mock.calls.filter(([name]) => name === event).map(([, properties]) => properties)
+
+ const openEditor = async (
+ props: WorkflowLogicProps
+ ): Promise<ReturnType<typeof workflowEditorVisitLogic.build>> => {
+ const editor = workflowLogic(props)
+ editor.mount()
+ await expectLogic(editor).toDispatchActions(['loadWorkflowSuccess'])
+ const visit = workflowEditorVisitLogic(props)
+ visit.mount()
+ return visit
+ }
+
+ const addStep = (props: WorkflowLogicProps, step: HogFlowAction): void => {
+ const editor = workflowLogic(props)
+ editor.actions.setWorkflowValues({ actions: [...editor.values.workflow.actions, step] })
+ }
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/hog_function_templates/': { results: [], count: 0 },
+ },
+ })
+ initKeaTests()
+ captureSpy = jest.spyOn(posthog, 'capture')
+ })
+
+ afterEach(() => {
+ captureSpy.mockRestore()
+ jest.useRealTimers()
+ })
+
+ it('reports how far a blank workflow got when the person leaves without saving', async () => {
+ jest.useFakeTimers({ now: new Date('2026-10-18T10:00:00Z'), doNotFake: ['nextTick', 'setImmediate'] })
+ const props = { id: 'new' }
+ const visit = await openEditor(props)
+
+ expect(captured('workflow editor opened')).toEqual([
+ {
+ start_path: 'blank',
+ template_id: null,
+ entry_source: null,
+ workflow_id: null,
+ status: 'draft',
+ },
+ ])
+
+ workflowLogic(props).actions.setWorkflowActionConfig('trigger_node', PAGEVIEW_TRIGGER)
+ addStep(props, delayStep('wait_valid', { delay_duration: '10m' }))
+ addStep(props, delayStep('wait_unset', {}))
+ jest.setSystemTime(new Date('2026-10-18T10:01:30Z'))
+ visit.unmount()
+
+ expect(captured('workflow editor left')).toEqual([
+ {
+ start_path: 'blank',
+ template_id: null,
+ entry_source: null,
+ workflow_id: null,
+ status: 'draft',
+ ever_saved: false,
+ trigger_type: 'event',
+ trigger_valid: true,
+ step_count: 2,
+ invalid_step_count: 1,
+ invalid_step_types: ['delay'],
+ step_types: { delay: 2 },
+ branch_count: 0,
+ last_edit: 'step_added',
+ last_added_step_type: 'delay',
+ enable_attempted: false,
+ seconds_open: 90,
+ },
+ ])
+ })
+
+ it('ends the visit to a new workflow at its first save, under the saved workflow', async () => {
+ const created = { ...NEW_WORKFLOW, id: SAVED_ID }
+ useMocks({
+ post: { '/api/projects/:team_id/hog_flows/': created },
+ get: { '/api/projects/:team_id/hog_flow_templates/tpl-1/': { ...created, id: 'tpl-1', name: 'Welcome' } },
+ })
+ const props = { id: 'new', templateId: 'tpl-1' }
+ const visit = await openEditor(props)
+
+ await expectLogic(workflowLogic(props), () => {
+ workflowLogic(props).actions.submitWorkflow()
+ }).toDispatchActions(['saveWorkflowSuccess'])
+ visit.unmount()
+
+ expect(captured('workflow draft created')).toEqual([
+ { workflow_id: SAVED_ID, entry_source: null, start_path: 'template', template_id: 'tpl-1' },
+ ])
+ expect(captured('workflow editor left')).toEqual([
+ expect.objectContaining({
+ start_path: 'template',
+ template_id: 'tpl-1',
+ workflow_id: SAVED_ID,
+ ever_saved: true,
+ }),
+ ])
+ })
+
+ it('counts a new broadcast as saved while the other workflows still move to broadcasts', async () => {
+ let releaseMove = (): void => {}
+ const moveHeld = new Promise<void>((resolve) => {
+ releaseMove = resolve
+ })
+ let markMoveRequested = (): void => {}
+ const moveRequested = new Promise<void>((resolve) => {
+ markMoveRequested = resolve
+ })
+ useMocks({
+ get: {
+ '/api/projects/:team_id/hog_flows/broadcast_conversion_candidates/': {
+ has_more: false,
+ results: [{ id: 'wf-other', name: 'Other', status: 'draft' }],
+ },
+ },
+ post: {
+ '/api/projects/:team_id/hog_flows/': { ...NEW_WORKFLOW, id: SAVED_ID, origin_product: 'broadcasts' },
+ '/api/projects/:team_id/hog_flows/:id/convert_to_broadcast/': async () => {
+ markMoveRequested()
+ await moveHeld
+ return [200, { origin_product: 'broadcasts' }]
+ },
+ },
+ })
+ jest.mocked(confirmCreateAsBroadcast).mockResolvedValue('broadcast_and_move')
+ const props = { id: 'new' }
+ const visit = await openEditor(props)
+ workflowLogic(props).actions.setWorkflowValues({
+ name: 'Monthly update',
+ exit_condition: 'exit_only_at_end',
+ ...batchEmailSteps(),
+ })
+
+ await expectLogic(workflowLogic(props), async () => {
+ workflowLogic(props).actions.submitWorkflow()
+ await moveRequested
+ visit.unmount()
+ releaseMove()
+ }).toDispatchActions(['saveWorkflowSuccess'])
+
+ expect(captured('workflow editor left')).toEqual([
+ expect.objectContaining({ start_path: 'blank', workflow_id: SAVED_ID, ever_saved: true }),
+ ])
+ })
+
+ it('reports the leave by beacon when the tab closes, and starts a new visit when the browser restores the page', async () => {
+ const visit = await openEditor({ id: 'new' })
+
+ window.dispatchEvent(new Event('pagehide'))
+ window.dispatchEvent(new PageTransitionEvent('pageshow', { persisted: true }))
+ visit.unmount()
+
+ expect(captured('workflow editor opened')).toHaveLength(2)
+ const leaves = captureSpy.mock.calls.filter(([name]) => name === 'workflow editor left')
+ expect(leaves).toEqual([
+ ['workflow editor left', expect.objectContaining({ start_path: 'blank' }), { transport: 'sendBeacon' }],
+ ['workflow editor left', expect.objectContaining({ start_path: 'blank' }), undefined],
+ ])
+ })
+
+ it.each([
+ [
+ 'moving a step',
+ 'step_edited',
+ (editor: ReturnType<typeof workflowLogic.build>) =>
+ editor.actions.setWorkflowValues({
+ edges: [
+ { from: 'trigger_node', to: 'wait_valid', type: 'continue' },
+ { from: 'wait_valid', to: 'exit_node', type: 'continue' },
+ ],
+ }),
+ ],
+ [
+ 'changing how often the schedule repeats',
+ 'trigger',
+ (editor: ReturnType<typeof workflowLogic.build>) =>
+ editor.actions.setScheduleState({ ...DEFAULT_STATE, frequency: 'daily' }),
+ ],
+ [
+ 'picking a schedule start',
+ 'trigger',
+ (editor: ReturnType<typeof workflowLogic.build>) =>
+ editor.actions.setScheduleStartsAtFromPicker('2026-05-01T10:00:00'),
+ ],
+ [
+ 'changing the schedule timezone',
+ 'trigger',
+ (editor: ReturnType<typeof workflowLogic.build>) => editor.actions.setScheduleTimezone('US/Eastern', 'UTC'),
+ ],
+ [
+ 'turning schedule repeats on',
+ 'trigger',
+ (editor: ReturnType<typeof workflowLogic.build>) => editor.actions.setScheduleRepeating(true),
+ ],
+ [
+ 'limiting how often the trigger fires per person',
+ 'trigger',
+ (editor: ReturnType<typeof workflowLogic.build>) =>
+ editor.actions.setWorkflowValue('trigger_masking', {
+ ttl: 1800,
+ hash: '{person_id}',
+ bytecode: [],
+ threshold: null,
+ }),
+ ],
+ [
+ 'setting a conversion goal',
+ 'trigger',
+ (editor: ReturnType<typeof workflowLogic.build>) =>
+ editor.actions.setWorkflowValue('conversion', { window: '7d', filters: [] }),
+ ],
+ [
+ 'changing the exit condition',
+ 'trigger',
+ (editor: ReturnType<typeof workflowLogic.build>) =>
+ editor.actions.setWorkflowValue('exit_condition', 'exit_on_conversion'),
+ ],
+ [
+ 'pacing email sends',
+ 'trigger',
+ (editor: ReturnType<typeof workflowLogic.build>) =>
+ editor.actions.setWorkflowValue('email_sending_rate_limit', { count: 100, period: 'hour' }),
+ ],
+ [
+ 'adding a workflow variable',
+ 'variables',
+ (editor: ReturnType<typeof workflowLogic.build>) =>
+ editor.actions.setWorkflowInfo({
+ variables: [{ key: 'plan', label: 'Plan', type: 'string', default: 'free' }],
+ }),
+ ],
+ [
+ 'replaying edits made while a save was in flight',
+ 'variables',
+ (editor: ReturnType<typeof workflowLogic.build>) => {
+ const saved = editor.values.workflow
+ editor.actions.setWorkflowValues({ actions: [...saved.actions, slackStep('notify')] })
+ editor.actions.setWorkflowInfo({
+ variables: [{ key: 'plan', label: 'Plan', type: 'string', default: 'free' }],
+ })
+ const { actions, edges, variables } = editor.values.workflow
+ editor.actions.resetWorkflow(saved)
+ editor.actions.setWorkflowValues({ actions, edges, variables })
+ },
+ ],
+ [
+ 'adding back a variable after discarding it',
+ 'variables',
+ async (editor: ReturnType<typeof workflowLogic.build>) => {
+ const saved = editor.values.workflow
+ const variables: HogFlow['variables'] = [
+ { key: 'plan', label: 'Plan', type: 'string', default: 'free' },
+ ]
+ editor.actions.setWorkflowInfo({ variables })
+ editor.actions.resetWorkflow(saved)
+ await Promise.resolve()
+ editor.actions.setScheduleRepeating(true)
+ editor.actions.setWorkflowInfo({ variables })
+ },
+ ],
+ [
+ 'adding a schedule',
+ 'trigger',
+ (editor: ReturnType<typeof workflowLogic.build>) => editor.actions.addSchedule(),
+ ],
+ [
+ 'removing a schedule',
+ 'trigger',
+ (editor: ReturnType<typeof workflowLogic.build>) => editor.actions.deleteSchedule('schedule-1'),
+ ],
+ ])('reports %s as a %s edit', async (_, lastEdit, edit) => {
+ const draft = {
+ ...NEW_WORKFLOW,
+ id: SAVED_ID,
+ actions: [...NEW_WORKFLOW.actions, delayStep('wait_valid', { delay_duration: '10m' })],
+ }
+ useMocks({ get: { [`/api/projects/:team_id/hog_flows/${SAVED_ID}/`]: draft } })
+ const props = { id: SAVED_ID }
+ const visit = await openEditor(props)
+
+ await edit(workflowLogic(props))
+ visit.unmount()
+
+ expect(captured('workflow editor left')).toEqual([expect.objectContaining({ last_edit: lastEdit })])
+ })
+
+ it('reports the progress a person discards when they confirm leaving with unsaved changes', async () => {
+ const confirmLeave = jest.spyOn(window, 'confirm').mockReturnValue(true)
+ useMocks({ get: { [`/api/projects/:team_id/hog_flows/${SAVED_ID}/`]: { ...NEW_WORKFLOW, id: SAVED_ID } } })
+ const props = { id: SAVED_ID }
+ router.actions.push(urls.workflow(SAVED_ID, 'workflow'))
+ const visit = await openEditor(props)
+
+ addStep(props, delayStep('wait_valid', { delay_duration: '10m' }))
+ router.actions.push(urls.workflow(SAVED_ID, 'metrics'))
+ visit.unmount()
+
+ expect(confirmLeave).toHaveBeenCalledTimes(1)
+ confirmLeave.mockRestore()
+ expect(captured('workflow editor left')).toEqual([
+ expect.objectContaining({ step_count: 1, step_types: { delay: 1 }, last_edit: 'step_added' }),
+ ])
+ })
+
+ it('reports which kinds of steps the workflow holds and where it branches', async () => {
+ const branched = {
+ ...NEW_WORKFLOW,
+ id: SAVED_ID,
+ actions: [...NEW_WORKFLOW.actions, branchStep('split'), delayStep('wait_valid', { delay_duration: '10m' })],
+ edges: [
+ { from: 'trigger_node', to: 'split', type: 'continue' },
+ { from: 'split', to: 'wait_valid', type: 'branch', index: 0 },
+ { from: 'split', to: 'exit_node', type: 'continue' },
+ { from: 'wait_valid', to: 'exit_node', type: 'continue' },
+ ],
+ } as HogFlow
+ useMocks({ get: { [`/api/projects/:team_id/hog_flows/${SAVED_ID}/`]: branched } })
+ const props = { id: SAVED_ID }
+ const visit = await openEditor(props)
+
+ addStep(props, slackStep('notify'))
+ visit.unmount()
+
+ expect(captured('workflow editor left')).toEqual([
+ expect.objectContaining({
+ step_types: { conditional_branch: 1, delay: 1, 'function:template-slack': 1 },
+ branch_count: 1,
+ last_added_step_type: 'function:template-slack',
+ }),
+ ])
+ })
+
+ it('reports which steps block a draft from going live', async () => {
+ const draft = {
+ ...NEW_WORKFLOW,
+ id: SAVED_ID,
+ actions: [...NEW_WORKFLOW.actions, delayStep('wait_unset', {})],
+ }
+ useMocks({ get: { [`/api/projects/:team_id/hog_flows/${SAVED_ID}/`]: draft } })
+ const props = { id: SAVED_ID }
+ const visit = await openEditor(props)
+
+ workflowLogic(props).actions.saveWorkflowPartial({ status: 'active' })
+ visit.unmount()
+
+ expect(captured('workflow enable blocked')).toEqual([
+ { workflow_id: SAVED_ID, invalid_step_count: 1, invalid_step_types: ['delay'] },
+ ])
+ expect(captured('workflow editor left')).toEqual([
+ expect.objectContaining({ status: 'draft', enable_attempted: true }),
+ ])
+ })
+})
diff --git a/products/workflows/frontend/Workflows/workflowEditorVisitLogic.ts b/products/workflows/frontend/Workflows/workflowEditorVisitLogic.ts
new file mode 100644
index 000000000000..6ab346d93219
--- /dev/null
+++ b/products/workflows/frontend/Workflows/workflowEditorVisitLogic.ts
@@ -0,0 +1,277 @@
+import { MakeLogicType, connect, events, kea, key, listeners, path, props } from 'kea'
+import posthog, { CaptureOptions } from 'posthog-js'
+
+import type { HogFlow, HogFlowActionValidationResult } from './hogflows/types'
+import {
+ BuilderProgress,
+ WorkflowBuilderEdit,
+ WorkflowStartPath,
+ addedStepKind,
+ builderProgress,
+ classifyEdit,
+ workflowStartPath,
+} from './workflowBuilderProgress'
+import { WorkflowLogicProps, workflowLogic, workflowLogicKey } from './workflowLogic'
+
+interface EditorVisit {
+ startPath: WorkflowStartPath
+ templateId: string | null
+ entrySource: string | null
+ openedAt: number
+ lastEdit: WorkflowBuilderEdit
+ lastAddedStepType: string | null
+ enableAttempted: boolean
+ discardedProgress: BuilderProgress | null
+}
+
+const KEEP_LISTENING_WHILE_THE_PAGE_HIDES_ON_LEAVE = false
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface workflowEditorVisitLogicValues {
+ actionValidationErrorsById: Record<string, HogFlowActionValidationResult | null> // workflowLogic
+ workflow: HogFlow // workflowLogic
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface workflowEditorVisitLogicActions {
+ addSchedule: () => {
+ value: true
+ } // workflowLogic
+ deleteSchedule: (scheduleId: string) => {
+ scheduleId: string
+ } // workflowLogic
+ enableBlocked: () => {
+ value: true
+ } // workflowLogic
+ leaveConfirmed: () => {
+ value: true
+ } // workflowLogic
+ resetWorkflow: (values?: HogFlow | undefined) => {
+ values?: HogFlow
+ } // workflowLogic
+ saveWorkflowPartial: (workflow: Partial<HogFlow>) => {
+ workflow: Partial<HogFlow>
+ } // workflowLogic
+ setScheduleRepeating: (repeating: boolean) => {
+ repeating: boolean
+ } // workflowLogic
+ setScheduleStartsAtFromPicker: (pickerDate: string | null) => {
+ pickerDate: string | null
+ } // workflowLogic
+ setScheduleState: (
+ scheduleState: import('./hogflows/steps/components/rrule-helpers').ScheduleState,
+ source?: 'natural_language' | 'picker' | undefined
+ ) => {
+ scheduleState: import('./hogflows/steps/components/rrule-helpers').ScheduleState
+ source: 'natural_language' | 'picker'
+ } // workflowLogic
+ setScheduleTimezone: (
+ timezone: string,
+ previousTimezone?: string | undefined
+ ) => {
+ previousTimezone: string | undefined
+ timezone: string
+ } // workflowLogic
+ setWorkflowValue: (
+ key: import('node_modules/kea-forms/lib').FieldName,
+ value: any
+ ) => {
+ name: import('node_modules/kea-forms/lib').FieldName
+ value: any
+ } // workflowLogic
+ setWorkflowValues: (values: import('node_modules/kea-forms/lib').DeepPartial<HogFlow>) => {
+ values: import('node_modules/kea-forms/lib').DeepPartial<HogFlow>
+ } // workflowLogic
+ workflowCreated: (workflowId: string) => {
+ workflowId: string
+ } // workflowLogic
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface workflowEditorVisitLogicMeta {
+ key: string
+}
+
+export type workflowEditorVisitLogicType = MakeLogicType<
+ workflowEditorVisitLogicValues,
+ workflowEditorVisitLogicActions,
+ WorkflowLogicProps,
+ workflowEditorVisitLogicMeta
+>
+
+export const workflowEditorVisitLogic = kea<workflowEditorVisitLogicType>([
+ props({} as WorkflowLogicProps),
+ key(workflowLogicKey),
+ path((key) => ['products', 'workflows', 'frontend', 'Workflows', 'workflowEditorVisitLogic', key]),
+ connect((props: WorkflowLogicProps) => ({
+ values: [workflowLogic(props), ['workflow', 'actionValidationErrorsById']],
+ actions: [
+ workflowLogic(props),
+ [
+ 'setWorkflowValue',
+ 'setWorkflowValues',
+ 'resetWorkflow',
+ 'saveWorkflowPartial',
+ 'workflowCreated',
+ 'enableBlocked',
+ 'leaveConfirmed',
+ 'setScheduleState',
+ 'setScheduleStartsAtFromPicker',
+ 'setScheduleTimezone',
+ 'setScheduleRepeating',
+ 'addSchedule',
+ 'deleteSchedule',
+ ],
+ ],
+ })),
+ listeners(({ cache, props, values }) => {
+ const recordEdit = (visit: EditorVisit, edit: WorkflowBuilderEdit): void => {
+ visit.lastEdit = edit
+ visit.discardedProgress = null
+ }
+ const recordFormEdit = (previousState: any): void => {
+ const editor = workflowLogic(props)
+ const before = editor.selectors.workflow(previousState)
+ const formBeforeReset = cache.formBeforeReset as HogFlow | null
+ cache.formBeforeReset = null
+ // A save response resets the form, then puts back the edits made while it was in flight.
+ if (formBeforeReset && classifyEdit(formBeforeReset, editor.values.workflow) === null) {
+ return
+ }
+ const edit = classifyEdit(before, editor.values.workflow)
+ const visit = cache.visit as EditorVisit | null
+ if (!visit || !edit) {
+ return
+ }
+ recordEdit(visit, edit)
+ if (edit === 'step_added') {
+ visit.lastAddedStepType = addedStepKind(before, editor.values.workflow)
+ }
+ }
+ const recordScheduleEdit = (): void => {
+ const visit = cache.visit as EditorVisit | null
+ if (visit) {
+ recordEdit(visit, 'trigger')
+ }
+ }
+ return {
+ setWorkflowValue: (_, __, ___, previousState) => recordFormEdit(previousState),
+ setWorkflowValues: (_, __, ___, previousState) => recordFormEdit(previousState),
+ resetWorkflow: (_, __, ___, previousState) => {
+ cache.formBeforeReset = workflowLogic(props).selectors.workflow(previousState)
+ // The save response replays in the same tick, so an edit after a discard or reload is never a replay.
+ queueMicrotask(() => {
+ cache.formBeforeReset = null
+ })
+ },
+ setScheduleState: recordScheduleEdit,
+ setScheduleStartsAtFromPicker: recordScheduleEdit,
+ setScheduleTimezone: recordScheduleEdit,
+ setScheduleRepeating: recordScheduleEdit,
+ addSchedule: recordScheduleEdit,
+ deleteSchedule: recordScheduleEdit,
+ saveWorkflowPartial: ({ workflow }) => {
+ const visit = cache.visit as EditorVisit | null
+ if (visit && workflow.status === 'active') {
+ visit.enableAttempted = true
+ }
+ },
+ enableBlocked: () => {
+ const { invalid_step_count, invalid_step_types } = builderProgress(
+ values.workflow,
+ values.actionValidationErrorsById
+ )
+ // pinned: analytics event name
+ posthog.capture('workflow enable blocked', {
+ workflow_id: props.id ?? null,
+ invalid_step_count,
+ invalid_step_types,
+ })
+ },
+ workflowCreated: ({ workflowId }) => {
+ cache.createdWorkflowId = workflowId
+ },
+ leaveConfirmed: () => {
+ const visit = cache.visit as EditorVisit | null
+ if (visit) {
+ visit.discardedProgress = builderProgress(values.workflow, values.actionValidationErrorsById)
+ }
+ },
+ }
+ }),
+ events(({ cache, props, values }) => {
+ const savedWorkflowId = (): string | null =>
+ props.id && props.id !== 'new' ? props.id : ((cache.createdWorkflowId as string | null | undefined) ?? null)
+
+ const visitProperties = (visit: EditorVisit): Record<string, unknown> => ({
+ start_path: visit.startPath,
+ template_id: visit.templateId,
+ entry_source: visit.entrySource,
+ workflow_id: savedWorkflowId(),
+ status: values.workflow.status,
+ })
+
+ const reportLeave = (options?: CaptureOptions): void => {
+ const visit = cache.visit as EditorVisit | null
+ if (!visit) {
+ return
+ }
+ cache.visit = null
+ posthog.capture(
+ // pinned: analytics event name
+ 'workflow editor left',
+ {
+ ...visitProperties(visit),
+ ever_saved: savedWorkflowId() !== null,
+ ...(visit.discardedProgress ?? builderProgress(values.workflow, values.actionValidationErrorsById)),
+ last_edit: visit.lastEdit,
+ last_added_step_type: visit.lastAddedStepType,
+ enable_attempted: visit.enableAttempted,
+ seconds_open: Math.round((Date.now() - visit.openedAt) / 1000),
+ },
+ options
+ )
+ }
+
+ const startVisit = (): void => {
+ const visit: EditorVisit = {
+ startPath: workflowStartPath(props),
+ templateId: props.templateId ?? null,
+ entrySource: props.entrySource ?? null,
+ openedAt: Date.now(),
+ lastEdit: 'none',
+ lastAddedStepType: null,
+ enableAttempted: false,
+ discardedProgress: null,
+ }
+ cache.visit = visit
+ // pinned: analytics event name
+ posthog.capture('workflow editor opened', visitProperties(visit))
+ }
+
+ return {
+ afterMount: () => {
+ cache.disposables.add(
+ () => {
+ const onPageHide = (): void => reportLeave({ transport: 'sendBeacon' })
+ const onPageShow = (event: PageTransitionEvent): void => {
+ if (event.persisted && !cache.visit) {
+ startVisit()
+ }
+ }
+ window.addEventListener('pagehide', onPageHide)
+ window.addEventListener('pageshow', onPageShow)
+ return () => {
+ window.removeEventListener('pagehide', onPageHide)
+ window.removeEventListener('pageshow', onPageShow)
+ }
+ },
+ 'pageLifecycle',
+ { pauseOnPageHidden: KEEP_LISTENING_WHILE_THE_PAGE_HIDES_ON_LEAVE }
+ )
+ startVisit()
+ },
+ beforeUnmount: () => reportLeave(),
+ }
+ }),
+])
diff --git a/products/workflows/frontend/Workflows/workflowLogic.ts b/products/workflows/frontend/Workflows/workflowLogic.ts
index 3c066f25cb8b..2543cc0f48a6 100644
--- a/products/workflows/frontend/Workflows/workflowLogic.ts
+++ b/products/workflows/frontend/Workflows/workflowLogic.ts
@@ -80,6 +80,7 @@ import {
} from './hogflows/types'
import { openPublishConfirmDialog } from './PublishImpactDialog'
import { ResourceSaveQueue } from './resourceSaveQueue'
+import { workflowStartPath } from './workflowBuilderProgress'
import { prepareWorkflowDuplicate } from './workflowDuplication'
import {
prefilledEmailContent,
@@ -102,6 +103,10 @@ export interface WorkflowLogicProps {
entrySource?: string
}
+export function workflowLogicKey(props: WorkflowLogicProps): string {
+ return `workflow-${props.id || 'new'}-${props.templateId || 'default'}-${props.editTemplateId || 'default'}-${props.triggerPrefill || 'default'}-${props.emailPrefill || 'default'}`
+}
+
export const TRIGGER_NODE_ID = 'trigger_node'
export const EXIT_NODE_ID = 'exit_node'
@@ -408,9 +413,15 @@ export interface workflowLogicActions {
duplicate: () => {
value: true
}
+ enableBlocked: () => {
+ value: true
+ }
keepMyWorkflowVersion: () => {
value: true
}
+ leaveConfirmed: () => {
+ value: true
+ }
loadAiEmailDraft: (request: EmailDraftRequestApi) => EmailDraftRequestApi
loadAiEmailDraftFailure: (
error: string,
@@ -3033,6 +3044,9 @@ export interface workflowLogicActions {
triggerManualWorkflow: (variables: Record<string, any>) => {
variables: Record<string, any>
}
+ workflowCreated: (workflowId: string) => {
+ workflowId: string
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -3288,10 +3302,7 @@ function getSaveQueue(
export const workflowLogic = kea<workflowLogicType>([
path((key) => ['products', 'workflows', 'frontend', 'Workflows', 'workflowLogic', key]),
props({ id: 'new' } as WorkflowLogicProps),
- key(
- (props) =>
- `workflow-${props.id || 'new'}-${props.templateId || 'default'}-${props.editTemplateId || 'default'}-${props.triggerPrefill || 'default'}-${props.emailPrefill || 'default'}`
- ),
+ key(workflowLogicKey),
connect(() => ({
values: [
userLogic,
@@ -3355,6 +3366,9 @@ export const workflowLogic = kea<workflowLogicType>([
publishDraft: true,
confirmPublishDraft: (confirmToken: string) => ({ confirmToken }),
discardDraft: true,
+ enableBlocked: true,
+ workflowCreated: (workflowId: string) => ({ workflowId }),
+ leaveConfirmed: true,
confirmDiscardDraft: true,
setDraftActionPending: (pending: 'publish' | 'discard' | null) => ({ pending }),
replayDeferredResourceEdited: true,
@@ -3469,6 +3483,7 @@ export const workflowLogic = kea<workflowLogicType>([
...updates,
...(createsBroadcast ? { origin_product: 'broadcasts' } : {}),
} as unknown as Parameters<typeof hogFlowsCreate>[1])) as unknown as HogFlow
+ actions.workflowCreated(result.id)
if (props.templateId) {
posthog.capture('hog_flow_created_from_template', {
@@ -3503,6 +3518,8 @@ export const workflowLogic = kea<workflowLogicType>([
posthog.capture('workflow draft created', {
workflow_id: result.id,
entry_source: props.entrySource ?? null,
+ start_path: workflowStartPath(props),
+ template_id: props.templateId ?? null,
})
}
return result
@@ -4504,6 +4521,7 @@ export const workflowLogic = kea<workflowLogicType>([
const merged = { ...(keepsFormEdits && stored ? withStagedDraft(stored) : values.workflow), ...workflow }
if (merged.status === 'active' && values.workflowHasActionErrors) {
lemonToast.error('Fix all errors before enabling')
+ actions.enableBlocked()
return
}
// This is the one path that means to change the lifecycle. The loader reads the flag
@@ -5017,6 +5035,7 @@ export const workflowLogic = kea<workflowLogicType>([
},
message: 'Leave workflow?\nChanges you made will be discarded.',
onConfirm: () => {
+ logic.actions.leaveConfirmed()
if (logic.values.originalWorkflow) {
logic.actions.resetWorkflow(logic.values.originalWorkflow)
}