: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
fix(workflows): reconcile ReactFlow nodes and edges instead of rebuilding wholesale (#68541)
Paul D'Ambra0a22e35acb14
diff --git a/products/workflows/frontend/Workflows/hogflows/HogFlowEditor.tsx b/products/workflows/frontend/Workflows/hogflows/HogFlowEditor.tsxindex 52af806dbe08..68d81cdd18e8 100644--- a/products/workflows/frontend/Workflows/hogflows/HogFlowEditor.tsx+++ b/products/workflows/frontend/Workflows/hogflows/HogFlowEditor.tsx@@ -12,7 +12,7 @@ import {useReactFlow,} from '@xyflow/react'import { BindLogic, useActions, useValues } from 'kea'-import { useEffect, useRef } from 'react'+import { useEffect, useMemo, useRef } from 'react'import { IconInfo } from '@posthog/icons'@@ -54,12 +54,19 @@ function HogFlowEditorContent(): JSX.Element {setReactFlowWrapper(reactFlowWrapper)}, [setReactFlowWrapper])+ // ReactFlow diffs its nodes prop by reference: an inline spread would hand it a fresh array+ // every render, making every render look like a graph change.+ const nodesWithDropzones = useMemo(+ () => [...nodes, ...(dropzoneNodes as unknown as HogFlowActionNode[])],+ [nodes, dropzoneNodes]+ )+return (<div ref={reactFlowWrapper} className="flex flex-col grow w-full" data-attr="workflow-editor"><ReactFlow<HogFlowActionNode, HogFlowActionEdge>className="grow"fitView- nodes={[...nodes, ...(dropzoneNodes as unknown as HogFlowActionNode[])]}+ nodes={nodesWithDropzones}edges={edges}onNodesChange={onNodesChange}onEdgesChange={onEdgesChange}diff --git a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.test.ts b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.test.tsindex d04cffc40d87..111cbfe122d8 100644--- a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.test.ts+++ b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.test.ts@@ -1,3 +1,5 @@+import { expectLogic } from 'kea-test-utils'+import { initKeaTests } from '~/test/init'import { computeMoveEdges, hogFlowEditorLogic } from './hogFlowEditorLogic'@@ -466,6 +468,97 @@ describe('hogFlowEditorLogic', () => {})})+ describe('graph identity across rebuilds', () => {+ // Auto-save round-trips rebuild the graph from the workflow; without id-based+ // reconciliation every node and edge object is recreated each time and every ReactFlow+ // subtree re-renders, the detached-DOM churn this exists to prevent. Fixed timestamps so+ // two calls produce deep-equal flows.+ const makeFlow = (branchName: string = 'Branch'): HogFlow => ({+ id: 'test-flow',+ team_id: 1,+ version: 1,+ name: 'Test Flow',+ status: 'draft',+ exit_condition: 'exit_only_at_end',+ actions: [+ {+ id: 'trigger',+ name: 'Trigger',+ description: '',+ type: 'trigger',+ created_at: 1,+ updated_at: 1,+ config: { type: 'event', filters: {} },+ },+ {+ id: 'branch',+ name: branchName,+ description: '',+ type: 'conditional_branch',+ created_at: 1,+ updated_at: 1,+ config: { conditions: [{ filters: {} }] },+ },+ {+ id: 'exit',+ name: 'Exit',+ description: '',+ type: 'exit',+ created_at: 1,+ updated_at: 1,+ config: { reason: '' },+ },+ ],+ edges: [+ { from: 'trigger', to: 'branch', type: 'continue' },+ { from: 'branch', to: 'exit', type: 'branch', index: 0 },+ { from: 'branch', to: 'exit', type: 'continue' },+ ],+ updated_at: '2026-01-01T00:00:00Z',+ created_at: '2026-01-01T00:00:00Z',+ })++ // Each rebuild finishes by dispatching setNodesRaw from the async layout listener, and+ // kea-test-utils consumes matched actions in order, so awaiting one setNodesRaw per+ // rebuild is the deterministic "layout finished" signal.+ const applyFlow = async (flow: HogFlow): Promise<void> => {+ await expectLogic(logic, () => logic.actions.resetFlowFromHogFlow(flow)).toDispatchActions(['setNodesRaw'])+ }++ beforeEach(async () => {+ // Let the mount-time subscription rebuild (from workflowLogic's template flow) land+ // first so it can't clobber the flows the tests apply.+ await expectLogic(logic).toDispatchActions(['setNodesRaw'])+ })++ it('keeps node and edge references stable across a deep-equal rebuild', async () => {+ await applyFlow(makeFlow())+ const initialNodes = logic.values.nodes+ const initialEdges = logic.values.edges+ expect(initialNodes.length).toBeGreaterThan(0)++ // Freshly constructed but deep-equal, as an auto-save round-trip would deliver.+ await applyFlow(makeFlow())++ logic.values.nodes.forEach((node, index) => expect(node).toBe(initialNodes[index]))+ logic.values.edges.forEach((edge, index) => expect(edge).toBe(initialEdges[index]))+ })++ it('replaces only the changed node reference when one action changes', async () => {+ await applyFlow(makeFlow())+ const initialNodes = logic.values.nodes++ await applyFlow(makeFlow('Renamed branch'))++ const byId = (id: string): HogFlowActionNode | undefined =>+ logic.values.nodes.find((node) => node.id === id)+ expect(byId('trigger')).toBe(initialNodes.find((node) => node.id === 'trigger'))+ expect(byId('exit')).toBe(initialNodes.find((node) => node.id === 'exit'))+ expect(byId('branch')).not.toBe(initialNodes.find((node) => node.id === 'branch'))+ expect(byId('branch')?.data.name).toBe('Renamed branch')+ })+ })+describe('showDropzones branch-join placement', () => {const makeNode = (id: string): HogFlowActionNode =>({diff --git a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsxindex 722c602213d5..99b79ab98dab 100644--- a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx+++ b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx@@ -21,6 +21,7 @@ import { lemonToast } from '@posthog/lemon-ui'import { AppMetricsTotalsRequest, loadAppMetricsTotals } from 'lib/components/AppMetrics/appMetricsLogic'import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'import { uuid } from 'lib/utils/dom'+import { objectsEqual, reconcileById } from 'lib/utils/objects'import { urls } from 'scenes/urls'import { optOutCategoriesLogic } from '../../OptOuts/optOutCategoriesLogic'@@ -474,27 +475,31 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([const nodes: HogFlowActionNode[] = hogFlow.actions.map((action: HogFlowAction) => {const step = getHogFlowStep(action, values.hogFunctionTemplatesById)- if (!step) {- // Migrate old function actions to the basic functon action type- if (action.type.startsWith('function_')) {- action.type = 'function'- }- }+ // Migrate old function actions to the basic function action type without+ // writing back onto workflowLogic's action: an in-place mutation corrupts+ // the workflow subscription's previous-value snapshot, so legacy flows+ // would never compare deep-equal and would rebuild on every poll.+ const migratedAction: HogFlowAction =+ !step && action.type.startsWith('function_')+ ? ({ ...action, type: 'function' } as HogFlowAction)+ : actionreturn {- id: action.id,+ id: migratedAction.id,type: 'action',- data: action,+ data: migratedAction,position: { x: 0, y: 0 },- handles: Object.values(handlesByIdByNodeId[action.id] ?? {}),- deletable: !['trigger', 'exit'].includes(action.type),+ handles: Object.values(handlesByIdByNodeId[migratedAction.id] ?? {}),+ deletable: !['trigger', 'exit'].includes(migratedAction.type),selectable: true,draggable: false,connectable: false,}})- actions.setEdges(edges)+ // Reuse unchanged edge references so ReactFlow only reprocesses edges that+ // actually changed (matching its own applyEdgeChanges contract).+ actions.setEdges(reconcileById(values.edges, edges, (edge) => edge.id))actions.setNodes(nodes)} catch (error) {console.error('Error resetting flow from hog flow', error)@@ -502,10 +507,16 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([}},- setNodes: async ({ nodes }) => {+ setNodes: async ({ nodes }, breakpoint) => {const formattedNodes = await getFormattedNodes(nodes, values.edges)+ // Drop this layout run if a newer setNodes was dispatched while elk was working,+ // so overlapping rebuilds can't finish out of order and let a stale layout win.+ breakpoint()- actions.setNodesRaw(formattedNodes)+ // Reconcile after layout so positions participate in the equality check: a node+ // that moved gets a fresh reference, an untouched one keeps its identity and its+ // ReactFlow subtree doesn't re-render.+ actions.setNodesRaw(reconcileById(values.nodes, formattedNodes, (node) => node.id))},onNodesDelete: ({ deleted }) => {@@ -940,8 +951,10 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([}),subscriptions(({ actions }) => ({- workflow: (hogFlow?: HogFlow) => {- if (hogFlow) {+ workflow: (hogFlow?: HogFlow, oldHogFlow?: HogFlow) => {+ // Auto-save round-trips can emit a deep-equal workflow; skipping the rebuild avoids+ // re-deriving every node and edge (including the async layout pass) for no change.+ if (hogFlow && !objectsEqual(hogFlow, oldHogFlow)) {actions.resetFlowFromHogFlow(hogFlow)}},diff --git a/products/workflows/frontend/Workflows/hogflows/react_flow_utils/autolayout.ts b/products/workflows/frontend/Workflows/hogflows/react_flow_utils/autolayout.tsindex adc985f068d3..96138fc6a497 100644--- a/products/workflows/frontend/Workflows/hogflows/react_flow_utils/autolayout.ts+++ b/products/workflows/frontend/Workflows/hogflows/react_flow_utils/autolayout.ts@@ -96,8 +96,22 @@ export const getFormattedNodes = async (nodes: HogFlowActionNode[], edges: Edge[node.y = (node.y || 0) - offsetY})- return layoutedGraph.children?.map((node) => ({- ...node,- position: { x: node.x, y: node.y },- })) as HogFlowActionNode[]+ // Rebuild from the input nodes rather than spreading elk's children: elk annotates every+ // graph element it lays out with internal bookkeeping (e.g. a `$H` hash that differs per+ // run), which would leak into ReactFlow and make deep-equal layouts look changed. Handle+ // positions come from each node's `handles`, not node-level source/targetPosition, so+ // dropping elk's copies of those fields is safe.+ const layoutedById = new Map(layoutedGraph.children?.map((child) => [child.id, child]))+ return nodes.map((node) => {+ const layouted = layoutedById.get(node.id)+ if (!layouted) {+ console.warn(`[autolayout] elk did not return a position for node "${node.id}"; defaulting to (0, 0)`)+ }+ return {+ ...node,+ width: NODE_WIDTH,+ height: NODE_HEIGHT,+ position: { x: layouted?.x ?? 0, y: layouted?.y ?? 0 },+ }+ })}diff --git a/products/workflows/frontend/Workflows/workflowLogic.ts b/products/workflows/frontend/Workflows/workflowLogic.tsindex f7af4e13e7ea..81914160f963 100644--- a/products/workflows/frontend/Workflows/workflowLogic.ts+++ b/products/workflows/frontend/Workflows/workflowLogic.ts@@ -865,11 +865,16 @@ export const workflowLogic = kea<workflowLogicType>([return}- action.config = { ...config } as HogFlowAction['config']-- const changes = { actions: [...values.workflow.actions] } as Partial<HogFlow>- if (action.type === 'trigger') {- changes.trigger = action.config as TriggerAction['config']+ // Replace the action rather than mutating it: subscribers diff the workflow against+ // their previous snapshot, and an in-place write updates that snapshot too, making+ // every config edit look like a no-op.+ const updatedAction = { ...action, config: { ...config } as HogFlowAction['config'] }++ const changes = {+ actions: values.workflow.actions.map((a) => (a.id === actionId ? updatedAction : a)),+ } as Partial<HogFlow>+ if (updatedAction.type === 'trigger') {+ changes.trigger = updatedAction.config as TriggerAction['config']}actions.setWorkflowValues(changes)