: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): surface the draft/publish cycle in the web editor (#81323)
Harley Alexander1e14440ca8ac
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex f7a821e664e4..ce857bcb4d53 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -252,6 +252,7 @@ import type {TaskRunCreateRequestSchemaApi,} from 'products/tasks/frontend/generated/api.schemas'import type { BlastRadiusApi } from 'products/workflows/frontend/generated/api.schemas'+import type { HogFlowPublishResponseApi } from 'products/workflows/frontend/generated/api.schemas'import type { MessageTemplate } from 'products/workflows/frontend/TemplateLibrary/types'import type { HogflowTestResult } from 'products/workflows/frontend/Workflows/hogflows/steps/types'import type {@@ -6718,10 +6719,28 @@ const api = {hogFlowId: HogFlow['id'],// `base_updated_at` is the updated_at the client loaded; the server rejects the write with a// 409 if the stored copy is newer (optimistic concurrency). Omit it for last-writer-wins.- data: Partial<HogFlow> & { base_updated_at?: string | null }+ // `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.+ data: Partial<HogFlow> & {+ base_updated_at?: string | null+ stage_draft?: boolean+ base_live_updated_at?: string | null+ }): Promise<HogFlow> {return await new ApiRequest().hogFlow(hogFlowId).update({ data })},+ async publishHogFlow(+ hogFlowId: HogFlow['id'],+ // Without `confirm` this only previews the impact and returns a `confirm_token`; a confirmed+ // publish must send that token back.+ data: { confirm: boolean; confirm_token?: string }+ ): Promise<HogFlowPublishResponseApi> {+ return await new ApiRequest().hogFlow(hogFlowId).withAction('publish').create({ data })+ },+ async discardHogFlowDraft(hogFlowId: HogFlow['id']): Promise<HogFlow> {+ return await new ApiRequest().hogFlow(hogFlowId).withAction('discard_draft').create()+ },async deleteHogFlow(hogFlowId: HogFlow['id']): Promise<void> {return await new ApiRequest().hogFlow(hogFlowId).delete()},diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex 41ac520fa89d..1fddfcc0c1e9 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -2530,6 +2530,15 @@ class HogFlowRevisionRestoreRequestSerializer(serializers.Serializer):"a draft is open returns 409."),)+ expected_draft_updated_at = serializers.DateTimeField(+ required=False,+ allow_null=True,+ help_text=(+ "The draft_updated_at of the staged draft this overwrite was confirmed against. If a draft "+ "exists with a different stamp (it was staged or edited since the confirmation was shown), "+ "the restore returns 409 instead of overwriting it. Omit to overwrite unconditionally."+ ),+ )class CommaSeparatedListFilter(BaseInFilter, CharFilter):@@ -2820,11 +2829,16 @@ class HogFlowViewSet(# Realtime "edited elsewhere" signal so an open builder (or another tab) can refresh instead of# clobbering edits made via a different channel (UI/MCP/API). Fires for every channel; the# frontend dedupes its own echo by comparing updated_at. Transient — no inbox notification.+ # Draft writes don't touch the live updated_at, so broadcast the newer of the two stamps;+ # otherwise an open builder never hears about content staged from another channel.+ edited_at = instance.updated_at+ if instance.draft_updated_at and instance.draft_updated_at > edited_at:+ edited_at = instance.draft_updated_atpublish_resource_edited(team=self.team,resource_type="HogFlow",resource_id=str(instance.id),- updated_at=instance.updated_at.isoformat(),+ updated_at=edited_at.isoformat(),actor_user_id=getattr(self.request.user, "id", None),ac_resource_type=self.scope_object,)@@ -2902,6 +2916,11 @@ class HogFlowViewSet(# PATCHes (the lifecycle tools) and metadata-only edits apply straight to the live row.if serializer.instance.status == HogFlow.State.ACTIVE and has_non_status:route_to_draft = bool(keys & set(DRAFT_CONTENT_FIELDS))+ elif serializer.instance.status == HogFlow.State.ACTIVE and self.request.data.get("stage_draft"):+ # The web builder opts into the same draft routing per request ("stage_draft" rides the+ # raw body like "base_updated_at"). Callers that don't send it keep deploy-on-save, so+ # existing raw-API automation is unaffected.+ route_to_draft = bool(set(self.request.data.keys()) & set(DRAFT_CONTENT_FIELDS))instance_id = serializer.instance.id@@ -2944,6 +2963,16 @@ class HogFlowViewSet(if k not in DRAFT_CONTENT_FIELDS and k != "billable_action_types"}if remaining:+ # The draft-stamp guard above doesn't protect this live write: a concurrent+ # live-metadata edit bumps updated_at but not draft_updated_at, so a staged save+ # would silently overwrite it. Clients that write metadata alongside a staged+ # draft send the live stamp they loaded as a second fence.+ base_live_raw = self.request.data.get("base_live_updated_at")+ base_live = parse_datetime(base_live_raw) if base_live_raw else None+ if base_live is not None and timezone.is_naive(base_live):+ base_live = timezone.make_aware(base_live)+ if base_live and before_update.updated_at and before_update.updated_at > base_live:+ raise StaleWorkflowUpdateError()serializer.validated_data.clear()serializer.validated_data.update(remaining)serializer.save()@@ -3455,7 +3484,12 @@ class HogFlowViewSet(locked.draft = Nonelocked.draft_updated_at = Nonelocked.draft_encrypted_inputs = None- locked.save(update_fields=["draft", "draft_updated_at", "draft_encrypted_inputs"])+ # updated_at (auto_now) is deliberately bumped: without a fresh live stamp the+ # resource_edited broadcast carries the old updated_at — older than the draft stamp+ # concurrent editors loaded, so they'd ignore the discard, and their next draft save+ # would pass the staleness guard (which falls back to the live stamp once the draft is+ # gone) and silently resurrect the discarded draft.+ locked.save(update_fields=["draft", "draft_updated_at", "draft_encrypted_inputs", "updated_at"])log_activity_from_viewset(self, locked, activity="draft_discarded", name=locked.name, previous=before_update)self._emit_resource_edited(locked)@@ -3513,6 +3547,16 @@ class HogFlowViewSet(raise exceptions.NotFound("No such revision for this workflow.")if locked.draft and not param_serializer.validated_data["overwrite"]:raise DraftExistsError()+ # Overwrite fencing: the client confirms against the draft stamp it saw. A draft staged+ # or edited between the confirmation dialog and this call carries a different stamp, and+ # overwriting it would lose unpublished content that no revision snapshots.+ expected_draft_updated_at = param_serializer.validated_data.get("expected_draft_updated_at")+ if (+ locked.draft+ and expected_draft_updated_at is not None+ and locked.draft_updated_at != expected_draft_updated_at+ ):+ raise StaleWorkflowUpdateError()# nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance for activity logging)before_update = HogFlow.objects.get(pk=instance.pk)locked.draft = dict(revision.content)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 966b81dcb4ae..aaa28beab91c 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@@ -9,6 +9,7 @@ from posthog.models.activity_logging.activity_log import ActivityLogfrom products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATESfrom products.workflows.backend.models.hog_flow.hog_flow import HogFlow+from products.workflows.backend.models.hog_flow_revision import HogFlowRevisionwebhook_template = MOCK_NODE_TEMPLATES[0]@@ -97,6 +98,106 @@ class TestHogFlowDraftPublish(APIBaseTest):live_urls = [a["config"]["inputs"]["url"]["value"] for a in flow.actions if a["type"] == "function"]assert live_urls == ["https://changed.example.com"]+ def test_web_content_edit_with_stage_draft_routes_to_draft_and_applies_metadata_live(self):+ flow_id = self._create_active_flow()+ live_actions_before = HogFlow.objects.get(pk=flow_id).actions++ response = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",+ {+ "actions": [_trigger_action(), _webhook_action(url="https://changed.example.com")],+ "name": "Renamed live",+ "stage_draft": True,+ },+ )+ assert response.status_code == 200, response.json()++ flow = HogFlow.objects.get(pk=flow_id)+ assert flow.actions == live_actions_before+ assert flow.draft is not None+ assert flow.draft_updated_at is not None+ draft_urls = [a["config"]["inputs"]["url"]["value"] for a in flow.draft["actions"] if a["type"] == "function"]+ assert draft_urls == ["https://changed.example.com"]+ assert flow.name == "Renamed live"+ assert response.json()["draft"] is not None++ def test_discard_bumps_live_stamp_so_stale_draft_saves_get_409(self):+ # Without the bump, a concurrent editor holding the discarded draft's stamp would pass the+ # staleness guard (which falls back to the live stamp once the draft is gone) and silently+ # resurrect the draft it never learned was discarded.+ flow_id = self._create_active_flow()+ staged = self._patch_actions_via_mcp(flow_id)+ assert staged.status_code == 200, staged.json()+ draft_stamp = HogFlow.objects.get(pk=flow_id).draft_updated_at+ assert draft_stamp is not None++ live_before_discard = HogFlow.objects.get(pk=flow_id).updated_at+ discard = self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/discard_draft")+ assert discard.status_code == 200, discard.json()+ flow = HogFlow.objects.get(pk=flow_id)+ assert flow.updated_at > live_before_discard++ resave = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",+ {+ "actions": [_trigger_action(), _webhook_action(url="https://resurrect.example.com")],+ "stage_draft": True,+ "base_updated_at": draft_stamp.isoformat(),+ },+ )+ assert resave.status_code == 409, resave.json()+ assert HogFlow.objects.get(pk=flow_id).draft is None++ def test_restore_with_stale_expected_draft_stamp_is_rejected_with_409(self):+ flow_id = self._create_active_flow()+ # Revisions only snapshot live-content changes, so make one to have a version to restore.+ live_edit = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",+ {"actions": [_trigger_action(), _webhook_action(url="https://live-v2.example.com")]},+ )+ assert live_edit.status_code == 200, live_edit.json()+ revision = (+ HogFlowRevision.objects.for_team(self.team.id).filter(hog_flow_id=flow_id).order_by("version").first()+ )+ assert revision is not None+ version = revision.version++ first = self._patch_actions_via_mcp(flow_id, url="https://first-draft.example.com")+ assert first.status_code == 200, first.json()+ stamp_at_dialog = HogFlow.objects.get(pk=flow_id).draft_updated_at+ assert stamp_at_dialog is not None++ second = self._patch_actions_via_mcp(flow_id, url="https://second-draft.example.com")+ assert second.status_code == 200, second.json()++ response = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/revisions/{version}/restore",+ {"overwrite": True, "expected_draft_updated_at": stamp_at_dialog.isoformat()},+ )+ assert response.status_code == 409, 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://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,+ },+ )+ assert response.status_code == 200, response.json()+ flow = HogFlow.objects.get(pk=flow_id)+ assert flow.draft is None+ live_urls = [a["config"]["inputs"]["url"]["value"] for a in flow.actions if a["type"] == "function"]+ assert live_urls == ["https://changed.example.com"]+def test_mcp_content_edit_on_inactive_flow_applies_live(self):# Disabled/draft-status workflows edit in place — the draft cycle protects in-flight runs onlyhog_flow = {"name": "Test Flow", "actions": [_trigger_action(), _webhook_action()]}diff --git a/products/workflows/frontend/Workflows/PublishImpactDialog.tsx b/products/workflows/frontend/Workflows/PublishImpactDialog.tsxnew file mode 100644index 000000000000..2eff95448dfc--- /dev/null+++ b/products/workflows/frontend/Workflows/PublishImpactDialog.tsx@@ -0,0 +1,123 @@+import { IconArrowRight } from '@posthog/icons'+import { LemonBanner, LemonDialog, LemonTable, LemonTag } from '@posthog/lemon-ui'++import type { HogFlowPublishImpactApi, HogFlowPublishImpactDeletedStepApi } from '../generated/api.schemas'++function PublishImpactContent({+ impact,+ inFlightRuns,+}: {+ impact: HogFlowPublishImpactApi | null+ inFlightRuns: number | null+}): JSX.Element {+ const deletedSteps = impact?.deleted_steps ?? []+ const emptyVariables = impact?.empty_variables ?? []+ const scheduleConflicts = impact?.schedule_conflicts ?? []++ return (+ <div className="flex flex-col gap-3">+ <p className="mb-0">+ This applies your staged changes to the live workflow.{' '}+ {inFlightRuns === null+ ? 'The number of people currently mid-run could not be determined.'+ : inFlightRuns === 0+ ? 'No one is currently mid-run.'+ : `${inFlightRuns} ${inFlightRuns === 1 ? 'person is' : 'people are'} currently mid-run and will continue on the published version.`}+ </p>+ {deletedSteps.length > 0 && (+ <div className="flex flex-col gap-1">+ <span className="font-semibold">Removed steps</span>+ <LemonTable<HogFlowPublishImpactDeletedStepApi>+ dataSource={deletedSteps}+ rowKey="action_id"+ size="small"+ columns={[+ {+ title: 'Step',+ key: 'name',+ render: (_, step) => step.name,+ },+ {+ title: 'People here now',+ key: 'runs',+ render: (_, step) => (step.runs === null ? 'Unknown' : step.runs),+ },+ {+ title: 'They will',+ key: 'outcome',+ render: (_, step) =>+ step.exits ? (+ <LemonTag type="danger">Exit the workflow</LemonTag>+ ) : (+ <span className="flex items-center gap-1">+ <IconArrowRight className="text-tertiary" />+ Move to {step.moves_to?.name ?? 'the next step'}+ </span>+ ),+ },+ ]}+ />+ {impact?.position_unknown ? (+ <span className="text-xs text-secondary">+ {impact.position_unknown} {impact.position_unknown === 1 ? 'person' : 'people'} mid-run+ could not be placed at a specific step.+ </span>+ ) : null}+ </div>+ )}+ {emptyVariables.length > 0 && (+ <LemonBanner type="warning">+ <div className="flex flex-col gap-1">+ <span>Some variables may be empty for people already mid-run:</span>+ <ul className="list-disc pl-4 mb-0">+ {emptyVariables.map((variable) => (+ <li key={variable.variable}>+ <code>{variable.variable}</code> is used by {variable.referenced_by.length}{' '}+ {variable.referenced_by.length === 1 ? 'step' : 'steps'} but only gets a value{' '}+ {variable.set_by ? 'from a step this draft adds or changes' : 'when a run starts'}.+ </li>+ ))}+ </ul>+ </div>+ </LemonBanner>+ )}+ {scheduleConflicts.length > 0 && (+ <LemonBanner type="warning">+ {(() => {+ const conflictVariables = new Set(scheduleConflicts.flatMap((conflict) => conflict.variables))+ return `This draft removes ${+ conflictVariables.size === 1 ? 'a variable' : `${conflictVariables.size} variables`+ } that ${+ scheduleConflicts.length === 1+ ? 'an existing schedule still sets'+ : 'existing schedules still set'+ }. Review the schedules after publishing.`+ })()}+ </LemonBanner>+ )}+ </div>+ )+}++export function openPublishConfirmDialog({+ impact,+ inFlightRuns,+ onConfirm,+}: {+ impact: HogFlowPublishImpactApi | null+ inFlightRuns: number | null+ onConfirm: () => void+}): void {+ LemonDialog.open({+ title: 'Publish staged changes?',+ maxWidth: '36rem',+ description: <PublishImpactContent impact={impact} inFlightRuns={inFlightRuns} />,+ primaryButton: {+ children: 'Publish',+ onClick: onConfirm,+ },+ secondaryButton: {+ children: 'Cancel',+ },+ })+}diff --git a/products/workflows/frontend/Workflows/Workflow.tsx b/products/workflows/frontend/Workflows/Workflow.tsxindex fcc191553c3e..3f2a0f1c0f70 100644--- a/products/workflows/frontend/Workflows/Workflow.tsx+++ b/products/workflows/frontend/Workflows/Workflow.tsx@@ -4,6 +4,7 @@ import { LemonBanner, LemonButton, SpinnerOverlay } from '@posthog/lemon-ui'import { HogFlowEditor } from './hogflows/HogFlowEditor'import { WorkflowLogicProps, workflowLogic } from './workflowLogic'+import { WorkflowStatusBar } from './WorkflowStatusBar'export function Workflow(props: WorkflowLogicProps): JSX.Element {const { originalWorkflow, workflowLoading, externallyEdited, isSyncingExternalEdit } = useValues(@@ -13,6 +14,7 @@ export function Workflow(props: WorkflowLogicProps): JSX.Element {return (<div className="flex flex-col grow relative border rounded-md">+ <WorkflowStatusBar {...props} />{/* Brief working/disabled overlay while we reconcile to an edit made elsewhere (clean state). */}{isSyncingExternalEdit && <SpinnerOverlay />}{externallyEdited && (diff --git a/products/workflows/frontend/Workflows/WorkflowRevisions.tsx b/products/workflows/frontend/Workflows/WorkflowRevisions.tsxnew file mode 100644index 000000000000..bc9fd7434d3d--- /dev/null+++ b/products/workflows/frontend/Workflows/WorkflowRevisions.tsx@@ -0,0 +1,111 @@+import { useActions, useValues } from 'kea'++import { LemonButton, LemonTable, LemonTag } from '@posthog/lemon-ui'++import { AccessControlAction } from 'lib/components/AccessControlAction'+import { TZLabel } from 'lib/components/TZLabel'+import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'++import { AccessControlLevel, AccessControlResourceType } from '~/types'+import type { UserBasicType } from '~/types'++import type { HogFlowRevisionBasicApi } from '../generated/api.schemas'+import { workflowLogic } from './workflowLogic'+import { workflowRevisionsLogic } from './workflowRevisionsLogic'++export function WorkflowRevisions({ id }: { id: string }): JSX.Element {+ const logic = workflowRevisionsLogic({ id })+ const { revisions, revisionsCount, revisionsResponseLoading, restoringVersion } = useValues(logic)+ const { restoreRevision } = useActions(logic)+ const { originalWorkflow, workflowUserAccessLevel } = useValues(workflowLogic({ id }))++ const liveVersion = originalWorkflow?.version++ return (+ <div className="flex flex-col gap-2">+ <div>+ <h3 className="mb-0">Versions</h3>+ <p className="text-secondary mb-0">+ A version is saved each time the live workflow changes. Restore one to open it as a draft, then+ publish it to go live.+ </p>+ </div>+ <LemonTable<HogFlowRevisionBasicApi>+ dataSource={revisions}+ loading={revisionsResponseLoading}+ rowKey="version"+ footer={+ revisionsCount > revisions.length ? (+ <div className="px-3 py-2 text-xs text-secondary">+ Showing the newest {revisions.length} of {revisionsCount} versions.+ </div>+ ) : undefined+ }+ emptyState="No versions yet. One is saved each time the live workflow changes."+ columns={[+ {+ title: 'Version',+ key: 'version',+ render: (_, revision) => (+ <span className="flex items-center gap-2 font-semibold">+ v{revision.version}+ {revision.version === liveVersion && <LemonTag type="success">Live</LemonTag>}+ </span>+ ),+ },+ {+ title: 'Changed by',+ key: 'created_by',+ render: (_, revision) =>+ revision.created_by ? (+ <span className="flex items-center gap-2">+ {/* The generated hedgehog_config shape differs from the app type in+ ways ProfilePicture never reads; the display fields match. */}+ <ProfilePicture user={revision.created_by as UserBasicType} size="md" showName />+ </span>+ ) : (+ <span className="text-secondary">API or system</span>+ ),+ },+ {+ title: 'Date',+ key: 'created_at',+ render: (_, revision) => <TZLabel time={revision.created_at} />,+ },+ {+ key: 'actions',+ width: 0,+ render: (_, revision) => (+ // The flex wrapper keeps the button at its intrinsic height instead of+ // stretching to the (avatar-driven) row height.+ <div className="flex items-center">+ <AccessControlAction+ resourceType={AccessControlResourceType.Workflow}+ minAccessLevel={AccessControlLevel.Editor}+ userAccessLevel={workflowUserAccessLevel ?? undefined}+ >+ <LemonButton+ type="secondary"+ size="xsmall"+ className="whitespace-nowrap"+ onClick={() => restoreRevision(revision.version)}+ loading={restoringVersion === revision.version}+ disabledReason={+ revision.version === liveVersion+ ? 'This is the live version'+ : restoringVersion !== null && restoringVersion !== revision.version+ ? 'Another restore is in progress'+ : undefined+ }+ >+ Restore as draft+ </LemonButton>+ </AccessControlAction>+ </div>+ ),+ },+ ]}+ />+ </div>+ )+}diff --git a/products/workflows/frontend/Workflows/WorkflowScene.tsx b/products/workflows/frontend/Workflows/WorkflowScene.tsxindex 86052e9d09fa..9dff474324d9 100644--- a/products/workflows/frontend/Workflows/WorkflowScene.tsx+++ b/products/workflows/frontend/Workflows/WorkflowScene.tsx@@ -1,17 +1,14 @@import clsx from 'clsx'-import { BindLogic, useActions, useValues } from 'kea'+import { BindLogic, useValues } from 'kea'import { router } from 'kea-router'import { useMemo } from 'react'-import { IconInfo } from '@posthog/icons'-import { LemonSwitch, Spinner, SpinnerOverlay } from '@posthog/lemon-ui'+import { SpinnerOverlay } from '@posthog/lemon-ui'import { ActivityLog } from 'lib/components/ActivityLog/ActivityLog'-import { LastSavedIndicator } from 'lib/components/LastSavedIndicator'import { NotFound } from 'lib/components/NotFound'import { useDebouncedValue } from 'lib/hooks/useDebouncedValue'import { LemonTab, LemonTabs } from 'lib/lemon-ui/LemonTabs'-import { Tooltip } from 'lib/lemon-ui/Tooltip'import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'import { sceneAgentPanelLogic } from 'scenes/max/sceneAgentPanelLogic'import { useSceneAgentPanel } from 'scenes/max/useSceneAgentPanel'@@ -29,6 +26,7 @@ import { WorkflowAssets } from './WorkflowAssets'import { WorkflowInvocations } from './WorkflowInvocations'import { workflowLogic } from './workflowLogic'import { WorkflowMetrics } from './WorkflowMetrics'+import { WorkflowRevisions } from './WorkflowRevisions'import { WorkflowSceneHeader } from './WorkflowSceneHeader'import { WorkflowSceneLogicProps, WorkflowTab, workflowSceneLogic } from './workflowSceneLogic'@@ -56,18 +54,9 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {const batchJobsLogic = batchWorkflowJobsLogic({ id: workflowSceneProps.id })const logic = workflowLogic({ id: props.id, templateId, editTemplateId })- const {- workflow,- workflowLoading,- originalWorkflow,- lastSavedAt,- isAutoSavePending,- autoSaveEnabled,- hogFunctionTemplatesById,- } = useValues(logic)- const { setAutoSaveEnabled } = useActions(logic)- const showSaving = useDebouncedValue(isAutoSavePending || workflowLoading, 1000)- const isDraft = originalWorkflow?.status === 'draft'+ // The save/auto-save indicators moved into the WorkflowStatusBar; the scene only needs the+ // workflow itself (for the agent context) and the load state.+ const { workflow, workflowLoading, originalWorkflow, hogFunctionTemplatesById } = useValues(logic)// Attach child logics to the scene logic so they persist across tab switchesuseAttachedLogic(batchJobsLogic, sceneLogic)@@ -148,7 +137,15 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {* If we're rendering tabs, props.id is guaranteed to be* defined and not "new" (see return statement below)*/- content: <ActivityLog id={workflowSceneProps.id!} scope={ActivityScope.HOG_FLOW} />,+ content: (+ <div className="flex flex-col gap-6">+ <WorkflowRevisions id={workflowSceneProps.id!} />+ <div className="flex flex-col gap-2">+ <h3 className="mb-0">Activity</h3>+ <ActivityLog id={workflowSceneProps.id!} scope={ActivityScope.HOG_FLOW} />+ </div>+ </div>+ ),},]@@ -165,35 +162,6 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {onChange={(tab) => router.actions.push(urls.workflow(props.id ?? 'new', tab))}tabs={tabs}sceneInset- rightSlot={- isDraft ? (- <span className="flex items-center gap-3">- {autoSaveEnabled && showSaving ? (- <span className="text-xs text-tertiary flex items-center gap-1">- <Spinner textColored /> Saving…- </span>- ) : lastSavedAt ? (- <LastSavedIndicator timestamp={lastSavedAt} />- ) : null}- <span className="flex items-center gap-1">- <LemonSwitch- checked={autoSaveEnabled}- onChange={setAutoSaveEnabled}- label="Auto-save"- size="small"- />- <Tooltip- title="Auto-save is only available for draft workflows. Active workflows require an explicit save to prevent unintended changes to live behavior."- placement="bottom"- >- <IconInfo className="text-tertiary size-4" />- </Tooltip>- </span>- </span>- ) : lastSavedAt ? (- <LastSavedIndicator timestamp={lastSavedAt} />- ) : null- }className={clsx({'flex flex-col grow [&>div]:flex [&>div]:flex-col [&>div]:grow': currentTab === 'workflow',})}diff --git a/products/workflows/frontend/Workflows/WorkflowSceneHeader.tsx b/products/workflows/frontend/Workflows/WorkflowSceneHeader.tsxindex 173c01879653..6e0c39de579a 100644--- a/products/workflows/frontend/Workflows/WorkflowSceneHeader.tsx+++ b/products/workflows/frontend/Workflows/WorkflowSceneHeader.tsx@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'import { router } from 'kea-router'import { useEffect, useRef, useState } from 'react'-import { IconArchive, IconCopy, IconScreen } from '@posthog/icons'+import { IconArchive, IconClock, IconCopy, IconScreen, IconTrash, IconUpload } from '@posthog/icons'import { LemonButton, LemonDivider } from '@posthog/lemon-ui'import { AccessControlAction } from 'lib/components/AccessControlAction'@@ -10,6 +10,7 @@ import { SceneMenuBarFileItems } from 'lib/components/Scenes/SceneMenuBarFileIteimport { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'+import { urls } from 'scenes/urls'import {SceneMenuBar,@@ -31,13 +32,23 @@ export const WorkflowSceneHeader = (props: WorkflowSceneLogicProps = {}): JSX.Elconst {workflow,hasUnsavedChanges,+ hasStagedDraft,+ draftActionPending,isWorkflowSubmitting,workflowLoading,workflowHasErrors,workflowUserAccessLevel,} = useValues(workflowLogic)- const { saveWorkflowPartial, submitWorkflow, setWorkflowValue, duplicate, archiveWorkflow, discardChanges } =- useActions(workflowLogic)+ const {+ saveWorkflowPartial,+ submitWorkflow,+ setWorkflowValue,+ duplicate,+ archiveWorkflow,+ discardChanges,+ publishDraft,+ discardDraft,+ } = useActions(workflowLogic)const { searchParams } = useValues(router)const editTemplateId = searchParams.editTemplateId as string | undefinedconst templateId = searchParams.templateId as string | undefined@@ -109,6 +120,66 @@ export const WorkflowSceneHeader = (props: WorkflowSceneLogicProps = {}): JSX.El<IconScreen />Save as template</SceneMenuBarItem>+ {hasStagedDraft && (+ <>+ <SceneMenuBarSeparator />+ <AccessControlAction+ resourceType={AccessControlResourceType.Workflow}+ minAccessLevel={AccessControlLevel.Editor}+ userAccessLevel={workflowUserAccessLevel ?? undefined}+ >+ {({ disabledReason }) => (+ <SceneMenuBarItem+ opensFloatingUi+ onClick={() => publishDraft()}+ data-attr="workflow-menubar-publish-draft"+ disabled={!!disabledReason || hasUnsavedChanges}+ tooltip={+ disabledReason ??+ (hasUnsavedChanges+ ? 'Save or clear your in-progress edits first'+ : undefined)+ }+ >+ <IconUpload />+ Publish draft+ </SceneMenuBarItem>+ )}+ </AccessControlAction>+ <AccessControlAction+ resourceType={AccessControlResourceType.Workflow}+ minAccessLevel={AccessControlLevel.Editor}+ userAccessLevel={workflowUserAccessLevel ?? undefined}+ >+ {({ disabledReason }) => (+ <SceneMenuBarItem+ variant="destructive"+ onClick={() => discardDraft()}+ data-attr="workflow-menubar-discard-draft"+ disabled={!!disabledReason || hasUnsavedChanges}+ tooltip={+ disabledReason ??+ (hasUnsavedChanges+ ? 'Save or clear your in-progress edits first'+ : undefined)+ }+ >+ <IconTrash />+ Discard draft+ </SceneMenuBarItem>+ )}+ </AccessControlAction>+ </>+ )}+ </SceneMenuBarMenu>+ <SceneMenuBarMenu label="View" dataAttr="workflow-menubar-view">+ <SceneMenuBarItem+ onClick={() => router.actions.push(urls.workflow(props.id!, 'history'))}+ data-attr="workflow-menubar-version-history"+ >+ <IconClock />+ Version history+ </SceneMenuBarItem></SceneMenuBarMenu></SceneMenuBar>)}@@ -219,6 +290,47 @@ 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.+ <>+ <AccessControlAction+ resourceType={AccessControlResourceType.Workflow}+ minAccessLevel={AccessControlLevel.Editor}+ userAccessLevel={workflowUserAccessLevel ?? undefined}+ >+ <LemonButton+ data-attr="workflow-discard-draft"+ type="secondary"+ size="small"+ status="danger"+ onClick={() => discardDraft()}+ loading={draftActionPending === 'discard'}+ disabledReason={+ draftActionPending === 'publish' ? 'Publishing is in progress' : undefined+ }+ >+ Discard draft+ </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+ }+ >+ Publish+ </LemonButton>+ </AccessControlAction>+ </>) : (<AccessControlActionresourceType={AccessControlResourceType.Workflow}@@ -245,7 +357,11 @@ export const WorkflowSceneHeader = (props: WorkflowSceneLogicProps = {}): JSX.El: 'No changes to save'}>- {props.id === 'new' ? 'Create as draft' : 'Save'}+ {props.id === 'new'+ ? 'Create as draft'+ : workflow?.status === 'active'+ ? 'Save draft'+ : 'Save'}</LemonButton></AccessControlAction>)}diff --git a/products/workflows/frontend/Workflows/WorkflowStatusBar.tsx b/products/workflows/frontend/Workflows/WorkflowStatusBar.tsxnew file mode 100644index 000000000000..6f8ceb093b9f--- /dev/null+++ b/products/workflows/frontend/Workflows/WorkflowStatusBar.tsx@@ -0,0 +1,96 @@+import { useValues, useActions } from 'kea'++import { IconClock, IconInfo } from '@posthog/icons'+import { LemonButton, LemonSwitch, LemonTag, Spinner, Tooltip } from '@posthog/lemon-ui'++import { LastSavedIndicator } from 'lib/components/LastSavedIndicator'+import { useDebouncedValue } from 'lib/hooks/useDebouncedValue'+import { urls } from 'scenes/urls'++import { WorkflowLogicProps, workflowLogic } from './workflowLogic'++/**+ * State narration for a saved workflow: what you're editing (live config vs staged draft), save+ * state, and the auto-save toggle. Deliberately no write actions here - save/publish/discard live+ * in the scene header with every other scene's primary actions, and in the scene menu bar.+ */+export function WorkflowStatusBar(props: WorkflowLogicProps): JSX.Element | null {+ const logic = workflowLogic(props)+ const {+ originalWorkflow,+ workflowLoading,+ hasUnsavedChanges,+ hasStagedDraft,+ isAutoSavePending,+ autoSaveEnabled,+ lastSavedAt,+ } = useValues(logic)+ const { setAutoSaveEnabled } = useActions(logic)+ const showSaving = useDebouncedValue(isAutoSavePending || workflowLoading, 1000)++ if (!props.id || props.id === 'new' || props.editTemplateId || !originalWorkflow) {+ return null+ }++ const isActive = originalWorkflow.status === 'active'+ const isEditingDraftOfLive = isActive && (hasStagedDraft || hasUnsavedChanges)++ return (+ <div className="flex items-center justify-between gap-2 px-2 py-1.5 border-b bg-surface-secondary rounded-t-md flex-wrap">+ <div className="flex items-center gap-3 min-w-0">+ {isEditingDraftOfLive ? (+ <LemonTag type="warning">Editing draft</LemonTag>+ ) : isActive ? (+ <LemonTag type="success">Live</LemonTag>+ ) : (+ <LemonTag>Draft</LemonTag>+ )}+ {isActive && (+ <span className="text-xs text-secondary truncate">+ {isEditingDraftOfLive+ ? 'The live version keeps running until you publish.'+ : 'Changes you make save as a draft.'}+ </span>+ )}+ </div>+ {/* Interactive controls sit right-anchored with variable-width text leftmost, so the+ toggle and History never shift as the narration or the timestamp changes. */}+ <div className="flex items-center gap-3 shrink-0">+ {autoSaveEnabled && showSaving ? (+ <span className="text-xs text-tertiary flex items-center gap-1">+ <Spinner textColored /> Saving…+ </span>+ ) : lastSavedAt ? (+ <LastSavedIndicator timestamp={lastSavedAt} />+ ) : null}+ <span className="flex items-center gap-1">+ <LemonSwitch+ checked={autoSaveEnabled}+ onChange={setAutoSaveEnabled}+ label="Auto-save"+ size="small"+ />+ <Tooltip+ title={+ isActive+ ? 'Auto-save stores your changes as a draft. Nothing goes live until you publish.'+ : 'Draft workflows auto-save as you edit.'+ }+ placement="bottom"+ >+ <IconInfo className="text-tertiary size-4" />+ </Tooltip>+ </span>+ <LemonButton+ type="tertiary"+ size="small"+ icon={<IconClock />}+ to={urls.workflow(props.id, 'history')}+ tooltip="See and restore previous versions"+ >+ History+ </LemonButton>+ </div>+ </div>+ )+}diff --git a/products/workflows/frontend/Workflows/hogflows/types.ts b/products/workflows/frontend/Workflows/hogflows/types.tsindex 94f3d9a420a5..ee91cf5f5e56 100644--- a/products/workflows/frontend/Workflows/hogflows/types.ts+++ b/products/workflows/frontend/Workflows/hogflows/types.ts@@ -83,7 +83,12 @@ export interface HogFlow extends z.infer<typeof HogFlowSchema> {created_by?: UserBasicType | null// Effective access level of the current user for this workflow (resource access control).user_access_level?: AccessControlLevel+ // Staged content changes awaiting publish (active workflows only). A full snapshot of the+ // content fields; null when nothing is staged. Read-only server state.+ draft?: Partial<HogFlow> | null+ draft_updated_at?: string | null}+export interface HogFlowEdge extends z.infer<typeof HogFlowEdgeSchema> {}export interface HogFlowActionEdge extends Edge<{ edge: HogFlowEdge; label?: string }> {}diff --git a/products/workflows/frontend/Workflows/workflowLogic.autosave.test.ts b/products/workflows/frontend/Workflows/workflowLogic.autosave.test.tsindex 06888af7367b..25d9add180ef 100644--- a/products/workflows/frontend/Workflows/workflowLogic.autosave.test.ts+++ b/products/workflows/frontend/Workflows/workflowLogic.autosave.test.ts@@ -176,32 +176,153 @@ describe('workflowLogic auto-save', () => {expect(logic.values.isAutoSavePending).toBe(false)expect(updateCalls).toBe(0)})+ })++ describe('active workflows stage drafts', () => {+ // Active-status validation requires the trigger to have at least one event, or every save+ // (auto-save included) is refused.+ const activeWorkflow = makeWorkflow({+ status: 'active',+ actions: makeWorkflow().actions.map((action) =>+ action.id === 'trigger_node'+ ? {+ ...action,+ config: {+ type: 'event',+ filters: { events: [{ id: '$pageview', name: '$pageview', type: 'events', order: 0 }] },+ },+ }+ : action+ ) as HogFlow['actions'],+ })+ let patchBodies: Record<string, any>[]++ const renameExit = (actions: HogFlow['actions'], name: string): HogFlow['actions'] =>+ actions.map((action) => (action.id === 'exit_node' ? { ...action, name } : action))- it('does not auto-save workflow loaded as active', async () => {- const activeWorkflow = makeWorkflow({ status: 'active' })- useMocks({- get: {- '/api/environments/:team_id/hog_flows/:id/': activeWorkflow,- '/api/projects/:team_id/hog_function_templates/': { results: [], count: 0 },+ // Passed to useMocks inside each test: a helper that calls useMocks itself trips the+ // rules-of-hooks lint (the "use" prefix reads as a React hook).+ const activeMocks = (getResponse: HogFlow): Parameters<typeof useMocks>[0] => ({+ get: {+ '/api/environments/:team_id/hog_flows/:id/': getResponse,+ '/api/projects/:team_id/hog_function_templates/': { results: [], count: 0 },+ },+ patch: {+ '/api/environments/:team_id/hog_flows/:id/': async ({ request }) => {+ updateCalls += 1+ 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.+ return [+ 200,+ body.stage_draft+ ? {+ ...getResponse,+ name: body.name ?? getResponse.name,+ draft: { actions: body.actions, edges: body.edges },+ draft_updated_at: '2026-05-02T00:00:00.000Z',+ }+ : { ...getResponse, ...body },+ ]},- patch: {- '/api/environments/:team_id/hog_flows/:id/': () => {- updateCalls += 1- return [200, activeWorkflow]+ },+ })++ beforeEach(() => {+ patchBodies = []+ })++ it('auto-saves an active workflow as a staged draft, keeping the edits on the canvas', async () => {+ useMocks(activeMocks(activeWorkflow))+ initKeaTests()+ logic = workflowLogic({ id: WORKFLOW_ID })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadWorkflowSuccess'])++ jest.useFakeTimers()+ logic.actions.setWorkflowValue('actions', renameExit(activeWorkflow.actions, 'Renamed exit'))+ // Fire the debounce under fake timers, then let the request itself run on real timers:+ // reading the mock request body (`request.json()`) parks on a macrotask fake timers never run.+ await jest.advanceTimersByTimeAsync(3100)+ jest.useRealTimers()+ await expectLogic(logic).toDispatchActions(['saveWorkflowSuccess'])++ expect(updateCalls).toBe(1)+ expect(patchBodies[0].stage_draft).toBe(true)+ // The staged-save echo carries the old live content plus the draft; rebaselining the form+ // must not wipe the just-saved edits off the canvas.+ expect(logic.values.workflow.actions.find((a) => a.id === 'exit_node')?.name).toBe('Renamed exit')+ expect(logic.values.hasStagedDraft).toBe(true)+ })++ it('opens the staged draft in the editor when one exists', async () => {+ useMocks(+ activeMocks({+ ...activeWorkflow,+ 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'])+ expect(logic.values.workflow.actions.find((a) => a.id === 'exit_node')?.name).toBe('Staged exit')+ expect(logic.values.hasStagedDraft).toBe(true)+ // The merged draft is the clean baseline, not an unsaved change.+ expect(logic.values.workflowChanged).toBe(false)+ })++ it('a metadata-only save on an active workflow applies live without staging a phantom draft', async () => {+ useMocks(activeMocks(activeWorkflow))initKeaTests()logic = workflowLogic({ id: WORKFLOW_ID })logic.mount()await expectLogic(logic).toDispatchActions(['loadWorkflowSuccess'])jest.useFakeTimers()- logic.actions.setWorkflowValue('name', 'Edited active')- await jest.advanceTimersByTimeAsync(3500)+ logic.actions.setWorkflowValue('name', 'Renamed active')+ await jest.advanceTimersByTimeAsync(3100)+ jest.useRealTimers()+ await expectLogic(logic).toDispatchActions(['saveWorkflowSuccess'])- expect(updateCalls).toBe(0)+ // Renaming must not route unchanged content into the draft slot: the body carries+ // neither content fields nor the staging flag.+ expect(patchBodies[0].stage_draft).toBeUndefined()+ expect(patchBodies[0].actions).toBeUndefined()+ expect(patchBodies[0].name).toBe('Renamed active')+ expect(logic.values.hasStagedDraft).toBe(false)+ })++ it('a status transition sends lifecycle and metadata only, never stage_draft', async () => {+ useMocks(+ activeMocks({+ ...activeWorkflow,+ 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'])++ await expectLogic(logic, () => {+ logic.actions.saveWorkflowPartial({ status: 'draft' })+ }).toDispatchActions(['saveWorkflowSuccess'])++ // Disabling must not deploy the staged draft the form is showing.+ expect(patchBodies[0].stage_draft).toBeUndefined()+ expect(patchBodies[0].actions).toBeUndefined()+ expect(patchBodies[0].status).toBe('draft')})})@@ -244,16 +365,6 @@ describe('workflowLogic auto-save', () => {await expectLogic(logic).toDispatchActions(['saveWorkflow', 'saveWorkflowSuccess'])expect(updateCalls).toBe(1)})-- it('does not auto-save active workflows', async () => {- jest.useFakeTimers()-- logic.actions.setWorkflowValue('status', 'active')- logic.actions.setWorkflowValue('name', 'Edited active')- await jest.advanceTimersByTimeAsync(3500)-- expect(updateCalls).toBe(0)- })})describe('navigation guard', () => {diff --git a/products/workflows/frontend/Workflows/workflowLogic.externalEdits.test.ts b/products/workflows/frontend/Workflows/workflowLogic.externalEdits.test.tsindex a47de8b8cf5d..485cc3784436 100644--- a/products/workflows/frontend/Workflows/workflowLogic.externalEdits.test.ts+++ b/products/workflows/frontend/Workflows/workflowLogic.externalEdits.test.ts@@ -127,6 +127,60 @@ describe('workflowLogic external edits', () => {expect(logic.values.isSyncingExternalEdit).toBe(false)})+ // The server emits resource_edited during our own PATCH/reload, and the SSE echo can land+ // before the HTTP response does. Reacting to it against the stale baseline flashed the+ // conflict banner at the user on every staged auto-save - but plain dropping would lose a+ // genuine concurrent edit arriving in the same window.+ it('defers events during our own flight, then reconciles genuine edits against the fresh baseline', async () => {+ logic.actions.setAutoSaveEnabled(false)+ logic.actions.setWorkflowValue('name', 'My local edit')+ expect(logic.values.hasUnsavedChanges).toBe(true)++ logic.actions.loadWorkflow()+ expect(logic.values.originalWorkflowLoading).toBe(true)+ resourceEditedLogic.actions.resourceEdited(makeEvent({ updated_at: NEWER }))++ // No banner while our own flight is up.+ expect(logic.values.externallyEdited).toBe(false)++ // Once the flight settles, the parked event replays. The loaded baseline is still older+ // than the event, so the (now clean) editor silently syncs with a fresh load - the event+ // is reconciled, not dropped.+ await expectLogic(logic).toDispatchActions([+ 'loadWorkflowSuccess',+ 'replayDeferredResourceEdited',+ 'setSyncingExternalEdit',+ 'loadWorkflowSuccess',+ ])+ expect(logic.values.externallyEdited).toBe(false)+ expect(getCalls).toBe(3)+ })++ it('ignores the echo of our own staged draft save', async () => {+ // A staged save doesn't bump the live updated_at; the emit broadcasts the draft stamp+ // instead. That echo must not read as an external edit, or every auto-save on an active+ // workflow would flash the conflict banner (or trigger a reload loop).+ const DRAFT_AT = '2026-05-15T00:00:00.000Z'+ useMocks({+ get: {+ '/api/environments/:team_id/hog_flows/:id/': () => {+ getCalls += 1+ return [200, makeWorkflow({ draft: { edges: [] }, draft_updated_at: DRAFT_AT })]+ },+ '/api/projects/:team_id/hog_function_templates/': { results: [], count: 0 },+ },+ })+ logic.actions.loadWorkflow()+ await expectLogic(logic).toDispatchActions(['loadWorkflowSuccess'])+ const baselineGets = getCalls++ resourceEditedLogic.actions.resourceEdited(makeEvent({ updated_at: DRAFT_AT }))+ await new Promise((resolve) => setTimeout(resolve, 0))++ expect(getCalls).toBe(baselineGets)+ expect(logic.values.externallyEdited).toBe(false)+ })+it('clears the banner and reloads when the user chooses Reload', async () => {logic.actions.setAutoSaveEnabled(false)logic.actions.setWorkflowValue('name', 'My local edit')diff --git a/products/workflows/frontend/Workflows/workflowLogic.ts b/products/workflows/frontend/Workflows/workflowLogic.tsindex e44f220c9228..19d1bc68d584 100644--- a/products/workflows/frontend/Workflows/workflowLogic.ts+++ b/products/workflows/frontend/Workflows/workflowLogic.ts@@ -15,6 +15,7 @@ import { dayjs } from 'lib/dayjs'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { publicWebhooksHostOrigin } from 'lib/utils/apiHost'import { LiquidRenderer } from 'lib/utils/liquid'+import { objectsEqual } from 'lib/utils/objects'import { sanitizeInputs } from 'scenes/hog-functions/configuration/hogFunctionConfigurationLogic'import type { EmailFieldErrors } from 'scenes/hog-functions/email-templater/types'import { projectLogic } from 'scenes/projectLogic'@@ -48,6 +49,7 @@ import {type HogFlowEdge,type HogFlowSchedule,} from './hogflows/types'+import { openPublishConfirmDialog } from './PublishImpactDialog'import { workflowSceneLogic } from './workflowSceneLogic'import { workflowsLogic } from './workflowsLogic'@@ -140,6 +142,41 @@ export function sanitizeWorkflow(return workflow}+/**+ * The content the editor should show: the staged draft overlaid on the live row. The draft blob is+ * a full snapshot of the content fields, so the merge is a plain spread. The draft bookkeeping+ * fields stay off the form value: they are read-only server state, and a form that carried them+ * would leak them back into save payloads.+ */+export function withStagedDraft(workflow: HogFlow): HogFlow {+ if (!workflow.draft) {+ return workflow+ }+ const { draft, draft_updated_at, ...rest } = workflow+ return { ...rest, ...draft } as HogFlow+}++// Mirrors DRAFT_CONTENT_FIELDS in products/workflows/backend/api/hog_flow.py: the fields the draft+// cycle stages and publish promotes. Keep the two lists in sync.+const WORKFLOW_CONTENT_FIELDS = [+ 'actions',+ 'edges',+ 'trigger',+ 'trigger_masking',+ 'conversion',+ 'exit_condition',+ 'abort_action',+ 'variables',+] as const++function omitWorkflowContent(workflow: HogFlow): Partial<HogFlow> {+ const result: Record<string, unknown> = { ...workflow }+ for (const field of WORKFLOW_CONTENT_FIELDS) {+ delete result[field]+ }+ return result as Partial<HogFlow>+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface workflowLogicValues {currentProjectId: number | null // projectLogic@@ -147,8 +184,11 @@ export interface workflowLogicValues {actionValidationErrorsById: Record<string, HogFlowActionValidationResult | null>autoSaveEnabled: booleancurrentSchedule: HogFlowSchedule | null+ deferredResourceEdited: ResourceEditedEvent | null+ draftActionPending: 'discard' | 'publish' | nulledgesByActionId: Record<string, HogFlowEdge[]>externallyEdited: boolean+ hasStagedDraft: booleanhasUnsavedChanges: booleanhogFunctionTemplatesById: Record<string, HogFunctionTemplateType>hogFunctionTemplatesByIdLoading: boolean@@ -212,9 +252,18 @@ export interface workflowLogicActions {clearAutoSavePending: () => {value: true}+ confirmDiscardDraft: () => {+ value: true+ }+ confirmPublishDraft: (confirmToken: string) => {+ confirmToken: string+ }discardChanges: () => {value: true}+ discardDraft: () => {+ value: true+ }duplicate: () => {value: true}@@ -2107,6 +2156,12 @@ export interface workflowLogicActions {}>}+ publishDraft: () => {+ value: true+ }+ replayDeferredResourceEdited: () => {+ value: true+ }resetWorkflow: (values?: HogFlow) => {values?: HogFlow}@@ -2131,6 +2186,12 @@ export interface workflowLogicActions {setAutoSaveEnabled: (enabled: boolean) => {enabled: boolean}+ setDeferredResourceEdited: (event: ResourceEditedEvent | null) => {+ event: ResourceEditedEvent | null+ }+ setDraftActionPending: (pending: 'discard' | 'publish' | null) => {+ pending: 'discard' | 'publish' | null+ }setExternallyEdited: (externallyEdited: boolean) => {externallyEdited: boolean}@@ -2672,6 +2733,7 @@ export interface workflowLogicMeta {workflow: HogFlow,hogFunctionTemplatesById: Record<string, HogFunctionTemplateType>) => HogFlow+ hasStagedDraft: (originalWorkflow: HogFlow | null) => boolean}}@@ -2733,6 +2795,13 @@ export const workflowLogic = kea<workflowLogicType>([setSyncingExternalEdit: (syncing: boolean) => ({ syncing }),setSaveBaseUpdatedAt: (updatedAt: string | null) => ({ updatedAt }),keepMyWorkflowVersion: true,+ publishDraft: true,+ confirmPublishDraft: (confirmToken: string) => ({ confirmToken }),+ discardDraft: true,+ confirmDiscardDraft: true,+ setDraftActionPending: (pending: 'publish' | 'discard' | null) => ({ pending }),+ setDeferredResourceEdited: (event: ResourceEditedEvent | null) => ({ event }),+ replayDeferredResourceEdited: true,}),loaders(({ props, values, actions }) => ({originalWorkflow: [@@ -2785,12 +2854,57 @@ export const workflowLogic = kea<workflowLogicType>([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+try {return await api.hogFlows.updateHogFlow(props.id, {- ...updates,+ ...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 ?? values.originalWorkflow?.updated_at ?? null,+ base_updated_at: values.saveBaseUpdatedAt ?? loadedBase ?? null,})} catch (error) {if (error instanceof ApiError && error.status === 409) {@@ -2916,7 +3030,11 @@ export const workflowLogic = kea<workflowLogicType>([null as string | null,{saveWorkflowSuccess: () => dayjs().toISOString(),- loadWorkflowSuccess: (_, { originalWorkflow }) => originalWorkflow?.updated_at ?? null,+ // Staged drafts don't bump the live updated_at, so the draft stamp is the real last+ // save. The cast collapses the loader's union: its template/new branches build+ // literals without the draft bookkeeping fields.+ loadWorkflowSuccess: (_, { originalWorkflow }) =>+ (originalWorkflow as HogFlow | null)?.draft_updated_at ?? originalWorkflow?.updated_at ?? null,},],isAutoSavePending: [@@ -2980,6 +3098,23 @@ export const workflowLogic = kea<workflowLogicType>([saveWorkflowSuccess: () => null,},],+ // Which staged-draft action is in flight, driving the banner buttons' loading/disabled state+ // so publish and discard can't race each other or double-submit.+ draftActionPending: [+ null as 'publish' | 'discard' | null,+ {+ setDraftActionPending: (_, { 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: [@@ -3279,6 +3414,11 @@ export const workflowLogic = kea<workflowLogicType>([return sanitizeWorkflow(workflow, hogFunctionTemplatesById)},],++ hasStagedDraft: [+ (s) => [s.originalWorkflow],+ (originalWorkflow: HogFlow | null): boolean => !!originalWorkflow?.draft,+ ],}),listeners(({ actions, values, props }) => ({setScheduleStartsAtFromPicker: ({ pickerDate }) => {@@ -3311,7 +3451,28 @@ export const workflowLogic = kea<workflowLogicType>([if (event.resource_type !== 'HogFlow' || event.resource_id !== props.id) {return}- const loadedUpdatedAt = values.originalWorkflow?.updated_at+ // 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) {+ 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.@@ -3328,6 +3489,79 @@ export const workflowLogic = kea<workflowLogicType>([actions.loadWorkflow()}},+ publishDraft: async () => {+ if (!props.id || props.id === 'new' || values.draftActionPending) {+ return+ }+ actions.setDraftActionPending('publish')+ let preview+ try {+ // Two-step publish: the unconfirmed call only previews the impact and mints the token+ // a confirmed publish must return, so a stale draft can never be promoted blind.+ preview = await api.hogFlows.publishHogFlow(props.id, { confirm: false })+ } catch {+ lemonToast.error('Could not load the publish preview. Please try again.')+ return+ } finally {+ actions.setDraftActionPending(null)+ }+ openPublishConfirmDialog({+ impact: preview.impact,+ inFlightRuns: preview.in_flight_runs,+ onConfirm: () => actions.confirmPublishDraft(preview.confirm_token ?? ''),+ })+ },+ confirmPublishDraft: async ({ confirmToken }) => {+ // draftActionPending also guards the dialog's close-animation window, where a fast+ // double-click on the confirm button dispatches twice.+ if (!props.id || props.id === 'new' || values.draftActionPending) {+ return+ }+ actions.setDraftActionPending('publish')+ try {+ await api.hogFlows.publishHogFlow(props.id, { confirm: true, confirm_token: confirmToken })+ lemonToast.success('Changes published')+ actions.loadWorkflow()+ } catch {+ // Covers a stale/expired token (the draft moved since the preview) and plain failures.+ lemonToast.error('Publishing failed. Review the staged changes and try again.')+ actions.loadWorkflow()+ } finally {+ actions.setDraftActionPending(null)+ }+ },+ discardDraft: () => {+ if (!props.id || props.id === 'new' || values.draftActionPending) {+ return+ }+ LemonDialog.open({+ title: 'Discard staged changes?',+ description: 'This throws away the staged changes. The live workflow is unaffected.',+ primaryButton: {+ children: 'Discard',+ status: 'danger',+ onClick: () => actions.confirmDiscardDraft(),+ },+ secondaryButton: {+ children: 'Cancel',+ },+ })+ },+ confirmDiscardDraft: async () => {+ if (!props.id || props.id === 'new' || values.draftActionPending) {+ return+ }+ actions.setDraftActionPending('discard')+ try {+ await api.hogFlows.discardHogFlowDraft(props.id)+ lemonToast.success('Staged changes discarded')+ actions.loadWorkflow()+ } catch {+ lemonToast.error('Could not discard the staged changes. Please try again.')+ } finally {+ actions.setDraftActionPending(null)+ }+ },keepMyWorkflowVersion: async () => {// The user wants their in-progress edits to win. Adopt the latest server updated_at as the// save baseline (without touching their canvas) so the next save passes the optimistic-lock@@ -3335,7 +3569,8 @@ export const workflowLogic = kea<workflowLogicType>([if (props.id && props.id !== 'new') {try {const latest = await api.hogFlows.getHogFlow(props.id)- actions.setSaveBaseUpdatedAt(latest.updated_at)+ // On an active workflow the next save races the draft slot, so its stamp is the baseline.+ actions.setSaveBaseUpdatedAt(latest.draft_updated_at ?? latest.updated_at)} catch {// If we can't fetch the latest timestamp, just dismiss; the 409 backstop still protects them.}@@ -3357,7 +3592,9 @@ export const workflowLogic = kea<workflowLogicType>([actions.saveWorkflow(merged)},loadWorkflowSuccess: async ({ originalWorkflow }) => {- actions.resetWorkflow(originalWorkflow)+ // The form edits the staged draft when one exists; the live config keeps running underneath.+ actions.resetWorkflow(withStagedDraft(originalWorkflow))+ actions.replayDeferredResourceEdited()const triggerType = originalWorkflow.trigger?.typeif (originalWorkflow.id && SCHEDULED_TRIGGER_TYPES.includes(triggerType ?? '')) {try {@@ -3368,6 +3605,19 @@ export const workflowLogic = kea<workflowLogicType>([}}},+ loadWorkflowFailure: () => {+ actions.replayDeferredResourceEdited()+ },+ saveWorkflowFailure: () => {+ actions.replayDeferredResourceEdited()+ },+ replayDeferredResourceEdited: () => {+ const deferred = values.deferredResourceEdited+ if (deferred) {+ actions.setDeferredResourceEdited(null)+ actions.resourceEdited(deferred)+ }+ },saveWorkflowSuccess: async ({ originalWorkflow }) => {const isAutoSave = values.isAutoSave@@ -3404,7 +3654,18 @@ export const workflowLogic = kea<workflowLogicType>([}}- lemonToast.success('Workflow saved')+ if (originalWorkflow.draft) {+ // Saving used to deploy immediately, so the changed contract needs a loud cue at+ // the moment of saving, not only the status bar.+ lemonToast.success('Draft saved. The live version keeps running until you publish.', {+ button: {+ label: 'Publish',+ action: () => actions.publishDraft(),+ },+ })+ } else {+ lemonToast.success('Workflow saved')+ }if (props.id === 'new') {tryShowMCPHint('workflows.create')@@ -3455,8 +3716,11 @@ export const workflowLogic = kea<workflowLogicType>([globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(tasksToMarkAsCompleted)}- actions.resetWorkflow(originalWorkflow)+ // A staged save's response carries the live config plus the new draft blob: rebaseline the+ // form on the merged view, or the reset would wipe the just-saved edits off the canvas.+ actions.resetWorkflow(withStagedDraft(originalWorkflow))actions.markAutoSave(false)+ actions.replayDeferredResourceEdited()},discardChanges: () => {if (!values.originalWorkflow) {@@ -3468,7 +3732,10 @@ export const workflowLogic = kea<workflowLogicType>([description: 'Are you sure?',primaryButton: {children: 'Discard',- onClick: () => actions.resetWorkflow(values.originalWorkflow ?? NEW_WORKFLOW),+ onClick: () =>+ actions.resetWorkflow(+ values.originalWorkflow ? withStagedDraft(values.originalWorkflow) : NEW_WORKFLOW+ ),},secondaryButton: {children: 'Cancel',@@ -3532,12 +3799,13 @@ export const workflowLogic = kea<workflowLogicType>([autoSaveWorkflow: async (_, breakpoint) => {await breakpoint(3000)+ // Active workflows auto-save too: their content edits route into the staged draft+ // (stage_draft in the saveWorkflow loader), so nothing deploys without an explicit publish.const shouldSkip =!values.autoSaveEnabled ||!props.id ||props.id === 'new' ||!!props.editTemplateId ||- values.workflow.status === 'active' ||!values.workflowChanged ||values.workflowHasErrorsdiff --git a/products/workflows/frontend/Workflows/workflowRevisionsLogic.test.ts b/products/workflows/frontend/Workflows/workflowRevisionsLogic.test.tsnew file mode 100644index 000000000000..94cd0dab934a--- /dev/null+++ b/products/workflows/frontend/Workflows/workflowRevisionsLogic.test.ts@@ -0,0 +1,73 @@+import { router } from 'kea-router'+import { expectLogic } from 'kea-test-utils'++import { urls } from 'scenes/urls'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { workflowLogic } from './workflowLogic'+import { workflowRevisionsLogic } from './workflowRevisionsLogic'++const WORKFLOW_ID = 'wf-revisions-1'++describe('workflowRevisionsLogic', () => {+ let logic: ReturnType<typeof workflowRevisionsLogic.build>+ let restoreBodies: Record<string, any>[]++ beforeEach(() => {+ restoreBodies = []+ useMocks({+ get: {+ '/api/environments/:team_id/hog_flows/:id/': {+ id: WORKFLOW_ID,+ name: 'Test',+ version: 3,+ status: 'active',+ actions: [],+ edges: [],+ updated_at: '2026-05-01T00:00:00.000Z',+ },+ '/api/projects/:team_id/hog_flows/:id/revisions': {+ count: 2,+ results: [+ { version: 3, created_at: '2026-05-01T00:00:00.000Z', created_by: null },+ { version: 2, created_at: '2026-04-01T00:00:00.000Z', created_by: null },+ ],+ },+ '/api/projects/:team_id/hog_function_templates/': { results: [], count: 0 },+ },+ post: {+ '/api/projects/:team_id/hog_flows/:id/revisions/:version/restore': async ({ request }) => {+ restoreBodies.push((await request.json()) as Record<string, any>)+ return [200, { id: WORKFLOW_ID }]+ },+ },+ })+ initKeaTests()+ logic = workflowRevisionsLogic({ id: WORKFLOW_ID })+ logic.mount()+ })++ it('loads revisions on mount', async () => {+ await expectLogic(logic).toDispatchActions(['loadRevisionsSuccess'])+ expect(logic.values.revisions.map((revision) => revision.version)).toEqual([3, 2])+ })++ // Restore must send overwrite (the confirm dialog already warned about replacing a staged+ // draft), rebase the open canvas on the restored draft, and land the user back on it.+ it('confirmRestoreRevision restores with overwrite, reloads the workflow, and navigates to the canvas', async () => {+ const flowLogic = workflowLogic({ id: WORKFLOW_ID })+ flowLogic.mount()+ await expectLogic(flowLogic).toDispatchActions(['loadWorkflowSuccess'])++ await expectLogic(logic, () => {+ logic.actions.confirmRestoreRevision(2, null)+ }).toDispatchActions([flowLogic.actionTypes.loadWorkflow])++ expect(restoreBodies).toEqual([{ overwrite: true, expected_draft_updated_at: null }])+ // The router projects the path under /project/:id.+ expect(router.values.location.pathname).toContain(urls.workflow(WORKFLOW_ID, 'workflow'))+ expect(logic.values.restoringVersion).toBeNull()+ })+})diff --git a/products/workflows/frontend/Workflows/workflowRevisionsLogic.ts b/products/workflows/frontend/Workflows/workflowRevisionsLogic.tsnew file mode 100644index 000000000000..fb71fdb2d3a5--- /dev/null+++ b/products/workflows/frontend/Workflows/workflowRevisionsLogic.ts@@ -0,0 +1,176 @@+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { router } from 'kea-router'++import { ApiError } from 'lib/api'+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'+import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'++import { hogFlowsRevisionsList, hogFlowsRevisionsRestoreCreate } from '../generated/api'+import type { HogFlowRevisionBasicApi, PaginatedHogFlowRevisionBasicListApi } from '../generated/api.schemas'+import type { HogFlow } from './hogflows/types'+import { workflowLogic } from './workflowLogic'++export interface WorkflowRevisionsLogicProps {+ id: string+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface workflowRevisionsLogicValues {+ currentTeamIdStrict: number | string // teamLogic+ hasStagedDraft: boolean // workflowLogic+ originalWorkflow: HogFlow | null // workflowLogic+ restoringVersion: number | null+ revisions: HogFlowRevisionBasicApi[]+ revisionsCount: number+ revisionsResponse: PaginatedHogFlowRevisionBasicListApi | null+ revisionsResponseLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface workflowRevisionsLogicActions {+ confirmRestoreRevision: (+ version: number,+ expectedDraftUpdatedAt: string | null+ ) => {+ expectedDraftUpdatedAt: string | null+ version: number+ }+ loadRevisions: () => any+ loadRevisionsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadRevisionsSuccess: (+ revisionsResponse: PaginatedHogFlowRevisionBasicListApi,+ payload?: any+ ) => {+ revisionsResponse: PaginatedHogFlowRevisionBasicListApi+ payload?: any+ }+ restoreRevision: (version: number) => {+ version: number+ }+ setRestoringVersion: (version: number | null) => {+ version: number | null+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface workflowRevisionsLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ revisions: (revisionsResponse: PaginatedHogFlowRevisionBasicListApi | null) => HogFlowRevisionBasicApi[]+ revisionsCount: (revisionsResponse: PaginatedHogFlowRevisionBasicListApi | null) => number+ }+}++export type workflowRevisionsLogicType = MakeLogicType<+ workflowRevisionsLogicValues,+ workflowRevisionsLogicActions,+ WorkflowRevisionsLogicProps,+ workflowRevisionsLogicMeta+>++export const workflowRevisionsLogic = kea<workflowRevisionsLogicType>([+ path(['products', 'workflows', 'frontend', 'Workflows', 'workflowRevisionsLogic']),+ props({} as WorkflowRevisionsLogicProps),+ key(({ id }) => id),+ connect(({ id }: WorkflowRevisionsLogicProps) => ({+ values: [teamLogic, ['currentTeamIdStrict'], workflowLogic({ id }), ['hasStagedDraft', 'originalWorkflow']],+ })),+ actions({+ restoreRevision: (version: number) => ({ version }),+ confirmRestoreRevision: (version: number, expectedDraftUpdatedAt: string | null) => ({+ version,+ expectedDraftUpdatedAt,+ }),+ setRestoringVersion: (version: number | null) => ({ version }),+ }),+ reducers({+ restoringVersion: [+ null as number | null,+ {+ setRestoringVersion: (_, { version }) => version,+ },+ ],+ }),+ loaders(({ props, values }) => ({+ revisionsResponse: [+ null as PaginatedHogFlowRevisionBasicListApi | null,+ {+ loadRevisions: async () => {+ return await hogFlowsRevisionsList(String(values.currentTeamIdStrict), props.id)+ },+ },+ ],+ })),+ selectors({+ revisions: [+ (s) => [s.revisionsResponse],+ (response: PaginatedHogFlowRevisionBasicListApi | null): HogFlowRevisionBasicApi[] =>+ response?.results ?? [],+ ],+ revisionsCount: [+ (s) => [s.revisionsResponse],+ (response: PaginatedHogFlowRevisionBasicListApi | null): number => response?.count ?? 0,+ ],+ }),+ listeners(({ actions, props, values }) => ({+ restoreRevision: ({ version }) => {+ if (values.restoringVersion !== null) {+ return+ }+ // The stamp of the draft this confirmation is about. The restore sends it as a fence, so+ // a draft staged or edited after this dialog opened returns 409 instead of being clobbered.+ const expectedDraftUpdatedAt = values.originalWorkflow?.draft_updated_at ?? null+ LemonDialog.open({+ title: `Restore version ${version} as draft?`,+ description: values.hasStagedDraft+ ? 'This replaces your current staged draft with this version. The live workflow keeps running until you publish.'+ : 'This version opens on the canvas as a draft. The live workflow keeps running until you publish.',+ primaryButton: {+ children: 'Restore as draft',+ onClick: () => actions.confirmRestoreRevision(version, expectedDraftUpdatedAt),+ },+ secondaryButton: {+ children: 'Cancel',+ },+ })+ },+ confirmRestoreRevision: async ({ version, expectedDraftUpdatedAt }) => {+ if (values.restoringVersion !== null) {+ return+ }+ actions.setRestoringVersion(version)+ try {+ // overwrite only replaces the draft the confirm dialog warned about: the expected+ // stamp fences the write, so a draft that changed since returns 409 below.+ await hogFlowsRevisionsRestoreCreate(String(values.currentTeamIdStrict), props.id, version, {+ overwrite: true,+ expected_draft_updated_at: expectedDraftUpdatedAt,+ })+ lemonToast.success(`Version ${version} restored as draft`)+ workflowLogic({ id: props.id }).actions.loadWorkflow()+ router.actions.push(urls.workflow(props.id, 'workflow'))+ } catch (error) {+ if (error instanceof ApiError && error.status === 409) {+ lemonToast.error('The staged draft changed while you were confirming. Review it and try again.')+ workflowLogic({ id: props.id }).actions.loadWorkflow()+ } else {+ lemonToast.error('Could not restore this version. Please try again.')+ }+ } finally {+ actions.setRestoringVersion(null)+ }+ },+ })),+ afterMount(({ actions }) => {+ actions.loadRevisions()+ }),+])diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.tsindex 4eb4769316ec..374648893982 100644--- a/products/workflows/frontend/generated/api.schemas.ts+++ b/products/workflows/frontend/generated/api.schemas.ts@@ -1105,6 +1105,11 @@ export interface HogFlowRevisionApi {export interface HogFlowRevisionRestoreRequestApi {/** Replace the open staged draft with this revision's content. Without it, restoring while a draft is open returns 409. */overwrite?: boolean+ /**+ * The draft_updated_at of the staged draft this overwrite was confirmed against. If a draft exists with a different stamp (it was staged or edited since the confirmation was shown), the restore returns 409 instead of overwriting it. Omit to overwrite unconditionally.+ * @nullable+ */+ expected_draft_updated_at?: string | null}export interface PatchedHogFlowScheduleApi {diff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.tsindex 7a4e38dfd0dd..cd97a9fd0d4f 100644--- a/products/workflows/frontend/generated/api.zod.ts+++ b/products/workflows/frontend/generated/api.zod.ts@@ -2201,6 +2201,12 @@ export const HogFlowsRevisionsRestoreCreateBody = /* @__PURE__ */ zod.object({.describe("Replace the open staged draft with this revision's content. Without it, restoring while a draft is open returns 409."),+ expected_draft_updated_at: zod.iso+ .datetime({ offset: true })+ .nullish()+ .describe(+ 'The draft_updated_at of the staged draft this overwrite was confirmed against. If a draft exists with a different stamp (it was staged or edited since the confirmation was shown), the restore returns 409 instead of overwriting it. Omit to overwrite unconditionally.'+ ),})export const hogFlowsSchedulesCreateBodyTimezoneMax = 64diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex ea6d1bc33e4a..ed5a2abda3f8 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -37525,6 +37525,11 @@ export namespace Schemas {export interface HogFlowRevisionRestoreRequest {/** Replace the open staged draft with this revision's content. Without it, restoring while a draft is open returns 409. */overwrite?: boolean;+ /**+ * The draft_updated_at of the staged draft this overwrite was confirmed against. If a draft exists with a different stamp (it was staged or edited since the confirmation was shown), the restore returns 409 instead of overwriting it. Omit to overwrite unconditionally.+ * @nullable+ */+ expected_draft_updated_at?: string | null;}/**diff --git a/services/mcp/src/generated/workflows/api.ts b/services/mcp/src/generated/workflows/api.tsindex b5621ff1a909..36090ae90e1a 100644--- a/services/mcp/src/generated/workflows/api.ts+++ b/services/mcp/src/generated/workflows/api.ts@@ -962,6 +962,12 @@ export const HogFlowsRevisionsRestoreCreateBody = /* @__PURE__ */ zod.object({.describe("Replace the open staged draft with this revision's content. Without it, restoring while a draft is open returns 409."),+ expected_draft_updated_at: zod.iso+ .datetime({ offset: true })+ .nullish()+ .describe(+ 'The draft_updated_at of the staged draft this overwrite was confirmed against. If a draft exists with a different stamp (it was staged or edited since the confirmation was shown), the restore returns 409 instead of overwriting it. Omit to overwrite unconditionally.'+ ),})export const HogFlowsSchedulesPartialUpdateParams = /* @__PURE__ */ zod.object({diff --git a/services/mcp/src/tools/generated/workflows.ts b/services/mcp/src/tools/generated/workflows.tsindex 85e9e8fa1709..1c6b0c3e3abf 100644--- a/services/mcp/src/tools/generated/workflows.ts+++ b/services/mcp/src/tools/generated/workflows.ts@@ -361,6 +361,9 @@ const workflowsRestoreRevision = (): ToolBase<typeof WorkflowsRestoreRevisionSchif (params.overwrite !== undefined) {body['overwrite'] = params.overwrite}+ if (params.expected_draft_updated_at !== undefined) {+ body['expected_draft_updated_at'] = params.expected_draft_updated_at+ }const result = await context.api.request<Schemas.HogFlow>({method: 'POST',path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.id))}/revisions/${encodeURIComponent(String(params.version))}/restore/`,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-restore-revision.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-restore-revision.jsonindex 09fac72f3553..ef2c33f01127 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-restore-revision.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-restore-revision.json@@ -1,6 +1,19 @@{"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {+ "expected_draft_updated_at": {+ "anyOf": [+ {+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "The draft_updated_at of the staged draft this overwrite was confirmed against. If a draft exists with a different stamp (it was staged or edited since the confirmation was shown), the restore returns 409 instead of overwriting it. Omit to overwrite unconditionally."+ },"id": {"description": "A UUID string identifying this hog flow.","type": "string"