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.

fix(workflows): stop auto-save fighting the person editing the workflow (#91486)

Harley Alexander2404411a0454
diff --git a/products/workflows/frontend/Workflows/WorkflowSceneHeader.test.tsx b/products/workflows/frontend/Workflows/WorkflowSceneHeader.test.tsx
new file mode 100644
index 000000000000..1b6242fc0f36
--- /dev/null
+++ b/products/workflows/frontend/Workflows/WorkflowSceneHeader.test.tsx
@@ -0,0 +1,101 @@
+import '@testing-library/jest-dom'
+
+import { act, cleanup, render } from '@testing-library/react'
+import { BindLogic, Provider } from 'kea'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { HogFlow } from './hogflows/types'
+import { workflowLogic } from './workflowLogic'
+import { WorkflowSceneHeader } from './WorkflowSceneHeader'
+
+const WORKFLOW_ID = 'wf-header-1'
+
+const ACTIVE_WITH_DRAFT: HogFlow = {
+ id: WORKFLOW_ID,
+ name: 'Header 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: 'active',
+ 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',
+ draft: { name: 'Header test', actions: [], edges: [] },
+ draft_updated_at: '2026-05-01T00:01:00.000Z',
+}
+
+// The label and order of the buttons a person points at, as rendered.
+const toolbar = (): string[] =>
+ Array.from(document.querySelectorAll('[data-attr="workflow-publish"],[data-attr="workflow-save"]')).map(
+ (el) => `${el.getAttribute('data-attr')}:${el.textContent ?? ''}`
+ )
+
+describe('WorkflowSceneHeader', () => {
+ let logic: ReturnType<typeof workflowLogic.build>
+
+ beforeEach(async () => {
+ useMocks({
+ get: {
+ '/api/environments/:team_id/hog_flows/:id/': ACTIVE_WITH_DRAFT,
+ '/api/environments/:team_id/hog_flows/:id/schedules': { results: [] },
+ '/api/projects/:team_id/hog_function_templates/': { results: [], count: 0 },
+ },
+ })
+ initKeaTests()
+ logic = workflowLogic({ id: WORKFLOW_ID })
+ logic.mount()
+ await act(async () => {
+ await logic.asyncActions.loadWorkflow()
+ })
+ })
+
+ afterEach(() => {
+ cleanup()
+ logic?.unmount()
+ })
+
+ it('keeps the same buttons in the same order when edits make the form dirty', () => {
+ render(
+ <Provider>
+ <BindLogic logic={workflowLogic} props={{ id: WORKFLOW_ID }}>
+ <WorkflowSceneHeader id={WORKFLOW_ID} />
+ </BindLogic>
+ </Provider>
+ )
+
+ // Auto-save has just landed: a draft is staged and the form is clean.
+ const clean = toolbar()
+ expect(clean).toEqual(['workflow-save:Save draft', 'workflow-publish:Publish'])
+
+ act(() => {
+ logic.actions.setWorkflowValue('name', 'Still typing')
+ })
+
+ // The pointer has not moved, so neither has the button under it.
+ expect(toolbar()).toEqual(clean)
+ })
+})
diff --git a/products/workflows/frontend/Workflows/WorkflowSceneHeader.tsx b/products/workflows/frontend/Workflows/WorkflowSceneHeader.tsx
index 6e0c39de579a..0f7549dfb84f 100644
--- a/products/workflows/frontend/Workflows/WorkflowSceneHeader.tsx
+++ b/products/workflows/frontend/Workflows/WorkflowSceneHeader.tsx
@@ -8,6 +8,7 @@ import { LemonButton, LemonDivider } from '@posthog/lemon-ui'
import { AccessControlAction } from 'lib/components/AccessControlAction'
import { SceneMenuBarFileItems } from 'lib/components/Scenes/SceneMenuBarFileItems'
import { FEATURE_FLAGS } from 'lib/constants'
+import { LemonMenuOverlay } from 'lib/lemon-ui/LemonMenu/LemonMenu'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
import { urls } from 'scenes/urls'
@@ -38,6 +39,9 @@ export const WorkflowSceneHeader = (props: WorkflowSceneLogicProps = {}): JSX.El
workflowLoading,
workflowHasErrors,
workflowUserAccessLevel,
+ publishDisabledReason,
+ discardDisabledReason,
+ showDraftActions,
} = useValues(workflowLogic)
const {
saveWorkflowPartial,
@@ -290,80 +294,86 @@ export const WorkflowSceneHeader = (props: WorkflowSceneLogicProps = {}): JSX.El
>
Update template
</LemonButton>
- ) : isSavedWorkflow && hasStagedDraft && !hasUnsavedChanges ? (
- // Staged and clean: publishing is the next act, so it takes the primary slot.
+ ) : (
+ // Both buttons hold a fixed slot for the whole edit. Auto-save used to
+ // swap this group between "Save draft" and "Publish" every few seconds,
+ // which moved a different action under a pointer that had not left the
+ // button.
<>
<AccessControlAction
resourceType={AccessControlResourceType.Workflow}
minAccessLevel={AccessControlLevel.Editor}
- userAccessLevel={workflowUserAccessLevel ?? undefined}
+ userAccessLevel={
+ props.id === 'new' ? undefined : (workflowUserAccessLevel ?? undefined)
+ }
>
<LemonButton
- data-attr="workflow-discard-draft"
- type="secondary"
+ data-attr="workflow-save"
+ type={hasStagedDraft && !hasUnsavedChanges ? 'secondary' : 'primary'}
size="small"
- status="danger"
- onClick={() => discardDraft()}
- loading={draftActionPending === 'discard'}
+ htmlType="submit"
+ form="workflow"
+ onClick={submitWorkflow}
+ loading={isWorkflowSubmitting}
disabledReason={
- draftActionPending === 'publish' ? 'Publishing is in progress' : undefined
+ workflowHasErrors
+ ? 'Some fields still need work'
+ : isCreatedFromTemplate
+ ? undefined
+ : hasUnsavedChanges
+ ? undefined
+ : 'No changes to save'
}
>
- Discard draft
+ {props.id === 'new'
+ ? 'Create as draft'
+ : workflow?.status === 'active'
+ ? 'Save draft'
+ : 'Save'}
</LemonButton>
</AccessControlAction>
- <AccessControlAction
- resourceType={AccessControlResourceType.Workflow}
- minAccessLevel={AccessControlLevel.Editor}
- userAccessLevel={workflowUserAccessLevel ?? undefined}
- >
- <LemonButton
- data-attr="workflow-publish"
- type="primary"
- size="small"
- onClick={() => publishDraft()}
- loading={draftActionPending === 'publish'}
- disabledReason={
- draftActionPending === 'discard' ? 'Discarding is in progress' : undefined
- }
+ {showDraftActions && (
+ <AccessControlAction
+ resourceType={AccessControlResourceType.Workflow}
+ minAccessLevel={AccessControlLevel.Editor}
+ userAccessLevel={workflowUserAccessLevel ?? undefined}
>
- Publish
- </LemonButton>
- </AccessControlAction>
+ <LemonButton
+ data-attr="workflow-publish"
+ type={hasStagedDraft && !hasUnsavedChanges ? 'primary' : 'secondary'}
+ size="small"
+ onClick={() => publishDraft()}
+ loading={draftActionPending === 'publish'}
+ disabledReason={publishDisabledReason}
+ // Discarding is rare and destructive, so it sits in the
+ // menu rather than next to the button a person aims for.
+ sideAction={{
+ 'data-attr': 'workflow-draft-actions',
+ 'aria-label': 'More draft actions',
+ dropdown: {
+ placement: 'bottom-end',
+ overlay: (
+ <LemonMenuOverlay
+ items={[
+ {
+ label: 'Discard draft',
+ icon: <IconTrash />,
+ status: 'danger',
+ onClick: () => discardDraft(),
+ disabledReason: discardDisabledReason,
+ 'data-attr': 'workflow-discard-draft',
+ },
+ ]}
+ />
+ ),
+ },
+ }}
+ >
+ Publish
+ </LemonButton>
+ </AccessControlAction>
+ )}
</>
- ) : (
- <AccessControlAction
- resourceType={AccessControlResourceType.Workflow}
- minAccessLevel={AccessControlLevel.Editor}
- userAccessLevel={
- props.id === 'new' ? undefined : (workflowUserAccessLevel ?? undefined)
- }
- >
- <LemonButton
- data-attr="workflow-save"
- type="primary"
- size="small"
- htmlType="submit"
- form="workflow"
- onClick={submitWorkflow}
- loading={isWorkflowSubmitting}
- disabledReason={
- workflowHasErrors
- ? 'Some fields still need work'
- : isCreatedFromTemplate
- ? undefined
- : hasUnsavedChanges
- ? undefined
- : 'No changes to save'
- }
- >
- {props.id === 'new'
- ? 'Create as draft'
- : workflow?.status === 'active'
- ? 'Save draft'
- : 'Save'}
- </LemonButton>
- </AccessControlAction>
)}
</>
}
diff --git a/products/workflows/frontend/Workflows/workflowLogic.autosave.test.ts b/products/workflows/frontend/Workflows/workflowLogic.autosave.test.ts
index 002f99223c75..540481ba9d15 100644
--- a/products/workflows/frontend/Workflows/workflowLogic.autosave.test.ts
+++ b/products/workflows/frontend/Workflows/workflowLogic.autosave.test.ts
@@ -3,6 +3,8 @@ import { expectLogic } from 'kea-test-utils'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
+import { resourceEditedLogic } from 'products/notifications/frontend/resourceEditedLogic'
+
import { HogFlow } from './hogflows/types'
import { workflowLogic } from './workflowLogic'
@@ -442,6 +444,342 @@ describe('workflowLogic auto-save', () => {
})
})
+ describe('a save that overlaps another save', () => {
+ let serverUpdatedAt: string
+ let rejected: number
+ let releaseFirstPatch: (() => void) | null
+ let firstPatchSeen: Promise<void>
+ let scheduleWrites: number
+ let events: string[]
+
+ beforeEach(async () => {
+ serverUpdatedAt = '2026-05-01T00:00:00.000Z'
+ rejected = 0
+ scheduleWrites = 0
+ events = []
+ releaseFirstPatch = null
+ let markFirstPatchSeen = (): void => {}
+ firstPatchSeen = new Promise<void>((resolve) => {
+ markFirstPatchSeen = resolve
+ })
+ let patches = 0
+
+ useMocks({
+ get: {
+ '/api/environments/:team_id/hog_flows/:id/': () => [
+ 200,
+ makeWorkflow({ updated_at: serverUpdatedAt }),
+ ],
+ '/api/environments/:team_id/hog_flows/:id/schedules': { results: [] },
+ },
+ post: {
+ '/api/environments/:team_id/hog_flows/:id/schedules': () => {
+ scheduleWrites += 1
+ events.push('schedule')
+ return [200, { id: 'sched-1', rrule: 'FREQ=DAILY', starts_at: '2026-07-01T00:00:00.000Z' }]
+ },
+ },
+ patch: {
+ // Stands in for perform_update, which rejects a write whose base_updated_at is
+ // older than the stored stamp with a 409.
+ '/api/environments/:team_id/hog_flows/:id/': async ({ request }) => {
+ const body = (await request.json()) as Record<string, any>
+ patches += 1
+ // Hold the first save open so the second one overlaps it, the way a slow
+ // save on a large workflow does.
+ if (patches === 1) {
+ await new Promise<void>((resolve) => {
+ releaseFirstPatch = resolve
+ markFirstPatchSeen()
+ })
+ }
+ if (body.base_updated_at && body.base_updated_at < serverUpdatedAt) {
+ rejected += 1
+ return [409, { detail: 'stale_update', code: 'stale_update' }]
+ }
+ serverUpdatedAt = new Date(Date.parse(serverUpdatedAt) + 1000).toISOString()
+ events.push('patch')
+ return [200, makeWorkflow({ updated_at: serverUpdatedAt, name: body.name })]
+ },
+ },
+ })
+
+ initKeaTests()
+ logic = workflowLogic({ id: WORKFLOW_ID })
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadWorkflowSuccess'])
+ })
+
+ it('does not raise the conflict banner at the only editor', async () => {
+ logic.actions.setWorkflowValue('name', 'Renamed by me')
+ await expectLogic(logic).toDispatchActions(['saveWorkflow'])
+ await firstPatchSeen
+
+ // The user clicks "Save draft" while the auto-save is still in flight.
+ logic.actions.submitWorkflow()
+ await new Promise((resolve) => setTimeout(resolve, 50))
+
+ releaseFirstPatch?.()
+ await new Promise((resolve) => setTimeout(resolve, 200))
+
+ expect({ rejected, banner: logic.values.externallyEdited }).toEqual({ rejected: 0, banner: false })
+ })
+
+ it('runs the manual-only save work once when a manual save queues behind an auto-save', async () => {
+ // Both saves now land, where the second used to 409. The auto-save must not pick up the
+ // manual save's label and repeat its side effects, which include creating a schedule.
+ logic.actions.setScheduleStartsAt('2026-07-01T00:00:00.000Z')
+
+ logic.actions.setWorkflowValue('name', 'Renamed by me')
+ await expectLogic(logic).toDispatchActions(['saveWorkflow'])
+ await firstPatchSeen
+
+ logic.actions.submitWorkflow()
+ await new Promise((resolve) => setTimeout(resolve, 50))
+
+ releaseFirstPatch?.()
+ await new Promise((resolve) => setTimeout(resolve, 300))
+
+ // The schedule belongs to the manual save, so it is written once and only after that
+ // save lands. Attributing it to the auto-save puts it between the two patches.
+ expect(events).toEqual(['patch', 'patch', 'schedule'])
+ expect(scheduleWrites).toBe(1)
+ })
+
+ it("ignores the second queued save's own edit event", async () => {
+ // The loader's loading flag is one boolean, so the first save clears it while the
+ // second still runs. An echo of the second save arriving in that window used to read
+ // as somebody else's edit, which is the false banner this whole change removes.
+ resourceEditedLogic.mount()
+ // Both saves are held, so the second is provably still open when the echo arrives.
+ const release: (() => void)[] = []
+ let held = 0
+ let sawSecond = (): void => {}
+ const secondPatchSeen = new Promise<void>((resolve) => {
+ sawSecond = resolve
+ })
+ let loads = 0
+ useMocks({
+ get: {
+ '/api/environments/:team_id/hog_flows/:id/': () => {
+ loads += 1
+ return [200, makeWorkflow({ updated_at: serverUpdatedAt })]
+ },
+ },
+ patch: {
+ '/api/environments/:team_id/hog_flows/:id/': async () => {
+ held += 1
+ if (held === 2) {
+ sawSecond()
+ }
+ await new Promise<void>((resolve) => release.push(resolve))
+ return [200, makeWorkflow({ updated_at: '2026-05-01T00:00:0' + held + '.000Z' })]
+ },
+ },
+ })
+
+ logic.actions.setWorkflowValue('name', 'Renamed by me')
+ await expectLogic(logic).toDispatchActions(['saveWorkflow'])
+ await new Promise((resolve) => setTimeout(resolve, 50))
+
+ logic.actions.submitWorkflow()
+ await new Promise((resolve) => setTimeout(resolve, 50))
+
+ release[0]()
+ await expectLogic(logic).toDispatchActions(['saveWorkflowSuccess'])
+ await secondPatchSeen
+
+ // The first save has landed and the second is still open. Its own emit arrives now.
+ resourceEditedLogic.actions.resourceEdited({
+ notification_type: 'resource_edited',
+ team_id: 1,
+ resource_type: 'HogFlow',
+ resource_id: WORKFLOW_ID,
+ updated_at: '2027-01-01T00:00:00.000Z',
+ actor_user_id: 1,
+ })
+ await new Promise((resolve) => setTimeout(resolve, 200))
+
+ // Reacting here means treating this editor's own in-flight save as somebody else's:
+ // a reload that resets the form under the person, or the banner.
+ expect({ reloads: loads, banner: logic.values.externallyEdited }).toEqual({
+ reloads: 0,
+ banner: false,
+ })
+
+ release[1]()
+ await new Promise((resolve) => setTimeout(resolve, 300))
+ })
+
+ it('keeps the form submitting until the queued manual save lands', async () => {
+ logic.actions.setWorkflowValue('name', 'Renamed by me')
+ await expectLogic(logic).toDispatchActions(['saveWorkflow'])
+ await firstPatchSeen
+
+ logic.actions.submitWorkflow()
+ await new Promise((resolve) => setTimeout(resolve, 50))
+
+ // The save button reads this. While it stays true the button cannot fire a second save.
+ expect(logic.values.isWorkflowSubmitting).toBe(true)
+
+ releaseFirstPatch?.()
+ await new Promise((resolve) => setTimeout(resolve, 200))
+
+ expect(logic.values.isWorkflowSubmitting).toBe(false)
+ })
+ })
+
+ describe('draft actions on an active workflow', () => {
+ const staged = makeWorkflow({
+ status: 'active',
+ draft: { name: 'Autosave test', actions: [], edges: [] },
+ draft_updated_at: '2026-05-01T00:01:00.000Z',
+ })
+
+ beforeEach(async () => {
+ useMocks({
+ get: { '/api/environments/:team_id/hog_flows/:id/': staged },
+ patch: { '/api/environments/:team_id/hog_flows/:id/': () => [200, staged] },
+ })
+ initKeaTests()
+ logic = workflowLogic({ id: WORKFLOW_ID })
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadWorkflowSuccess'])
+ })
+
+ it('keeps the draft actions mounted and blocks publish while edits are unsaved', () => {
+ logic.actions.setWorkflowValue('name', 'Still typing')
+
+ expect(logic.values.hasUnsavedChanges).toBe(true)
+ // Hiding these on a dirty form moved a different action under the pointer every time
+ // auto-save landed.
+ expect(logic.values.showDraftActions).toBe(true)
+ // Publish promotes the staged draft, not what is on screen.
+ expect(logic.values.publishDisabledReason).toBe('Save your changes first')
+ // Discarding reloads the workflow, which would drop the edits still in the form.
+ expect(logic.values.discardDisabledReason).toBe('Save or clear your changes first')
+ })
+
+ it('allows publish once auto-save clears the unsaved edits', async () => {
+ jest.useFakeTimers()
+
+ logic.actions.setWorkflowValue('name', 'Edited')
+ await jest.advanceTimersByTimeAsync(3500)
+ await expectLogic(logic).toDispatchActions(['saveWorkflowSuccess'])
+
+ expect(logic.values.publishDisabledReason).toBeUndefined()
+ expect(logic.values.discardDisabledReason).toBeUndefined()
+ })
+
+ it('still stages content when a queued save undoes the edit the previous save wrote', async () => {
+ // Comparing against kea's copy would compare this edit with the state from two saves
+ // ago. The undo then looks like no change at all, so its payload carries no content and
+ // the draft keeps the step the user just deleted, which publishing would deploy.
+ const patched: Record<string, any>[] = []
+ let releaseFirst: () => void = () => {}
+ let seen = 0
+ const base = staged.actions
+ const withStep = [
+ ...base,
+ {
+ id: 'delay_node',
+ type: 'delay',
+ name: 'Wait',
+ description: '',
+ created_at: 0,
+ updated_at: 0,
+ config: { delay_duration: '5m' },
+ },
+ ] as HogFlow['actions']
+ // Start from a draft that holds the live steps, so reverting lands exactly back on it.
+ const loaded = makeWorkflow({
+ ...staged,
+ draft: { ...(staged.draft as any), actions: base, edges: staged.edges },
+ })
+
+ useMocks({
+ get: { '/api/environments/:team_id/hog_flows/:id/': loaded },
+ patch: {
+ '/api/environments/:team_id/hog_flows/:id/': async ({ request }) => {
+ const body = (await request.json()) as Record<string, any>
+ patched.push(body)
+ if (++seen === 1) {
+ await new Promise<void>((resolve) => {
+ releaseFirst = resolve
+ })
+ }
+ // A staged save answers with the live row plus the new draft blob.
+ return [
+ 200,
+ makeWorkflow({
+ ...loaded,
+ draft: { ...(loaded.draft as any), actions: body.actions ?? base },
+ draft_updated_at: new Date(Date.parse('2026-05-01T00:02:00.000Z') + seen).toISOString(),
+ }),
+ ]
+ },
+ },
+ })
+
+ logic.actions.loadWorkflow()
+ await expectLogic(logic).toDispatchActions(['loadWorkflowSuccess'])
+
+ // Add a step, let that save start, then take it back out while it is still open.
+ logic.actions.setWorkflowValues({ actions: withStep })
+ logic.actions.markAutoSave(true)
+ logic.actions.saveWorkflow(logic.values.workflow)
+ await new Promise((resolve) => setTimeout(resolve, 50))
+
+ logic.actions.setWorkflowValues({ actions: base })
+ logic.actions.markAutoSave(true)
+ logic.actions.saveWorkflow(logic.values.workflow)
+ await new Promise((resolve) => setTimeout(resolve, 50))
+
+ releaseFirst()
+ await new Promise((resolve) => setTimeout(resolve, 400))
+
+ // The undo must reach the draft, not be dropped as "nothing changed".
+ expect(patched[1]?.actions?.map((a: any) => a.id)).toEqual(base.map((a) => a.id))
+ expect(patched[1]?.stage_draft).toBe(true)
+ })
+
+ it('does not re-enable a workflow when a save is queued behind a disable', async () => {
+ // The disable request is held open, so the save below queues behind it and carries the
+ // form's stale status. Landing that would put a stopped workflow back into sending.
+ const patched: Record<string, any>[] = []
+ let releaseDisable: () => void = () => {}
+ let seen = 0
+ useMocks({
+ patch: {
+ '/api/environments/:team_id/hog_flows/:id/': async ({ request }) => {
+ const body = (await request.json()) as Record<string, any>
+ patched.push(body)
+ if (++seen === 1) {
+ await new Promise<void>((resolve) => {
+ releaseDisable = resolve
+ })
+ }
+ return [200, makeWorkflow({ ...staged, status: body.status ?? 'draft' })]
+ },
+ },
+ })
+
+ logic.actions.saveWorkflowPartial({ status: 'draft' })
+ await new Promise((resolve) => setTimeout(resolve, 50))
+
+ logic.actions.setWorkflowValue('name', 'Edited while disabling')
+ logic.actions.submitWorkflow()
+ await new Promise((resolve) => setTimeout(resolve, 50))
+
+ releaseDisable()
+ await new Promise((resolve) => setTimeout(resolve, 300))
+
+ expect(patched[0].status).toBe('draft')
+ // The queued form save must not speak about status at all.
+ expect(patched[1]).not.toHaveProperty('status')
+ })
+ })
+
describe('navigation guard', () => {
it('does not fire save on unmount (no silent flush)', async () => {
initKeaTests()
diff --git a/products/workflows/frontend/Workflows/workflowLogic.ts b/products/workflows/frontend/Workflows/workflowLogic.ts
index cc1cadc85f52..fb2296dc1c85 100644
--- a/products/workflows/frontend/Workflows/workflowLogic.ts
+++ b/products/workflows/frontend/Workflows/workflowLogic.ts
@@ -187,6 +187,12 @@ function pickWorkflowEdits(workflow: HogFlow): Partial<HogFlow> {
return result as Partial<HogFlow>
}
+/** What a save was dispatched with, kept per save because a later save moves the shared state. */
+interface SaveContext {
+ initiatedByAutoSave: boolean
+ pendingSchedule: { rrule: string; starts_at: string; timezone?: string } | null | false
+}
+
function omitWorkflowContent(workflow: HogFlow): Partial<HogFlow> {
const result: Record<string, unknown> = { ...workflow }
for (const field of WORKFLOW_CONTENT_FIELDS) {
@@ -204,6 +210,7 @@ export interface workflowLogicValues {
autoSaveEnabled: boolean
currentSchedule: HogFlowSchedule | null
deferredResourceEdited: ResourceEditedEvent | null
+ discardDisabledReason: string | undefined
draftActionPending: 'discard' | 'publish' | null
edgesByActionId: Record<string, HogFlowEdge[]>
externallyEdited: boolean
@@ -230,6 +237,7 @@ export interface workflowLogicValues {
}
| false
| null
+ publishDisabledReason: string | undefined
saveAttemptedActionIds: string[] | null
saveBaseUpdatedAt: string | null
scheduleConfigSources: {
@@ -240,6 +248,7 @@ export interface workflowLogicValues {
scheduleState: ScheduleState
scheduleTimezone: string
schedules: HogFlowSchedule[]
+ showDraftActions: boolean
showWorkflowErrors: boolean
triggerAction: TriggerAction | null
workflow: HogFlow
@@ -2933,6 +2942,17 @@ export interface workflowLogicMeta {
hogFunctionTemplatesById: Record<string, HogFunctionTemplateType>
) => HogFlow
hasStagedDraft: (originalWorkflow: HogFlow | null) => boolean
+ showDraftActions: (originalWorkflow: HogFlow | null) => boolean
+ publishDisabledReason: (
+ hasStagedDraft: boolean,
+ hasUnsavedChanges: boolean,
+ draftActionPending: 'discard' | 'publish' | null
+ ) => string | undefined
+ discardDisabledReason: (
+ hasStagedDraft: boolean,
+ hasUnsavedChanges: boolean,
+ draftActionPending: 'discard' | 'publish' | null
+ ) => string | undefined
}
}
@@ -3002,7 +3022,7 @@ export const workflowLogic = kea<workflowLogicType>([
setDeferredResourceEdited: (event: ResourceEditedEvent | null) => ({ event }),
replayDeferredResourceEdited: true,
}),
- loaders(({ props, values, actions }) => ({
+ loaders(({ props, values, actions, cache }) => ({
originalWorkflow: [
null as HogFlow | null,
{
@@ -3039,91 +3059,139 @@ export const workflowLogic = kea<workflowLogicType>([
return api.hogFlows.getHogFlow(props.id)
},
saveWorkflow: async (updates: HogFlow) => {
- updates = sanitizeWorkflow(updates, values.hogFunctionTemplatesById)
+ // `isAutoSave` is one shared reducer, not a per-request value. A manual save
+ // dispatched while an auto-save is still in flight sets it to false, so the
+ // auto-save's own 409 would then take the manual path and raise the banner.
+ // Read the origin at dispatch time, while it still describes this save.
+ const initiatedByAutoSave = values.isAutoSave
+ // Saves run one at a time, so their success and failure actions arrive in
+ // dispatch order. Queue what each save needs alongside them, so the success
+ // listener reads its own values rather than shared state a later save moved.
+ // The pending schedule rides along because an earlier save's reset clears it,
+ // which would drop a schedule change the user asked a manual save to persist.
+ const saveContexts = (cache.saveContexts ??= []) as SaveContext[]
+ saveContexts.push({ initiatedByAutoSave, pendingSchedule: values.pendingSchedule })
+ // Whether this save means to change the lifecycle. Only the enable and disable
+ // control does, and it says so when it dispatches. Comparing the payload's
+ // status against the stored one cannot tell the difference: that control does
+ // not write its new status back to the form, so a form save queued behind it
+ // carries the old value and reads as a transition back to it.
+ const isStatusSave = cache.nextSaveChangesStatus === true
+ cache.nextSaveChangesStatus = false
- if (!props.id || props.id === 'new') {
- const result = await api.hogFlows.createHogFlow(updates)
+ const runSave = async (): Promise<HogFlow> => {
+ updates = sanitizeWorkflow(updates, values.hogFunctionTemplatesById)
- if (props.templateId) {
- posthog.capture('hog_flow_created_from_template', {
- workflow_id: result.id,
- template_id: props.templateId,
- })
+ if (!props.id || props.id === 'new') {
+ const result = await api.hogFlows.createHogFlow(updates)
+
+ if (props.templateId) {
+ posthog.capture('hog_flow_created_from_template', {
+ workflow_id: result.id,
+ template_id: props.templateId,
+ })
+ }
+ return result
}
- return result
- }
- // The form's clean baseline: the staged draft merged over the live row. Sanitized
- // like `updates` so untouched steps compare equal. Cloned via JSON round-trip,
- // not structuredClone: the clone only feeds the comparison, and structuredClone
- // can yield objects whose constructors fail fast-equals' check, making every
- // save look like a content change.
- const baseline = values.originalWorkflow
- ? sanitizeWorkflow(
- JSON.parse(JSON.stringify(withStagedDraft(values.originalWorkflow))),
- values.hogFunctionTemplatesById
- )
- : null
- const contentChanged =
- !baseline ||
- WORKFLOW_CONTENT_FIELDS.some(
- (field) => !objectsEqual((updates as any)[field], (baseline as any)[field])
- )
- const isStatusTransition =
- !!values.originalWorkflow && updates.status !== values.originalWorkflow.status
- // Content edits on an active workflow stage into its draft (publish promotes them).
- // Metadata-only saves (rename, description) must not: staging the unchanged content
- // would create a phantom draft identical to live.
- const stagingDraft =
- values.originalWorkflow?.status === 'active' && updates.status === 'active' && contentChanged
- // A status transition (enable/disable) toggles the lifecycle only. The button is
- // disabled while the form is dirty, so content in the payload is at best a no-op
- // re-send of the live row and at worst (with a staged draft merged into the form)
- // a silent deploy of unpublished content. Metadata-only saves on active workflows
- // strip content the same way, so unchanged content never routes to a draft.
- const payload: Partial<HogFlow> =
- isStatusTransition || (values.originalWorkflow?.status === 'active' && !contentChanged)
- ? omitWorkflowContent(updates)
- : updates
- // Draft writes race against other draft writes, not the live row, so the staleness
- // baseline follows the routing: the draft's own stamp once one is staged.
- const loadedBase = stagingDraft
- ? (values.originalWorkflow?.draft_updated_at ?? values.originalWorkflow?.updated_at)
- : values.originalWorkflow?.updated_at
+ // The newest server copy this editor has produced. A queued save must compare
+ // and fence against the copy the save before it wrote, and that copy reaches
+ // this cache when its response lands, which is before kea applies the result
+ // to `originalWorkflow`. Reading the kea value instead would compare an edit
+ // against the state from two saves ago: an edit that returns the content to
+ // that older state looks unchanged, so its payload carries no content and
+ // the draft keeps what the user just removed. Cleared on load, because a
+ // reload, publish, or discard establishes a new baseline.
+ const latest = (cache.lastSavedWorkflow as HogFlow | undefined) ?? values.originalWorkflow
+ // The form's clean baseline: the staged draft merged over the live row. Sanitized
+ // like `updates` so untouched steps compare equal. Cloned via JSON round-trip,
+ // not structuredClone: the clone only feeds the comparison, and structuredClone
+ // can yield objects whose constructors fail fast-equals' check, making every
+ // save look like a content change.
+ const baseline = latest
+ ? sanitizeWorkflow(
+ JSON.parse(JSON.stringify(withStagedDraft(latest))),
+ values.hogFunctionTemplatesById
+ )
+ : null
+ const contentChanged =
+ !baseline ||
+ WORKFLOW_CONTENT_FIELDS.some(
+ (field) => !objectsEqual((updates as any)[field], (baseline as any)[field])
+ )
+ const isStatusTransition = isStatusSave && !!latest && updates.status !== latest.status
+ // Content edits on an active workflow stage into its draft (publish promotes them).
+ // Metadata-only saves (rename, description) must not: staging the unchanged content
+ // would create a phantom draft identical to live.
+ const stagingDraft =
+ latest?.status === 'active' && updates.status === 'active' && contentChanged
+ // A status transition (enable/disable) toggles the lifecycle only. The button is
+ // disabled while the form is dirty, so content in the payload is at best a no-op
+ // re-send of the live row and at worst (with a staged draft merged into the form)
+ // a silent deploy of unpublished content. Metadata-only saves on active workflows
+ // strip content the same way, so unchanged content never routes to a draft.
+ const payload: Partial<HogFlow> =
+ isStatusTransition || (latest?.status === 'active' && !contentChanged)
+ ? omitWorkflowContent(updates)
+ : { ...updates }
+ if (!isStatusSave) {
+ // A form save must not speak about the lifecycle. Otherwise one queued
+ // behind a disable carries the pre-change status and puts the workflow
+ // back, so a stopped workflow resumes running and sending.
+ delete payload.status
+ }
+ const liveBase = latest?.updated_at
+ // Draft writes race against other draft writes, not the live row, so the staleness
+ // baseline follows the routing: the draft's own stamp once one is staged.
+ const loadedBase = stagingDraft ? (latest?.draft_updated_at ?? liveBase) : liveBase
- try {
- return await api.hogFlows.updateHogFlow(props.id, {
- ...payload,
- ...(stagingDraft ? { stage_draft: true } : {}),
- // A staged save's metadata still writes live; fence that write with the
- // live stamp so it can't overwrite a concurrent metadata edit the
- // draft-stamp baseline wouldn't catch.
- ...(stagingDraft && values.originalWorkflow?.updated_at
- ? { base_live_updated_at: values.originalWorkflow.updated_at }
- : {}),
- // Let the server reject the save if a newer copy exists (optimistic concurrency).
- // saveBaseUpdatedAt overrides the loaded timestamp after the user picks "Keep mine".
- base_updated_at: values.saveBaseUpdatedAt ?? loadedBase ?? null,
- })
- } catch (error) {
- if (error instanceof ApiError && error.status === 409) {
- if (values.isAutoSave && values.pendingSchedule === false) {
- // An auto-save losing the race is not a decision point: the user never
- // asked to overwrite anything, so reconcile to the newer copy silently.
- // A pending schedule change is the exception: only a manual save
- // persists it, and the reload would wipe it, so that gets the banner.
- actions.setSyncingExternalEdit(true)
- actions.loadWorkflow()
- } else {
- // A newer version exists (SSE event likely missed): surface the reconcile
- // banner, which carries the actionable Reload / Keep mine choice. No toast,
- // as it would just duplicate the banner (the global kea handler already
- // skips 409).
- actions.setExternallyEdited(true)
+ try {
+ const result = await api.hogFlows.updateHogFlow(props.id, {
+ ...payload,
+ ...(stagingDraft ? { stage_draft: true } : {}),
+ // A staged save's metadata still writes live; fence that write with the
+ // live stamp so it can't overwrite a concurrent metadata edit the
+ // draft-stamp baseline wouldn't catch.
+ ...(stagingDraft && liveBase ? { base_live_updated_at: liveBase } : {}),
+ // Let the server reject the save if a newer copy exists (optimistic concurrency).
+ // saveBaseUpdatedAt overrides the loaded timestamp after the user picks "Keep mine".
+ base_updated_at: values.saveBaseUpdatedAt ?? loadedBase ?? null,
+ })
+ cache.lastSavedWorkflow = result
+ return result
+ } catch (error) {
+ if (error instanceof ApiError && error.status === 409) {
+ if (initiatedByAutoSave && values.pendingSchedule === false) {
+ // An auto-save losing the race is not a decision point: the user never
+ // asked to overwrite anything, so reconcile to the newer copy silently.
+ // A pending schedule change is the exception: only a manual save
+ // persists it, and the reload would wipe it, so that gets the banner.
+ actions.setSyncingExternalEdit(true)
+ actions.loadWorkflow()
+ } else {
+ // A newer version exists (SSE event likely missed): surface the reconcile
+ // banner, which carries the actionable Reload / Keep mine choice. No toast,
+ // as it would just duplicate the banner (the global kea handler already
+ // skips 409).
+ actions.setExternallyEdited(true)
+ }
}
+ throw error
}
- throw error
}
+
+ // Saves run one at a time. Every save fences on `base_updated_at`, taken from the
+ // newest server copy this editor knows about. A save that starts while another is
+ // still in flight carries a baseline the server has already moved past, so it comes
+ // back 409 and the user sees the "updated elsewhere" banner for their own edit. The
+ // reported case is a click on "Save draft" as the auto-save debounce fires.
+ const previous = (cache.saveChain as Promise<unknown> | undefined) ?? Promise.resolve()
+ const current = previous.then(runSave, runSave)
+ cache.saveChain = current.then(
+ () => undefined,
+ () => undefined
+ )
+ return current
},
},
],
@@ -3150,7 +3218,7 @@ export const workflowLogic = kea<workflowLogicType>([
},
],
})),
- forms(({ actions, values }) => ({
+ forms(({ actions, values, cache }) => ({
workflow: {
defaults: NEW_WORKFLOW,
errors: ({ name, actions, status }) => {
@@ -3171,6 +3239,10 @@ export const workflowLogic = kea<workflowLogicType>([
}
actions.saveWorkflow(values)
+ // Hold the form in its submitting state until the save lands, so the save button
+ // keeps a loading state and cannot fire a second save. The loader assigns
+ // `saveChain` while it handles the action above, so this reads the current save.
+ await cache.saveChain
},
},
})),
@@ -3648,6 +3720,57 @@ export const workflowLogic = kea<workflowLogicType>([
(s) => [s.originalWorkflow],
(originalWorkflow: HogFlow | null): boolean => !!originalWorkflow?.draft,
],
+
+ // A staged draft outlives the edits made after it, so the draft actions stay mounted while
+ // the form is dirty. Gating them on a clean form made them appear and disappear on every
+ // auto-save cycle.
+ // Every live workflow keeps the publish slot, staged draft or not. Mounting the button only
+ // once a draft exists would move the save button on the first auto-save, which is the jump
+ // this editor is meant to stop. A live workflow can always be published into, so the button
+ // is honest when idle: it says there is nothing staged yet.
+ showDraftActions: [
+ (s) => [s.originalWorkflow],
+ (originalWorkflow: HogFlow | null): boolean =>
+ originalWorkflow?.status === 'active' && !!originalWorkflow?.id,
+ ],
+
+ publishDisabledReason: [
+ (s) => [s.hasStagedDraft, s.hasUnsavedChanges, s.draftActionPending],
+ (
+ hasStagedDraft: boolean,
+ hasUnsavedChanges: boolean,
+ draftActionPending: 'publish' | 'discard' | null
+ ): string | undefined => {
+ if (draftActionPending === 'discard') {
+ return 'Discarding is in progress'
+ }
+ // Publish promotes the staged draft, so edits still sitting in the form would not
+ // go out. Auto-save clears this a few seconds after the user stops typing.
+ if (hasUnsavedChanges) {
+ return 'Save your changes first'
+ }
+ return hasStagedDraft ? undefined : 'No changes staged to publish'
+ },
+ ],
+
+ discardDisabledReason: [
+ (s) => [s.hasStagedDraft, s.hasUnsavedChanges, s.draftActionPending],
+ (
+ hasStagedDraft: boolean,
+ hasUnsavedChanges: boolean,
+ draftActionPending: 'publish' | 'discard' | null
+ ): string | undefined => {
+ if (draftActionPending === 'publish') {
+ return 'Publishing is in progress'
+ }
+ // Discarding reloads the workflow, which drops whatever the form still holds. The
+ // user only agreed to lose the staged draft, so block until the form is clean.
+ if (hasUnsavedChanges) {
+ return 'Save or clear your changes first'
+ }
+ return hasStagedDraft ? undefined : 'No changes staged to discard'
+ },
+ ],
}),
listeners(({ actions, values, props, cache }) => ({
setScheduleStartsAtFromPicker: ({ pickerDate }) => {
@@ -3680,13 +3803,18 @@ export const workflowLogic = kea<workflowLogicType>([
if (event.resource_type !== 'HogFlow' || event.resource_id !== props.id) {
return
}
- // Our own save/reload is mid-flight (originalWorkflowLoading covers both, they share a
- // loader), or a publish/discard is about to reload: the emit for our own write can beat
- // its HTTP response back to us, and reacting to that echo against the stale baseline
- // flashes the conflict banner at ourselves. Park the event instead of reacting; once the
- // flight settles it replays against the fresh baseline, where our own echo compares equal
- // (ignored) and a genuine concurrent edit is still strictly newer (reconciled).
- if (values.originalWorkflowLoading || values.draftActionPending) {
+ // Our own save/reload is mid-flight, or a publish/discard is about to reload: the emit
+ // for our own write can beat its HTTP response back to us, and reacting to that echo
+ // against the stale baseline flashes the conflict banner at ourselves. Park the event
+ // instead of reacting; once the flight settles it replays against the fresh baseline,
+ // where our own echo compares equal (ignored) and a genuine concurrent edit is still
+ // strictly newer (reconciled).
+ // `originalWorkflowLoading` alone is not enough here. It is one boolean for the whole
+ // loader, so the first save of a queued pair clears it while the second still runs, and
+ // that second save's own echo would then read as somebody else's edit. Count the saves
+ // this editor still has outstanding instead.
+ const savesInFlight = ((cache.saveContexts as SaveContext[] | undefined) ?? []).length
+ if (values.originalWorkflowLoading || savesInFlight > 0 || values.draftActionPending) {
actions.setDeferredResourceEdited(event)
return
}
@@ -3824,9 +3952,15 @@ export const workflowLogic = kea<workflowLogicType>([
lemonToast.error('Fix all errors before enabling')
return
}
+ // This is the one path that means to change the lifecycle. The loader reads the flag
+ // as it handles the action below, so it describes this save and no other.
+ cache.nextSaveChangesStatus = 'status' in workflow
actions.saveWorkflow(merged)
},
loadWorkflowSuccess: async ({ originalWorkflow }) => {
+ // This response is now the save baseline. Discarding a draft moves its stamp backwards,
+ // so a copy kept from an earlier save would fence later saves too loosely.
+ cache.lastSavedWorkflow = undefined
// The form edits the staged draft when one exists; the live config keeps running underneath.
actions.resetWorkflow(withStagedDraft(originalWorkflow))
actions.replayDeferredResourceEdited()
@@ -3847,6 +3981,8 @@ export const workflowLogic = kea<workflowLogicType>([
cache.saveEditVersion = values.workflowEditVersion
},
saveWorkflowFailure: () => {
+ // Keep the queue aligned with the saves still in flight.
+ ;(cache.saveContexts as SaveContext[] | undefined)?.shift()
actions.replayDeferredResourceEdited()
},
replayDeferredResourceEdited: () => {
@@ -3857,12 +3993,18 @@ export const workflowLogic = kea<workflowLogicType>([
}
},
saveWorkflowSuccess: async ({ originalWorkflow }) => {
- const isAutoSave = values.isAutoSave
+ // What this save was dispatched with. A manual save queued behind an auto-save used to
+ // relabel the auto-save here, so the auto-save also ran the manual-only work below: a
+ // second toast, and a second schedule write that can leave a duplicate schedule.
+ const saveContext = (cache.saveContexts as SaveContext[] | undefined)?.shift()
+ const isAutoSave = saveContext?.initiatedByAutoSave ?? values.isAutoSave
if (!isAutoSave) {
// Save pending schedule changes (only on manual save)
const workflowId = originalWorkflow.id
- const pendingSchedule = values.pendingSchedule
+ // Read the schedule this save carried. An auto-save that landed first has already
+ // reset the reducers, so the live value no longer describes what the user staged.
+ const pendingSchedule = saveContext ? saveContext.pendingSchedule : values.pendingSchedule
const existingScheduleId = values.currentSchedule?.id
const hasScheduleChanges = pendingSchedule !== false && !!workflowId