: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): workflow autosave (#58152)
Meikel Ratza27aef66d61e
diff --git a/frontend/src/lib/components/LastSavedIndicator.tsx b/frontend/src/lib/components/LastSavedIndicator.tsxnew file mode 100644index 000000000000..c5e6ca1eb4d4--- /dev/null+++ b/frontend/src/lib/components/LastSavedIndicator.tsx@@ -0,0 +1,9 @@+import { TZLabel } from 'lib/components/TZLabel'++export function LastSavedIndicator({ timestamp }: { timestamp: string }): JSX.Element {+ return (+ <span className="text-xs text-tertiary">+ Last saved <TZLabel time={timestamp} />+ </span>+ )+}diff --git a/frontend/src/lib/hooks/useDebouncedValue.ts b/frontend/src/lib/hooks/useDebouncedValue.tsnew file mode 100644index 000000000000..827b505cc2ec--- /dev/null+++ b/frontend/src/lib/hooks/useDebouncedValue.ts@@ -0,0 +1,18 @@+import { useEffect, useState } from 'react'++/**+ * Returns a debounced version of the given value. Truthy transitions are+ * delayed by `delayMs`; falsy transitions are applied immediately.+ * Useful for delaying the appearance of loading indicators.+ */+export function useDebouncedValue<T>(value: T, delayMs: number): T {+ const [debounced, setDebounced] = useState(value)+ useEffect(() => {+ if (value) {+ const timer = setTimeout(() => setDebounced(value), delayMs)+ return () => clearTimeout(timer)+ }+ setDebounced(value)+ }, [value, delayMs])+ return debounced+}diff --git a/products/workflows/frontend/Workflows/WorkflowScene.tsx b/products/workflows/frontend/Workflows/WorkflowScene.tsxindex 0f3b0d949788..6447047033ae 100644--- a/products/workflows/frontend/Workflows/WorkflowScene.tsx+++ b/products/workflows/frontend/Workflows/WorkflowScene.tsx@@ -1,12 +1,16 @@import clsx from 'clsx'-import { BindLogic, useValues } from 'kea'+import { BindLogic, useActions, useValues } from 'kea'import { router } from 'kea-router'-import { SpinnerOverlay } from '@posthog/lemon-ui'+import { IconInfo } from '@posthog/icons'+import { LemonSwitch, Spinner, SpinnerOverlay } from '@posthog/lemon-ui'import { ActivityLog } from 'lib/components/ActivityLog/ActivityLog'+import { LastSavedIndicator } from 'lib/components/LastSavedIndicator'import { NotFound } from 'lib/components/NotFound'+import { useDebouncedValue } from 'lib/hooks/useDebouncedValue'import { LemonTab, LemonTabs } from 'lib/lemon-ui/LemonTabs'+import { Tooltip } from 'lib/lemon-ui/Tooltip'import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'import { SceneExport } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'@@ -48,7 +52,10 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {const batchJobsLogic = batchWorkflowJobsLogic({ id: workflowSceneProps.id })const logic = workflowLogic({ id: props.id, tabId: props.tabId, templateId, editTemplateId })- const { workflowLoading, originalWorkflow } = useValues(logic)+ const { workflowLoading, originalWorkflow, lastSavedAt, isAutoSavePending, autoSaveEnabled } = useValues(logic)+ const { setAutoSaveEnabled } = useActions(logic)+ const showSaving = useDebouncedValue(isAutoSavePending || workflowLoading, 1000)+ const isDraft = originalWorkflow?.status === 'draft'// Attach child logics to the scene logic so they persist across tab switchesuseAttachedLogic(batchJobsLogic, sceneLogic)@@ -107,6 +114,35 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {onChange={(tab) => router.actions.push(urls.workflow(props.id ?? 'new', tab))}tabs={tabs}sceneInset+ rightSlot={+ isDraft ? (+ <span className="flex items-center gap-3">+ {autoSaveEnabled && showSaving ? (+ <span className="text-xs text-tertiary flex items-center gap-1">+ <Spinner textColored /> Saving…+ </span>+ ) : lastSavedAt ? (+ <LastSavedIndicator timestamp={lastSavedAt} />+ ) : null}+ <span className="flex items-center gap-1">+ <LemonSwitch+ checked={autoSaveEnabled}+ onChange={setAutoSaveEnabled}+ label="Auto-save"+ size="small"+ />+ <Tooltip+ title="Auto-save is only available for draft workflows. Active workflows require an explicit save to prevent unintended changes to live behavior."+ placement="bottom"+ >+ <IconInfo className="text-tertiary size-4" />+ </Tooltip>+ </span>+ </span>+ ) : lastSavedAt ? (+ <LastSavedIndicator timestamp={lastSavedAt} />+ ) : null+ }className={clsx({'flex flex-col grow [&>div]:flex [&>div]:flex-col [&>div]:grow': currentTab === 'workflow',})}diff --git a/products/workflows/frontend/Workflows/workflowLogic.autosave.test.ts b/products/workflows/frontend/Workflows/workflowLogic.autosave.test.tsnew file mode 100644index 000000000000..adfcfda96907--- /dev/null+++ b/products/workflows/frontend/Workflows/workflowLogic.autosave.test.ts@@ -0,0 +1,288 @@+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { HogFlow } from './hogflows/types'+import { workflowLogic } from './workflowLogic'++const WORKFLOW_ID = 'wf-autosave-1'++const makeWorkflow = (overrides: Partial<HogFlow> = {}): HogFlow => ({+ id: WORKFLOW_ID,+ name: 'Autosave test',+ actions: [+ {+ id: 'trigger_node',+ type: 'trigger',+ name: 'Trigger',+ description: '',+ created_at: 0,+ updated_at: 0,+ config: { type: 'event', filters: {} },+ },+ {+ id: 'exit_node',+ type: 'exit',+ name: 'Exit',+ description: '',+ created_at: 0,+ updated_at: 0,+ config: { reason: 'Default exit' },+ },+ ],+ edges: [{ from: 'trigger_node', to: 'exit_node', type: 'continue' }],+ conversion: { window_minutes: null, filters: [] },+ exit_condition: 'exit_only_at_end',+ version: 1,+ status: 'draft',+ team_id: 1,+ trigger: { type: 'event', filters: {} } as HogFlow['trigger'],+ created_at: '2026-05-01T00:00:00.000Z',+ updated_at: '2026-05-01T00:00:00.000Z',+ ...overrides,+})++describe('workflowLogic auto-save', () => {+ let logic: ReturnType<typeof workflowLogic.build>+ let updateCalls: number+ const workflow = makeWorkflow()++ beforeEach(() => {+ updateCalls = 0+ useMocks({+ get: {+ '/api/environments/:team_id/hog_flows/:id/': workflow,+ '/api/projects/:team_id/hog_function_templates/': { results: [], count: 0 },+ },+ patch: {+ '/api/environments/:team_id/hog_flows/:id/': () => {+ updateCalls += 1+ return [200, workflow]+ },+ },+ })+ })++ afterEach(() => {+ jest.useRealTimers()+ })++ describe('debouncing existing workflow', () => {+ beforeEach(async () => {+ initKeaTests()+ logic = workflowLogic({ id: WORKFLOW_ID, tabId: 'default' })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadWorkflowSuccess'])+ })++ it('collapses rapid edits into a single save after 3s', async () => {+ jest.useFakeTimers()++ logic.actions.setWorkflowValue('name', 'Edit 1')+ logic.actions.setWorkflowValue('name', 'Edit 2')+ logic.actions.setWorkflowValue('name', 'Edit 3')++ await jest.advanceTimersByTimeAsync(2000)+ expect(updateCalls).toBe(0)++ await jest.advanceTimersByTimeAsync(1500)+ await expectLogic(logic).toDispatchActions(['saveWorkflow', 'saveWorkflowSuccess'])+ expect(updateCalls).toBe(1)+ })++ it('updates lastSavedAt on auto-save success', async () => {+ jest.useFakeTimers()++ expect(logic.values.lastSavedAt).toBe('2026-05-01T00:00:00.000Z')++ logic.actions.setWorkflowValue('name', 'Edited')+ await jest.advanceTimersByTimeAsync(3500)+ await expectLogic(logic).toDispatchActions(['saveWorkflowSuccess'])++ expect(logic.values.lastSavedAt).not.toBe('2026-05-01T00:00:00.000Z')+ expect(logic.values.lastSavedAt).not.toBeNull()+ })++ it('resets isAutoSave after auto-save completes', async () => {+ jest.useFakeTimers()++ logic.actions.setWorkflowValue('name', 'Edited')+ await jest.advanceTimersByTimeAsync(3500)+ await expectLogic(logic).toDispatchActions(['saveWorkflowSuccess'])++ expect(logic.values.isAutoSave).toBe(false)+ expect(updateCalls).toBe(1)+ })+ })++ describe('skip cases', () => {+ it.each([+ ['new workflow', { id: 'new' as const }],+ ['template editing', { id: WORKFLOW_ID, editTemplateId: 'tpl-1' }],+ ])('does not auto-save for %s', async (_label, props) => {+ initKeaTests()+ logic = workflowLogic({ ...props, tabId: 'default' })+ logic.mount()++ jest.useFakeTimers()+ logic.actions.autoSaveWorkflow()+ await jest.advanceTimersByTimeAsync(3500)++ expect(updateCalls).toBe(0)+ })++ it('does not auto-save when there are validation errors', async () => {+ initKeaTests()+ logic = workflowLogic({ id: WORKFLOW_ID, tabId: 'default' })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadWorkflowSuccess'])++ jest.useFakeTimers()++ logic.actions.setWorkflowValue('name', '')+ await jest.advanceTimersByTimeAsync(3500)++ expect(logic.values.workflowHasErrors).toBe(true)+ expect(updateCalls).toBe(0)+ })++ it('does not auto-save when nothing has changed', async () => {+ initKeaTests()+ logic = workflowLogic({ id: WORKFLOW_ID, tabId: 'default' })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadWorkflowSuccess'])++ jest.useFakeTimers()+ logic.actions.autoSaveWorkflow()+ await jest.advanceTimersByTimeAsync(3500)++ expect(updateCalls).toBe(0)+ })++ it('clears isAutoSavePending when auto-save is skipped', async () => {+ initKeaTests()+ logic = workflowLogic({ id: WORKFLOW_ID, tabId: 'default' })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadWorkflowSuccess'])++ jest.useFakeTimers()++ // Dispatch auto-save without actual changes — guard will skip+ logic.actions.autoSaveWorkflow()+ expect(logic.values.isAutoSavePending).toBe(true)++ await jest.advanceTimersByTimeAsync(3500)+ expect(logic.values.isAutoSavePending).toBe(false)+ expect(updateCalls).toBe(0)+ })++ it('does not auto-save workflow loaded as active', async () => {+ const activeWorkflow = makeWorkflow({ status: 'active' })+ useMocks({+ get: {+ '/api/environments/:team_id/hog_flows/:id/': activeWorkflow,+ '/api/projects/:team_id/hog_function_templates/': { results: [], count: 0 },+ },+ patch: {+ '/api/environments/:team_id/hog_flows/:id/': () => {+ updateCalls += 1+ return [200, activeWorkflow]+ },+ },+ })++ initKeaTests()+ logic = workflowLogic({ id: WORKFLOW_ID, tabId: 'default' })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadWorkflowSuccess'])++ jest.useFakeTimers()+ logic.actions.setWorkflowValue('name', 'Edited active')+ await jest.advanceTimersByTimeAsync(3500)++ expect(updateCalls).toBe(0)+ })+ })++ describe('auto-save toggle', () => {+ beforeEach(async () => {+ initKeaTests()+ logic = workflowLogic({ id: WORKFLOW_ID, tabId: 'default' })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadWorkflowSuccess'])+ })++ it('does not auto-save when toggle is disabled', async () => {+ jest.useFakeTimers()++ logic.actions.setAutoSaveEnabled(false)+ logic.actions.setWorkflowValue('name', 'Edited')+ await jest.advanceTimersByTimeAsync(3500)++ expect(updateCalls).toBe(0)+ })++ it('resets isAutoSavePending when toggle is disabled', async () => {+ logic.actions.setWorkflowValue('name', 'Edited')+ expect(logic.values.isAutoSavePending).toBe(true)++ logic.actions.setAutoSaveEnabled(false)+ expect(logic.values.isAutoSavePending).toBe(false)+ })++ it('triggers auto-save when toggle is re-enabled with pending changes', async () => {+ jest.useFakeTimers()++ logic.actions.setAutoSaveEnabled(false)+ logic.actions.setWorkflowValue('name', 'Edited while off')+ await jest.advanceTimersByTimeAsync(3500)+ expect(updateCalls).toBe(0)++ logic.actions.setAutoSaveEnabled(true)+ await jest.advanceTimersByTimeAsync(3500)+ await expectLogic(logic).toDispatchActions(['saveWorkflow', 'saveWorkflowSuccess'])+ expect(updateCalls).toBe(1)+ })++ it('does not auto-save active workflows', async () => {+ jest.useFakeTimers()++ logic.actions.setWorkflowValue('status', 'active')+ logic.actions.setWorkflowValue('name', 'Edited active')+ await jest.advanceTimersByTimeAsync(3500)++ expect(updateCalls).toBe(0)+ })+ })++ describe('navigation guard', () => {+ it('does not fire save on unmount (no silent flush)', async () => {+ initKeaTests()+ logic = workflowLogic({ id: WORKFLOW_ID, tabId: 'default' })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadWorkflowSuccess'])++ logic.actions.setWorkflowValue('name', 'Unsaved edit')+ expect(logic.values.hasUnsavedChanges).toBe(true)++ logic.unmount()+ await new Promise((resolve) => setTimeout(resolve, 0))+ expect(updateCalls).toBe(0)+ })++ it('does not warn on navigation for new workflows', async () => {+ // The beforeUnload guard skips when id is 'new', even if+ // the form has unsaved changes (e.g. freshly created draft).+ initKeaTests()+ logic = workflowLogic({ id: 'new', tabId: 'default' })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadWorkflowSuccess'])++ logic.actions.setWorkflowValue('name', 'My new workflow')+ expect(logic.values.hasUnsavedChanges).toBe(true)+ // Guard condition: props.id === 'new' → skip+ expect(logic.props.id).toBe('new')+ })+ })+})diff --git a/products/workflows/frontend/Workflows/workflowLogic.ts b/products/workflows/frontend/Workflows/workflowLogic.tsindex d119341594b2..a2c0b390da2a 100644--- a/products/workflows/frontend/Workflows/workflowLogic.ts+++ b/products/workflows/frontend/Workflows/workflowLogic.ts@@ -1,7 +1,7 @@import { actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { DeepPartialMap, ValidationErrorType, forms } from 'kea-forms'import { lazyLoaders, loaders } from 'kea-loaders'-import { router } from 'kea-router'+import { beforeUnload, router } from 'kea-router'import posthog from 'posthog-js'import { LemonDialog } from '@posthog/lemon-ui'@@ -176,6 +176,10 @@ export const workflowLogic = kea<workflowLogicType>([}),discardChanges: true,duplicate: true,+ autoSaveWorkflow: true,+ markAutoSave: (isAutoSave: boolean) => ({ isAutoSave }),+ setAutoSaveEnabled: (enabled: boolean) => ({ enabled }),+ clearAutoSavePending: true,}),loaders(({ props, values }) => ({originalWorkflow: [@@ -332,6 +336,38 @@ export const workflowLogic = kea<workflowLogicType>([setSchedules: () => ({ picker: false, natural_language: false }),},],+ isAutoSave: [+ false as boolean,+ {+ markAutoSave: (_, { isAutoSave }) => isAutoSave,+ submitWorkflow: () => false,+ saveWorkflowPartial: () => false,+ },+ ],+ lastSavedAt: [+ null as string | null,+ {+ saveWorkflowSuccess: () => dayjs().toISOString(),+ loadWorkflowSuccess: (_, { originalWorkflow }) => originalWorkflow?.updated_at ?? null,+ },+ ],+ isAutoSavePending: [+ false as boolean,+ {+ autoSaveWorkflow: () => true,+ clearAutoSavePending: () => false,+ saveWorkflowSuccess: () => false,+ saveWorkflowFailure: () => false,+ resetWorkflow: () => false,+ setAutoSaveEnabled: (_, { enabled }) => (!enabled ? false : _),+ },+ ],+ autoSaveEnabled: [+ true as boolean,+ {+ setAutoSaveEnabled: (_, { enabled }) => enabled,+ },+ ],}),selectors({logicProps: [() => [(_, props: WorkflowLogicProps) => props], (props): WorkflowLogicProps => props],@@ -590,48 +626,54 @@ export const workflowLogic = kea<workflowLogicType>([}},saveWorkflowSuccess: async ({ originalWorkflow }) => {- // Save pending schedule changes- const workflowId = originalWorkflow.id- const pendingSchedule = values.pendingSchedule- const existingScheduleId = values.currentSchedule?.id- const hasScheduleChanges = pendingSchedule !== false && !!workflowId+ const isAutoSave = values.isAutoSave++ if (!isAutoSave) {+ // Save pending schedule changes (only on manual save)+ const workflowId = originalWorkflow.id+ const pendingSchedule = values.pendingSchedule+ const existingScheduleId = values.currentSchedule?.id+ const hasScheduleChanges = pendingSchedule !== false && !!workflowId++ if (hasScheduleChanges) {+ try {+ if (pendingSchedule === null && existingScheduleId) {+ await api.hogFlows.deleteHogFlowSchedule(workflowId, existingScheduleId)+ } else if (pendingSchedule !== null && existingScheduleId) {+ await api.hogFlows.updateHogFlowSchedule(workflowId, existingScheduleId, pendingSchedule)+ } else if (pendingSchedule !== null) {+ await api.hogFlows.createHogFlowSchedule(workflowId, pendingSchedule)+ }- if (hasScheduleChanges) {- try {- if (pendingSchedule === null && existingScheduleId) {- await api.hogFlows.deleteHogFlowSchedule(workflowId, existingScheduleId)- } else if (pendingSchedule !== null && existingScheduleId) {- await api.hogFlows.updateHogFlowSchedule(workflowId, existingScheduleId, pendingSchedule)- } else if (pendingSchedule !== null) {- await api.hogFlows.createHogFlowSchedule(workflowId, pendingSchedule)- }+ if (pendingSchedule !== null) {+ posthog.capture('workflows schedule saved', {+ workflow_id: workflowId,+ configured_via_picker: values.scheduleConfigSources.picker,+ configured_via_natural_language: values.scheduleConfigSources.natural_language,+ })+ }- if (pendingSchedule !== null) {- posthog.capture('workflows schedule saved', {- workflow_id: workflowId,- configured_via_picker: values.scheduleConfigSources.picker,- configured_via_natural_language: values.scheduleConfigSources.natural_language,- })+ const schedules = await api.hogFlows.getHogFlowSchedules(workflowId)+ actions.setSchedules(schedules)+ } catch (e) {+ console.error('Failed to save schedule', e)+ lemonToast.error('Workflow saved, but schedule could not be updated')}+ }- const schedules = await api.hogFlows.getHogFlowSchedules(workflowId)- actions.setSchedules(schedules)- } catch (e) {- console.error('Failed to save schedule', e)- lemonToast.error('Workflow saved, but schedule could not be updated')+ lemonToast.success('Workflow saved')++ if (props.id === 'new' && originalWorkflow.id) {+ router.actions.replace(+ urls.workflow(+ originalWorkflow.id,+ workflowSceneLogic.findMounted()?.values.currentTab || 'workflow'+ )+ )}}const tasksToMarkAsCompleted: SetupTaskId[] = []- lemonToast.success('Workflow saved')- if (props.id === 'new' && originalWorkflow.id) {- router.actions.replace(- urls.workflow(- originalWorkflow.id,- workflowSceneLogic.findMounted()?.values.currentTab || 'workflow'- )- )- }// Mark workflow creation task as completed everytime it's saved for completenesstasksToMarkAsCompleted.push(SetupTaskId.CreateFirstWorkflow)@@ -667,6 +709,7 @@ export const workflowLogic = kea<workflowLogicType>([}actions.resetWorkflow(originalWorkflow)+ actions.markAutoSave(false)},discardChanges: () => {if (!values.originalWorkflow) {@@ -687,6 +730,7 @@ export const workflowLogic = kea<workflowLogicType>([},setWorkflowInfo: async ({ workflow }) => {actions.setWorkflowValues(workflow)+ actions.autoSaveWorkflow()},setWorkflowActionConfig: async ({ actionId, config }) => {const action = values.workflow.actions.find((action) => action.id === actionId)@@ -702,6 +746,7 @@ export const workflowLogic = kea<workflowLogicType>([}actions.setWorkflowValues(changes)+ actions.autoSaveWorkflow()},partialSetWorkflowActionConfig: async ({ actionId, config }) => {const action = values.workflow.actions.find((action) => action.id === actionId)@@ -714,6 +759,7 @@ export const workflowLogic = kea<workflowLogicType>([setWorkflowAction: async ({ actionId, action }) => {const newActions = values.workflow.actions.map((a) => (a.id === actionId ? action : a))actions.setWorkflowValues({ actions: newActions })+ actions.autoSaveWorkflow()},setWorkflowActionEdges: async ({ actionId, edges }) => {// Helper method - Replaces all edges related to the action with the new edges@@ -721,6 +767,35 @@ export const workflowLogic = kea<workflowLogicType>([const newEdges = values.workflow.edges.filter((e) => !actionEdges.includes(e))actions.setWorkflowValues({ edges: [...newEdges, ...edges] })+ actions.autoSaveWorkflow()+ },+ setWorkflowValue: () => {+ actions.autoSaveWorkflow()+ },+ setAutoSaveEnabled: ({ enabled }) => {+ if (enabled && values.workflowChanged) {+ actions.autoSaveWorkflow()+ }+ },+ autoSaveWorkflow: async (_, breakpoint) => {+ await breakpoint(3000)++ const shouldSkip =+ !values.autoSaveEnabled ||+ !props.id ||+ props.id === 'new' ||+ !!props.editTemplateId ||+ values.workflow.status === 'active' ||+ !values.workflowChanged ||+ values.workflowHasErrors++ if (shouldSkip) {+ actions.clearAutoSavePending()+ return+ }++ actions.markAutoSave(true)+ actions.saveWorkflow(values.workflow)},duplicate: async () => {const workflow = values.originalWorkflow@@ -804,4 +879,27 @@ export const workflowLogic = kea<workflowLogicType>([actions.loadWorkflow()actions.loadHogFunctionTemplatesById()}),+ beforeUnload((logic) => ({+ enabled: (newLocation) => {+ if (!logic.props.id || logic.props.id === 'new') {+ return false+ }+ if (logic.props.editTemplateId) {+ return false+ }+ if (!logic.values.hasUnsavedChanges) {+ return false+ }+ if (newLocation && newLocation.pathname === router.values.location.pathname) {+ return false+ }+ return true+ },+ message: 'Leave workflow?\nChanges you made will be discarded.',+ onConfirm: () => {+ if (logic.values.originalWorkflow) {+ logic.actions.resetWorkflow(logic.values.originalWorkflow)+ }+ },+ })),])