: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): clear a stale staged draft when a disabled workflow saves live (#101505)
Luke Beltonfc29ea1f4923
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex d5b0f3b1968c..0c4f6eeea682 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -6601,10 +6601,13 @@ const api = {// `stage_draft` routes content edits on an active workflow into its staged draft instead of// the live config; publish promotes them. Ignored on non-active workflows.// `base_live_updated_at` fences a staged save's live metadata write the same way.+ // `includes_staged_draft` marks a full save on a non-active workflow that carries its staged+ // draft, so the server clears that draft.data: Partial<HogFlow> & {base_updated_at?: string | nullstage_draft?: booleanbase_live_updated_at?: string | null+ includes_staged_draft?: boolean}): Promise<HogFlow> {return await new ApiRequest().hogFlow(hogFlowId).update({ data })diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex 7ba52d813baa..2fba414aec0e 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -3813,6 +3813,9 @@ def mint_audience_confirm_token()+WRITABLE_DRAFT_CONTENT_FIELDS = frozenset(DRAFT_CONTENT_FIELDS) - frozenset(HogFlowSerializer.Meta.read_only_fields)++@extend_schema(extensions={"x-product": "workflows"})@extend_schema_view(list=extend_schema(@@ -4265,6 +4268,24 @@ class HogFlowViewSet(guard_timestamp = before_update.updated_at if before_update else Noneif route_to_draft and before_update and before_update.draft_updated_at:guard_timestamp = before_update.draft_updated_at+ # The web builder sends "includes_staged_draft" (raw body, like "stage_draft") when a save on+ # a non-active workflow carries the staged draft merged into it. The draft is only cleared on+ # that explicit signal, so an API caller that resends live content never loses a draft.+ clears_staged_draft = (+ not route_to_draft+ and before_update is not None+ and before_update.status != HogFlow.State.ACTIVE+ and before_update.draft is not None+ and bool(self.request.data.get("includes_staged_draft"))+ and WRITABLE_DRAFT_CONTENT_FIELDS <= self.request.data.keys()+ )+ if clears_staged_draft:+ assert before_update is not None+ # A revision restore writes the draft without moving the live stamp, so fence on the newer one.+ if before_update.draft_updated_at and (+ guard_timestamp is None or before_update.draft_updated_at > guard_timestamp+ ):+ guard_timestamp = before_update.draft_updated_atif base_updated_at and guard_timestamp and guard_timestamp > base_updated_at:raise StaleWorkflowUpdateError()@@ -4300,7 +4321,10 @@ class HogFlowViewSet(serializer.instance, before_update, serializer.validated_data.get("actions"))bump = self._stage_revision_bump(serializer.instance, before_update, serializer.validated_data)- serializer.save()+ if clears_staged_draft:+ serializer.save(draft=None, draft_updated_at=None, draft_encrypted_inputs=None)+ else:+ serializer.save()if bump:assert before_update is not Noneself._append_revisions(serializer.instance, before_update)diff --git a/products/workflows/backend/api/test/test_hog_flow_draft_publish.py b/products/workflows/backend/api/test/test_hog_flow_draft_publish.pyindex e2b4b1e38460..7352b6592888 100644--- a/products/workflows/backend/api/test/test_hog_flow_draft_publish.py+++ b/products/workflows/backend/api/test/test_hog_flow_draft_publish.py@@ -1,3 +1,5 @@+from datetime import timedelta+import time_machinefrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch@@ -8,6 +10,7 @@ from posthog.cdp.templates.hog_function_template import sync_template_to_dbfrom posthog.models.activity_logging.activity_log import ActivityLogfrom products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATES+from products.workflows.backend.api.hog_flow import WRITABLE_DRAFT_CONTENT_FIELDSfrom products.workflows.backend.models.hog_flow.hog_flow import HogFlowfrom products.workflows.backend.models.hog_flow_revision import HogFlowRevision@@ -51,6 +54,33 @@ class TestHogFlowDraftPublish(APIBaseTest):assert activate.status_code == 200, activate.json()return flow_id+ def _create_disabled_flow_with_staged_draft(self) -> str:+ flow_id = self._create_active_flow()+ staged = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",+ {+ "actions": [_trigger_action(), _webhook_action(url="https://staged.example.com")],+ "stage_draft": True,+ },+ )+ assert staged.status_code == 200, staged.json()+ disable = self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}", {"status": "draft"})+ assert disable.status_code == 200, disable.json()+ flow = HogFlow.objects.get(pk=flow_id)+ assert flow.draft is not None+ flow.draft_encrypted_inputs = {"action_1": {"api_key": "fake-draft-secret"}}+ flow.save(update_fields=["draft_encrypted_inputs"])+ return flow_id++ def _editor_save_payload(self, flow_id: str, url: str, includes_staged_draft: bool = True) -> dict:+ flow = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow_id}").json()+ payload = {field: flow[field] for field in WRITABLE_DRAFT_CONTENT_FIELDS}+ payload.update({field: value for field, value in (flow["draft"] or {}).items() if field in payload})+ payload["actions"] = [_trigger_action(), _webhook_action(url=url)]+ if includes_staged_draft:+ payload["includes_staged_draft"] = True+ return payload+def _patch_actions_via_mcp(self, flow_id: str, url: str = "https://changed.example.com"):# Graph content edits over MCP go through the surgical graph endpoint (a plain update# rejects actions/edges outright), so drafts are staged the way real agents stage them.@@ -234,23 +264,65 @@ class TestHogFlowDraftPublish(APIBaseTest):draft_urls = [a["config"]["inputs"]["url"]["value"] for a in draft["actions"] if a["type"] == "function"]assert draft_urls == ["https://second-draft.example.com"]- def test_stage_draft_on_inactive_flow_applies_live(self):- hog_flow = {"name": "Test Flow", "actions": [_trigger_action(), _webhook_action()]}- create = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)- flow_id = create.json()["id"]-- response = self.client.patch(- f"/api/projects/{self.team.id}/hog_flows/{flow_id}",- {- "actions": [_trigger_action(), _webhook_action(url="https://changed.example.com")],- "stage_draft": True,- },- )+ @parameterized.expand(+ [+ ("never_active_with_stage_draft", False, True),+ ("disabled_with_staged_draft", True, False),+ ("disabled_with_staged_draft_and_stage_draft", True, True),+ ]+ )+ def test_content_save_on_inactive_flow_applies_live_and_clears_draft(+ self, _name: str, disabled_with_staged_draft: bool, stage_draft: bool+ ):+ if disabled_with_staged_draft:+ flow_id = self._create_disabled_flow_with_staged_draft()+ else:+ hog_flow = {"name": "Test Flow", "actions": [_trigger_action(), _webhook_action()]}+ create = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)+ flow_id = create.json()["id"]++ payload = self._editor_save_payload(flow_id, url="https://saved.example.com")+ if stage_draft:+ payload["stage_draft"] = True+ response = self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}", payload)assert response.status_code == 200, response.json()+ assert response.json()["draft"] is Noneflow = HogFlow.objects.get(pk=flow_id)assert flow.draft is None+ assert flow.draft_updated_at is None+ assert flow.draft_encrypted_inputs is Nonelive_urls = [a["config"]["inputs"]["url"]["value"] for a in flow.actions if a["type"] == "function"]- assert live_urls == ["https://changed.example.com"]+ assert live_urls == ["https://saved.example.com"]++ @parameterized.expand(["metadata_only", "partial_content", "full_content_without_flag"])+ def test_save_on_disabled_flow_without_the_staged_draft_keeps_it(self, payload_kind: str):+ flow_id = self._create_disabled_flow_with_staged_draft()+ actions = [_trigger_action(), _webhook_action(url="https://saved.example.com")]+ if payload_kind == "metadata_only":+ payload: dict = {"name": "Renamed"}+ elif payload_kind == "partial_content":+ payload = {"actions": actions, "includes_staged_draft": True}+ else:+ payload = self._editor_save_payload(flow_id, url="https://saved.example.com", includes_staged_draft=False)++ response = self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}", payload)+ assert response.status_code == 200, response.json()+ draft = HogFlow.objects.get(pk=flow_id).draft+ assert draft is not None+ draft_urls = [a["config"]["inputs"]["url"]["value"] for a in draft["actions"] if a["type"] == "function"]+ assert draft_urls == ["https://staged.example.com"]++ def test_full_save_on_disabled_flow_is_rejected_when_the_draft_moved_after_load(self):+ flow_id = self._create_disabled_flow_with_staged_draft()+ payload = self._editor_save_payload(flow_id, url="https://saved.example.com")+ loaded = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow_id}").json()+ payload["base_updated_at"] = loaded["updated_at"]+ flow = HogFlow.objects.get(pk=flow_id)+ HogFlow.objects.filter(pk=flow_id).update(draft_updated_at=flow.updated_at + timedelta(minutes=1))++ response = self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}", payload)+ assert response.status_code == 409, response.json()+ assert HogFlow.objects.get(pk=flow_id).draft is not Nonedef test_mcp_content_edit_on_inactive_flow_applies_live(self):# Disabled/draft-status workflows edit in place — the draft cycle protects in-flight runs onlydiff --git a/products/workflows/frontend/Workflows/workflowLogic.autosave.test.ts b/products/workflows/frontend/Workflows/workflowLogic.autosave.test.tsindex 540481ba9d15..ff4cfed76676 100644--- a/products/workflows/frontend/Workflows/workflowLogic.autosave.test.ts+++ b/products/workflows/frontend/Workflows/workflowLogic.autosave.test.ts@@ -255,7 +255,8 @@ describe('workflowLogic auto-save', () => {const body = (await request.json()) as Record<string, any>patchBodies.push(body)// Server-faithful echo: a staged save keeps the live content and returns the- // new draft blob; a live save applies the payload.+ // new draft blob; a live save applies the payload, and clears the draft only+ // when the save says it carries it.return [200,body.stage_draft@@ -265,7 +266,9 @@ describe('workflowLogic auto-save', () => {draft: { actions: body.actions, edges: body.edges },draft_updated_at: '2026-05-02T00:00:00.000Z',}- : { ...getResponse, ...body },+ : body.includes_staged_draft+ ? { ...getResponse, ...body, draft: null, draft_updated_at: null }+ : { ...getResponse, ...body },]},},@@ -401,6 +404,39 @@ describe('workflowLogic auto-save', () => {expect(patchBodies[0].actions).toBeUndefined()expect(patchBodies[0].status).toBe('draft')})++ it('an edit to a disabled workflow with a leftover draft clears the draft and keeps the edit', async () => {+ useMocks(+ activeMocks({+ ...activeWorkflow,+ status: 'draft',+ draft: {+ actions: renameExit(activeWorkflow.actions, 'Staged exit'),+ edges: activeWorkflow.edges,+ },+ draft_updated_at: '2026-05-02T00:00:00.000Z',+ })+ )+ initKeaTests()+ logic = workflowLogic({ id: WORKFLOW_ID })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadWorkflowSuccess'])++ jest.useFakeTimers()+ logic.actions.setWorkflowValue(+ 'actions',+ renameExit(logic.values.workflow.actions, 'Edited while disabled')+ )+ await jest.advanceTimersByTimeAsync(3100)+ jest.useRealTimers()+ await expectLogic(logic).toDispatchActions(['saveWorkflowSuccess'])++ expect(patchBodies[0].stage_draft).toBeUndefined()+ expect(patchBodies[0].includes_staged_draft).toBe(true)+ expect(patchBodies[0].base_updated_at).toBe('2026-05-02T00:00:00.000Z')+ expect(logic.values.workflow.actions.find((a) => a.id === 'exit_node')?.name).toBe('Edited while disabled')+ expect(logic.values.hasStagedDraft).toBe(false)+ })})describe('auto-save toggle', () => {diff --git a/products/workflows/frontend/Workflows/workflowLogic.ts b/products/workflows/frontend/Workflows/workflowLogic.tsindex c2fb3ab2874d..9d20137ab2d0 100644--- a/products/workflows/frontend/Workflows/workflowLogic.ts+++ b/products/workflows/frontend/Workflows/workflowLogic.ts@@ -3213,12 +3213,23 @@ export const workflowLogic = kea<workflowLogicType>([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+ const includesStagedDraft =+ !stagingDraft && !isStatusTransition && latest?.status !== 'active' && !!latest?.draft+ const newestBase =+ latest?.draft_updated_at && liveBase && dayjs(latest.draft_updated_at).isAfter(liveBase)+ ? latest.draft_updated_at+ : liveBase+ const loadedBase = stagingDraft+ ? (latest?.draft_updated_at ?? liveBase)+ : includesStagedDraft+ ? newestBase+ : liveBasetry {const result = await api.hogFlows.updateHogFlow(props.id, {...payload,...(stagingDraft ? { stage_draft: true } : {}),+ ...(includesStagedDraft ? { includes_staged_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.