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.

chore(workflows): move the workflow editor's save queue and edit-event sorting into a shared helper (#106720)

Daniel Marchuke6ca63b8824e
diff --git a/products/workflows/frontend/Workflows/resourceSaveQueue.test.ts b/products/workflows/frontend/Workflows/resourceSaveQueue.test.ts
new file mode 100644
index 000000000000..f67c673a3465
--- /dev/null
+++ b/products/workflows/frontend/Workflows/resourceSaveQueue.test.ts
@@ -0,0 +1,103 @@
+import type { ResourceEditedEvent } from '~/types'
+
+import { ResourceSaveQueue } from './resourceSaveQueue'
+
+const event = (overrides: Partial<ResourceEditedEvent> = {}): ResourceEditedEvent => ({
+ notification_type: 'resource_edited',
+ team_id: 1,
+ resource_type: 'HogFlow',
+ resource_id: 'flow-1',
+ updated_at: '2026-09-25T10:00:05Z',
+ actor_user_id: 2,
+ ...overrides,
+})
+
+const queue = (loadedStamp: string | null = '2026-09-25T10:00:00Z', isBusy = false): ResourceSaveQueue =>
+ new ResourceSaveQueue({
+ resourceType: 'HogFlow',
+ getResourceId: () => 'flow-1',
+ getLoadedStamp: () => loadedStamp,
+ isBusy: () => isBusy,
+ })
+
+describe('ResourceSaveQueue', () => {
+ it('runs a save only after the one before it settles, even when that one fails', async () => {
+ const saves = queue()
+ const order: string[] = []
+ let failFirst: (error: Error) => void = () => {}
+ const first = saves.run(
+ () =>
+ new Promise((_, reject) => {
+ order.push('first started')
+ failFirst = reject
+ })
+ )
+ const second = saves.run(async () => {
+ order.push('second started')
+ return 'saved'
+ })
+ await Promise.resolve()
+ expect(order).toEqual(['first started'])
+ expect(saves.inFlight).toBe(2)
+
+ failFirst(new Error('409'))
+ await expect(first).rejects.toThrow('409')
+ await expect(second).resolves.toBe('saved')
+ await saves.whenIdle()
+ expect(order).toEqual(['first started', 'second started'])
+ expect(saves.inFlight).toBe(0)
+ })
+
+ it.each([
+ ['another resource type', 'ignore', event({ resource_type: 'HogFunction' })],
+ ['another workflow', 'ignore', event({ resource_id: 'flow-2' })],
+ ['the echo of our own save', 'ignore', event({ updated_at: '2026-09-25T10:00:00Z' })],
+ ['an older copy', 'ignore', event({ updated_at: '2026-09-25T09:59:00Z' })],
+ ['a newer copy from elsewhere', 'external', event()],
+ ])('reads %s as %s', (_, verdict, incoming) => {
+ expect(queue().classify(incoming)).toBe(verdict)
+ })
+
+ it('ignores every event until something has loaded', () => {
+ expect(queue(null).classify(event())).toBe('ignore')
+ })
+
+ it('holds an event that lands mid-save and hands the latest one over once', async () => {
+ const saves = queue()
+ let finish: () => void = () => {}
+ const saving = saves.run(() => new Promise<void>((resolve) => (finish = resolve)))
+
+ expect(saves.classify(event({ updated_at: '2026-09-25T10:00:03Z' }))).toBe('defer')
+ expect(saves.classify(event())).toBe('defer')
+ await Promise.resolve()
+ finish()
+ await saving
+
+ expect(saves.takeDeferred()).toEqual(event())
+ expect(saves.takeDeferred()).toBeNull()
+ })
+
+ it('keeps holding a replayed event until the last queued save settles', async () => {
+ const saves = queue()
+ const finishers: (() => void)[] = []
+ const first = saves.run(() => new Promise<void>((resolve) => finishers.push(resolve)))
+ const second = saves.run(() => new Promise<void>((resolve) => finishers.push(resolve)))
+ await Promise.resolve()
+
+ expect(saves.classify(event())).toBe('defer')
+ finishers[0]()
+ await first
+ const replayed = saves.takeDeferred()
+ expect(replayed && saves.classify(replayed)).toBe('defer')
+
+ await Promise.resolve()
+ finishers[1]()
+ await second
+ const lastReplay = saves.takeDeferred()
+ expect(lastReplay && saves.classify(lastReplay)).toBe('external')
+ })
+
+ it('holds events while the editor says it is busy', () => {
+ expect(queue(undefined, true).classify(event())).toBe('defer')
+ })
+})
diff --git a/products/workflows/frontend/Workflows/resourceSaveQueue.ts b/products/workflows/frontend/Workflows/resourceSaveQueue.ts
new file mode 100644
index 000000000000..1d7342ce5280
--- /dev/null
+++ b/products/workflows/frontend/Workflows/resourceSaveQueue.ts
@@ -0,0 +1,68 @@
+import { dayjs } from 'lib/dayjs'
+
+import type { ResourceEditedEvent } from '~/types'
+
+export type ResourceEditedVerdict = 'ignore' | 'defer' | 'external'
+
+export interface ResourceSaveQueueOptions {
+ resourceType: ResourceEditedEvent['resource_type']
+ getResourceId: () => string | null | undefined
+ /** The newest server stamp this editor has loaded or saved. An event no newer than it is the echo of our own write. */
+ getLoadedStamp: () => string | null | undefined
+ /** Other reasons to hold events back, such as a load in flight or a publish about to reload. */
+ isBusy?: () => boolean
+}
+
+/**
+ * Runs an editor's saves one at a time, so a queued save fences on the stamp the save before it wrote
+ * instead of coming back 409. Edit events that land mid-save are held until the saves settle, because
+ * the server's event for our own write can beat its HTTP response.
+ */
+export class ResourceSaveQueue {
+ private chain: Promise<unknown> = Promise.resolve()
+ private pending = 0
+ private deferred: ResourceEditedEvent | null = null
+
+ constructor(private readonly options: ResourceSaveQueueOptions) {}
+
+ get inFlight(): number {
+ return this.pending
+ }
+
+ run<T>(save: () => Promise<T>): Promise<T> {
+ this.pending += 1
+ const settle = (): void => {
+ this.pending -= 1
+ }
+ const current = this.chain.then(save, save)
+ current.then(settle, settle)
+ this.chain = current.then(
+ () => undefined,
+ () => undefined
+ )
+ return current
+ }
+
+ whenIdle(): Promise<void> {
+ return this.chain.then(() => undefined)
+ }
+
+ classify(event: ResourceEditedEvent): ResourceEditedVerdict {
+ if (event.resource_type !== this.options.resourceType || event.resource_id !== this.options.getResourceId()) {
+ return 'ignore'
+ }
+ if (this.pending > 0 || this.options.isBusy?.()) {
+ this.deferred = event
+ return 'defer'
+ }
+ const loaded = this.options.getLoadedStamp()
+ return loaded && dayjs(event.updated_at).isAfter(dayjs(loaded)) ? 'external' : 'ignore'
+ }
+
+ /** Call after a save or load settles, and dispatch the event again. */
+ takeDeferred(): ResourceEditedEvent | null {
+ const deferred = this.deferred
+ this.deferred = null
+ return deferred
+ }
+}
diff --git a/products/workflows/frontend/Workflows/workflowLogic.ts b/products/workflows/frontend/Workflows/workflowLogic.ts
index 1d649273f306..9b641a0f50c0 100644
--- a/products/workflows/frontend/Workflows/workflowLogic.ts
+++ b/products/workflows/frontend/Workflows/workflowLogic.ts
@@ -51,6 +51,7 @@ import {
type HogFlowSchedule,
} from './hogflows/types'
import { openPublishConfirmDialog } from './PublishImpactDialog'
+import { ResourceSaveQueue } from './resourceSaveQueue'
import { prepareWorkflowDuplicate } from './workflowDuplication'
import { workflowSceneLogic } from './workflowSceneLogic'
import { workflowsLogic } from './workflowsLogic'
@@ -213,7 +214,6 @@ export interface workflowLogicValues {
autoSaveBlockedByValidation: boolean
autoSaveEnabled: boolean
currentSchedule: HogFlowSchedule | null
- deferredResourceEdited: ResourceEditedEvent | null
discardDisabledReason: string | undefined
draftActionPending: 'discard' | 'publish' | null
edgesByActionId: Record<string, HogFlowEdge[]>
@@ -2387,9 +2387,6 @@ export interface workflowLogicActions {
setAutoSaveEnabled: (enabled: boolean) => {
enabled: boolean
}
- setDeferredResourceEdited: (event: ResourceEditedEvent | null) => {
- event: ResourceEditedEvent | null
- }
setDraftActionPending: (pending: 'discard' | 'publish' | null) => {
pending: 'discard' | 'publish' | null
}
@@ -3015,6 +3012,30 @@ export type workflowLogicType = MakeLogicType<
workflowLogicMeta
>
+function getSaveQueue(
+ cache: Record<string, any>,
+ values: workflowLogicType['values'],
+ props: WorkflowLogicProps
+): ResourceSaveQueue {
+ return (cache.saveQueue ??= new ResourceSaveQueue({
+ resourceType: 'HogFlow',
+ getResourceId: () => props.id,
+ // Draft writes don't bump the live updated_at, and the event carries the newer of the two
+ // stamps, so compare against the newer one we loaded.
+ getLoadedStamp: () => {
+ const { updated_at, draft_updated_at } = values.originalWorkflow ?? {}
+ return draft_updated_at && updated_at && dayjs(draft_updated_at).isAfter(dayjs(updated_at))
+ ? draft_updated_at
+ : updated_at
+ },
+ // The loader flag clears when the first of a queued pair lands, so count unfinished saves too.
+ isBusy: () =>
+ values.originalWorkflowLoading ||
+ ((cache.saveContexts as SaveContext[] | undefined) ?? []).length > 0 ||
+ !!values.draftActionPending,
+ }))
+}
+
export const workflowLogic = kea<workflowLogicType>([
path((key) => ['products', 'workflows', 'frontend', 'Workflows', 'workflowLogic', key]),
props({ id: 'new' } as WorkflowLogicProps),
@@ -3072,7 +3093,6 @@ export const workflowLogic = kea<workflowLogicType>([
discardDraft: true,
confirmDiscardDraft: true,
setDraftActionPending: (pending: 'publish' | 'discard' | null) => ({ pending }),
- setDeferredResourceEdited: (event: ResourceEditedEvent | null) => ({ event }),
replayDeferredResourceEdited: true,
resumeEmailSending: true,
confirmResumeEmailSending: true,
@@ -3257,18 +3277,9 @@ export const workflowLogic = kea<workflowLogicType>([
}
}
- // 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
+ // The reported case for queueing: a click on "Save draft" as the auto-save debounce
+ // fires would otherwise send two saves with the same baseline, and the second 409s.
+ return getSaveQueue(cache, values, props).run(runSave)
},
},
],
@@ -3317,9 +3328,9 @@ 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
+ // keeps a loading state and cannot fire a second save. The loader created the queue
+ // while it handled the action above.
+ await (cache.saveQueue as ResourceSaveQueue | undefined)?.whenIdle()
},
},
})),
@@ -3480,15 +3491,6 @@ export const workflowLogic = kea<workflowLogicType>([
setResumeEmailSendingPending: (_, { pending }) => pending,
},
],
- // A resource_edited event parked while our own save/reload was in flight. Replayed once the
- // flight settles, so a genuine external edit landing in that window is reconciled instead of
- // dropped. Latest event wins: the comparison is against timestamps, so older ones are moot.
- deferredResourceEdited: [
- null as ResourceEditedEvent | null,
- {
- setDeferredResourceEdited: (_, { event }) => event,
- },
- ],
}),
selectors({
logicProps: [
@@ -3903,42 +3905,8 @@ export const workflowLogic = kea<workflowLogicType>([
actions.setSchedules(values.schedules)
},
resourceEdited: ({ event }) => {
- // Another channel (a second UI tab, MCP, or the API) saved this workflow. React only to
- // events for the workflow we currently have open.
- if (event.resource_type !== 'HogFlow' || event.resource_id !== props.id) {
- return
- }
- // 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
- }
- // Draft writes don't bump the live updated_at (the emit broadcasts the newer of the two
- // stamps), so compare against the newest stamp we loaded or a staged edit from another
- // channel would go unnoticed.
- let loadedUpdatedAt = values.originalWorkflow?.updated_at
- const loadedDraftUpdatedAt = values.originalWorkflow?.draft_updated_at
- if (
- loadedDraftUpdatedAt &&
- loadedUpdatedAt &&
- dayjs(loadedDraftUpdatedAt).isAfter(dayjs(loadedUpdatedAt))
- ) {
- loadedUpdatedAt = loadedDraftUpdatedAt
- }
- // Strictly-newer comparison rather than equality: equal means the event is the echo of our
- // own save (originalWorkflow already carries that updated_at), so we ignore it. Only a server
- // copy that is genuinely ahead of what we loaded is a real external edit.
- if (!loadedUpdatedAt || !dayjs(event.updated_at).isAfter(dayjs(loadedUpdatedAt))) {
+ // Another channel (a second UI tab, MCP, or the API) saved this workflow.
+ if (getSaveQueue(cache, values, props).classify(event) !== 'external') {
return
}
// Server wins while auto-save can flush the local buffer: unsaved edits are then at most
@@ -4127,9 +4095,8 @@ export const workflowLogic = kea<workflowLogicType>([
actions.replayDeferredResourceEdited()
},
replayDeferredResourceEdited: () => {
- const deferred = values.deferredResourceEdited
+ const deferred = getSaveQueue(cache, values, props).takeDeferred()
if (deferred) {
- actions.setDeferredResourceEdited(null)
actions.resourceEdited(deferred)
}
},