: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): add auto-save with debounce and last saved indicator (#57953)
Meikel Ratzd7cc6bc4da82
diff --git a/products/workflows/frontend/Workflows/WorkflowScene.tsx b/products/workflows/frontend/Workflows/WorkflowScene.tsxindex 8fe7290276c6..3358f5b996fb 100644--- a/products/workflows/frontend/Workflows/WorkflowScene.tsx+++ b/products/workflows/frontend/Workflows/WorkflowScene.tsx@@ -1,13 +1,15 @@import clsx from 'clsx'import { BindLogic, useValues } from 'kea'import { router } from 'kea-router'+import { useEffect, useState } from 'react'-import { SpinnerOverlay } from '@posthog/lemon-ui'+import { Spinner, SpinnerOverlay } from '@posthog/lemon-ui'import { ActivityLog } from 'lib/components/ActivityLog/ActivityLog'import { FlaggedFeature } from 'lib/components/FlaggedFeature'import { NotFound } from 'lib/components/NotFound'import { FEATURE_FLAGS } from 'lib/constants'+import { dayjs } from 'lib/dayjs'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { LemonTab, LemonTabs } from 'lib/lemon-ui/LemonTabs'import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'@@ -28,6 +30,27 @@ import { WorkflowMetrics } from './WorkflowMetrics'import { WorkflowSceneHeader } from './WorkflowSceneHeader'import { WorkflowSceneLogicProps, WorkflowTab, workflowSceneLogic } from './workflowSceneLogic'+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+}++function RelativeTime({ timestamp }: { timestamp: string }): JSX.Element {+ const [, setTick] = useState(0)+ useEffect(() => {+ const interval = setInterval(() => setTick((t) => t + 1), 30000)+ return () => clearInterval(interval)+ }, [])+ return <>{dayjs(timestamp).fromNow()}</>+}+export const scene: SceneExport<WorkflowSceneLogicProps> = {component: WorkflowScene,logic: workflowSceneLogic,@@ -53,7 +76,8 @@ 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 } = useValues(logic)+ const showSaving = useDebouncedValue(isAutoSavePending || workflowLoading, 1000)const showBlockedRuns = useFeatureFlag('WORKFLOWS_REPLAY_BLOCKED_RUNS')@@ -124,6 +148,17 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {onChange={(tab) => router.actions.push(urls.workflow(props.id ?? 'new', tab))}tabs={tabs}sceneInset+ rightSlot={+ showSaving ? (+ <span className="text-xs text-tertiary flex items-center gap-1">+ <Spinner textColored /> Saving…+ </span>+ ) : lastSavedAt ? (+ <span className="text-xs text-tertiary">+ Last saved <RelativeTime timestamp={lastSavedAt} />+ </span>+ ) : 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..06144b33d9d9--- /dev/null+++ b/products/workflows/frontend/Workflows/workflowLogic.autosave.test.ts@@ -0,0 +1,190 @@+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('marks isAutoSave true on the auto-save path', async () => {+ jest.useFakeTimers()++ logic.actions.setWorkflowValue('name', 'Edited')+ await jest.advanceTimersByTimeAsync(3500)++ expect(logic.values.isAutoSave).toBe(true)+ 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)+ })+ })++ describe('beforeUnmount', () => {+ it('flushes pending changes when the logic unmounts', async () => {+ initKeaTests()+ logic = workflowLogic({ id: WORKFLOW_ID, tabId: 'default' })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadWorkflowSuccess'])++ logic.actions.setWorkflowValue('name', 'Unflushed edit')+ expect(logic.values.workflowChanged).toBe(true)++ logic.unmount()++ await new Promise((resolve) => setTimeout(resolve, 0))+ expect(updateCalls).toBe(1)+ })++ it('does not flush when there are no changes', async () => {+ initKeaTests()+ logic = workflowLogic({ id: WORKFLOW_ID, tabId: 'default' })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadWorkflowSuccess'])++ logic.unmount()+ await new Promise((resolve) => setTimeout(resolve, 0))+ expect(updateCalls).toBe(0)+ })+ })+})diff --git a/products/workflows/frontend/Workflows/workflowLogic.ts b/products/workflows/frontend/Workflows/workflowLogic.tsindex d119341594b2..b3183990cfc5 100644--- a/products/workflows/frontend/Workflows/workflowLogic.ts+++ b/products/workflows/frontend/Workflows/workflowLogic.ts@@ -1,4 +1,4 @@-import { actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { actions, afterMount, beforeUnmount, 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'@@ -176,6 +176,8 @@ export const workflowLogic = kea<workflowLogicType>([}),discardChanges: true,duplicate: true,+ autoSaveWorkflow: true,+ markAutoSave: (isAutoSave: boolean) => ({ isAutoSave }),}),loaders(({ props, values }) => ({originalWorkflow: [@@ -332,6 +334,30 @@ 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,+ saveWorkflowSuccess: () => false,+ saveWorkflowFailure: () => false,+ resetWorkflow: () => false,+ },+ ],}),selectors({logicProps: [() => [(_, props: WorkflowLogicProps) => props], (props): WorkflowLogicProps => props],@@ -590,48 +616,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)@@ -687,6 +719,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 +735,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 +748,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 +756,32 @@ 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()+ },+ autoSaveWorkflow: async (_, breakpoint) => {+ await breakpoint(3000)++ if (!props.id || props.id === 'new') {+ return+ }+ if (props.editTemplateId) {+ return+ }+ if (!values.workflowChanged) {+ return+ }+ if (values.workflowHasErrors) {+ return+ }+ if (values.workflow.status === 'active' && values.workflowHasActionErrors) {+ return+ }++ actions.markAutoSave(true)+ actions.saveWorkflow(values.workflow)},duplicate: async () => {const workflow = values.originalWorkflow@@ -804,4 +865,12 @@ export const workflowLogic = kea<workflowLogicType>([actions.loadWorkflow()actions.loadHogFunctionTemplatesById()}),+ beforeUnmount(({ values, props }) => {+ if (props.id && props.id !== 'new' && values.workflowChanged && !values.workflowHasErrors) {+ const workflow = sanitizeWorkflow(values.workflow, values.hogFunctionTemplatesById)+ api.hogFlows.updateHogFlow(props.id, workflow).catch((e) => {+ console.error('Failed to auto-save workflow on unmount', e)+ })+ }+ }),])