: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): make the builder aware of edits from MCP/API (#64001)
Harley Alexanderc617e72bbb8e
diff --git a/frontend/package.json b/frontend/package.jsonindex 111cf9e62a83..a798e87ab3e2 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -106,6 +106,7 @@"@posthog/products-messaging": "workspace:*","@posthog/products-metrics": "workspace:*","@posthog/products-notebooks": "workspace:*",+ "@posthog/products-notifications": "workspace:*","@posthog/products-persons": "workspace:*","@posthog/products-platform-features": "workspace:*","@posthog/products-posthog-ai": "workspace:*",diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsxindex b795ecef0444..f0dfc0483446 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsx+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsx@@ -22,7 +22,13 @@ import { urls } from 'scenes/urls'import { connectToNotificationsSSE } from '~/layout/navigation-3000/sidepanel/panels/activity/notificationsSSE'import { ChangesResponse } from '~/layout/navigation-3000/sidepanel/panels/activity/sidePanelActivityLogic'-import { InAppNotification, InsightShortId, SidePanelTab, WebAnalyticsDigestMetadata } from '~/types'+import {+ InAppNotification,+ InsightShortId,+ ResourceEditedEvent,+ SidePanelTab,+ WebAnalyticsDigestMetadata,+} from '~/types'import {notificationsList,@@ -36,6 +42,7 @@ import {NotificationEventSourceTypeEnumApi,NotificationsListParams,} from 'products/notifications/frontend/generated/api.schemas'+import { RESOURCE_EDITED_EVENT_TYPE, resourceEditedLogic } from 'products/notifications/frontend/resourceEditedLogic'import { sidePanelContextLogic } from '../../sidePanelContextLogic'import { sidePanelStateLogic } from '../../sidePanelStateLogic'@@ -127,7 +134,14 @@ export const sidePanelNotificationsLogic = kea<sidePanelNotificationsLogicType>(organizationLogic,['currentOrganization'],],- actions: [sidePanelStateLogic, ['openSidePanel'], teamLogic, ['loadCurrentTeamSuccess']],+ actions: [+ sidePanelStateLogic,+ ['openSidePanel'],+ teamLogic,+ ['loadCurrentTeamSuccess'],+ resourceEditedLogic,+ ['resourceEdited'],+ ],})),actions({togglePolling: (pageIsVisible: boolean) => ({ pageIsVisible }),@@ -459,6 +473,13 @@ export const sidePanelNotificationsLogic = kea<sidePanelNotificationsLogicType>(token,abortController.signal,(notification) => {+ // Transient "edited elsewhere" events ride this stream but are+ // not inbox notifications — forward them to interested editors and+ // skip the unread-count / toast / list handling below.+ if (notification.notification_type === RESOURCE_EDITED_EVENT_TYPE) {+ actions.resourceEdited(notification as unknown as ResourceEditedEvent)+ return+ }if (!values.isInitialLoadComplete) {return}diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex af3fcdbd33a8..2a6a22d8a5ec 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -6575,7 +6575,12 @@ const api = {async createHogFlow(data: Partial<HogFlow>): Promise<HogFlow> {return await new ApiRequest().hogFlows().create({ data })},- async updateHogFlow(hogFlowId: HogFlow['id'], data: Partial<HogFlow>): Promise<HogFlow> {+ async updateHogFlow(+ 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 }+ ): Promise<HogFlow> {return await new ApiRequest().hogFlow(hogFlowId).update({ data })},async deleteHogFlow(hogFlowId: HogFlow['id']): Promise<void> {diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex fda7cfc65ac7..5eaba6262d14 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -478,6 +478,21 @@ export interface InAppNotification {created_at: string}+/**+ * Transient realtime event signalling that a resource was edited through some channel+ * (UI, MCP, or API). Rides the same notifications SSE transport as InAppNotification but is+ * never persisted or shown in the inbox — an open editor uses it to refresh instead of+ * clobbering edits made elsewhere. Discriminated by `notification_type === 'resource_edited'`.+ */+export interface ResourceEditedEvent {+ notification_type: 'resource_edited'+ team_id: number+ resource_type: string+ resource_id: string+ updated_at: string+ actor_user_id: number | null+}+export interface PluginAccess {view: booleaninstall: booleandiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 93e7159a151a..1887cfeb2592 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -705,6 +705,9 @@ importers:'@posthog/products-notebooks':specifier: workspace:*version: link:../products/notebooks+ '@posthog/products-notifications':+ specifier: workspace:*+ version: link:../products/notifications'@posthog/products-persons':specifier: workspace:*version: link:../products/persons@@ -3718,7 +3721,11 @@ importers:specifier: 18.3.1version: 18.3.1- products/notifications: {}+ products/notifications:+ dependencies:+ kea:+ specifier: 'catalog:'+ version: 4.0.0-pre.5([email protected])products/persons:dependencies:diff --git a/products/notifications/backend/facade/api.py b/products/notifications/backend/facade/api.pyindex 23ed44fe026a..1a57632ec799 100644--- a/products/notifications/backend/facade/api.py+++ b/products/notifications/backend/facade/api.py@@ -1,22 +1,25 @@from products.notifications.backend.facade.contracts import NotificationDatafrom products.notifications.backend.facade.enums import (+ RESOURCE_EDITED_EVENT_TYPE,NotificationResourceType,NotificationType,Priority,SourceType,TargetType,)-from products.notifications.backend.logic import create_notification, has_been_dispatched+from products.notifications.backend.logic import create_notification, has_been_dispatched, publish_resource_editedfrom products.notifications.backend.resolvers import RecipientsResolver__all__ = ["create_notification","has_been_dispatched",+ "publish_resource_edited","NotificationData","NotificationResourceType","NotificationType","Priority","RecipientsResolver",+ "RESOURCE_EDITED_EVENT_TYPE","SourceType","TargetType",]diff --git a/products/notifications/backend/facade/enums.py b/products/notifications/backend/facade/enums.pyindex 86de06e041f4..60ded344bb65 100644--- a/products/notifications/backend/facade/enums.py+++ b/products/notifications/backend/facade/enums.py@@ -25,6 +25,12 @@ class Priority(str, Enum):CRITICAL = "critical"+# Discriminator for transient "resource edited elsewhere" realtime events. These ride the+# notifications SSE transport but are NOT inbox notifications (no NotificationEvent row, no unread+# count) — see products.notifications.backend.logic.publish_resource_edited.+RESOURCE_EDITED_EVENT_TYPE = "resource_edited"++class TargetType(str, Enum):USER = "user"TEAM = "team"diff --git a/products/notifications/backend/logic.py b/products/notifications/backend/logic.pyindex 21a68020c21a..ac74170c75f6 100644--- a/products/notifications/backend/logic.py+++ b/products/notifications/backend/logic.py@@ -11,6 +11,7 @@ from products.notifications.backend.cache import invalidate_unread_count_for_usefrom products.notifications.backend.facade.contracts import NotificationDatafrom products.notifications.backend.facade.enums import (AC_RESOURCE_TYPES,+ RESOURCE_EDITED_EVENT_TYPE,NotificationOnlyResourceType,NotificationType,TargetType,@@ -88,6 +89,67 @@ def has_been_dispatched().exists()+def publish_resource_edited(+ *,+ team: Team,+ resource_type: str,+ resource_id: str,+ updated_at: str,+ actor_user_id: int | None = None,+ ac_resource_type: str | None = None,+) -> None:+ """Push a transient "this resource was edited elsewhere" event over the realtime stream, so an+ open editor (e.g. the workflow builder) can refresh instead of clobbering edits made via MCP/API.++ Unlike create_notification this persists NO NotificationEvent row: it is editor-state sync, not an+ inbox notification — it must not appear in the popover, must not bump the unread count, and there+ are no user mute preferences to honour. It rides the same Kafka → livestream → SSE transport; the+ Go handler passes unknown fields through and filters delivery by resolved_user_ids.++ `resource_type` is the value the frontend matches on (e.g. "HogFlow"); `ac_resource_type` is the+ access-control scope used to drop recipients without viewer access (e.g. "hog_flow").+ """+ organization_id = team.organization_id++ if not posthoganalytics.feature_enabled(+ "real-time-notifications",+ str(organization_id),+ groups={"organization": str(organization_id)},+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ ):+ return++ resolver = RecipientsResolver()+ recipient_user_ids = resolver.resolve(TargetType.TEAM, str(team.id), team.id)+ if ac_resource_type and ac_resource_type in AC_RESOURCE_TYPES:+ recipient_user_ids = resolver.filter_by_access_control(recipient_user_ids, ac_resource_type, team)++ if not recipient_user_ids:+ return++ payload = {+ "organization_id": str(organization_id),+ "team_id": team.id,+ "notification_type": RESOURCE_EDITED_EVENT_TYPE,+ "resource_type": resource_type,+ "resource_id": str(resource_id),+ "updated_at": updated_at,+ "actor_user_id": actor_user_id,+ "resolved_user_ids": recipient_user_ids,+ "priority": "normal",+ }++ def _on_commit() -> None:+ try:+ producer = get_producer(topic=KAFKA_NOTIFICATION_EVENTS)+ producer.produce(topic=KAFKA_NOTIFICATION_EVENTS, data=payload, key=str(organization_id))+ except Exception:+ logger.exception("notifications.resource_edited_publish_failed", resource_id=str(resource_id))++ transaction.on_commit(_on_commit)++def create_notification(data: NotificationData) -> NotificationEvent | None:team: Team | None = Noneif data.team_id is not None:diff --git a/products/notifications/backend/tests/test_logic.py b/products/notifications/backend/tests/test_logic.pyindex 4deedf87f3ce..1d23aa41b878 100644--- a/products/notifications/backend/tests/test_logic.py+++ b/products/notifications/backend/tests/test_logic.py@@ -18,7 +18,7 @@ from products.notifications.backend.facade.enums import (SourceType,TargetType,)-from products.notifications.backend.logic import create_notification+from products.notifications.backend.logic import create_notification, publish_resource_editedfrom products.notifications.backend.models import NotificationEventfrom products.notifications.backend.resolvers import RecipientsResolver@@ -334,3 +334,80 @@ class TestAccessControlFiltering(BaseTest):user_ids = [self.user.id, self.user2.id]result = self.resolver.filter_by_access_control(user_ids, "dashboard", self.team)assert result == [self.user.id]+++class TestPublishResourceEdited(BaseTest):+ def setUp(self):+ super().setUp()+ self.organization = Organization.objects.create(name="RE Org")+ self.team = Team.objects.create(organization=self.organization, name="RE Team")+ self.user = User.objects.create_and_join(self.organization, "[email protected]", "password")++ @patch("products.notifications.backend.logic.posthoganalytics.feature_enabled", return_value=True)+ @patch("products.notifications.backend.logic.get_producer")+ def test_publishes_transient_event_without_persisting(self, mock_get_producer, mock_ff):+ producer = mock_get_producer.return_value++ with self.captureOnCommitCallbacks(execute=True):+ publish_resource_edited(+ team=self.team,+ resource_type="HogFlow",+ resource_id="flow-123",+ updated_at="2026-06-16T00:00:00+00:00",+ actor_user_id=self.user.id,+ ac_resource_type="hog_flow",+ )++ producer.produce.assert_called_once()+ payload = producer.produce.call_args.kwargs["data"]+ assert payload["notification_type"] == "resource_edited"+ assert payload["resource_type"] == "HogFlow"+ assert payload["resource_id"] == "flow-123"+ assert payload["updated_at"] == "2026-06-16T00:00:00+00:00"+ assert self.user.id in payload["resolved_user_ids"]+ # Editor-state sync only — it must never become an inbox notification.+ assert NotificationEvent.objects.count() == 0++ @patch("products.notifications.backend.logic.posthoganalytics.feature_enabled", return_value=False)+ @patch("products.notifications.backend.logic.get_producer")+ def test_noops_when_flag_disabled(self, mock_get_producer, mock_ff):+ with self.captureOnCommitCallbacks(execute=True):+ publish_resource_edited(+ team=self.team,+ resource_type="HogFlow",+ resource_id="flow-123",+ updated_at="2026-06-16T00:00:00+00:00",+ )++ mock_get_producer.assert_not_called()++ @patch("products.notifications.backend.logic.posthoganalytics.feature_enabled", return_value=True)+ @patch("products.notifications.backend.logic.get_producer")+ @patch.object(RecipientsResolver, "resolve", return_value=[])+ def test_noops_when_no_recipients(self, mock_resolve, mock_get_producer, mock_ff):+ with self.captureOnCommitCallbacks(execute=True):+ publish_resource_edited(+ team=self.team,+ resource_type="HogFlow",+ resource_id="flow-123",+ updated_at="2026-06-16T00:00:00+00:00",+ )++ mock_get_producer.assert_not_called()++ @patch("products.notifications.backend.logic.posthoganalytics.feature_enabled", return_value=True)+ @patch("products.notifications.backend.logic.get_producer")+ @patch.object(RecipientsResolver, "filter_by_access_control")+ def test_skips_access_control_filtering_for_non_ac_resource(self, mock_ac_filter, mock_get_producer, mock_ff):+ # hog_flow is not an access-controlled resource type, so recipients are not AC-filtered.+ with self.captureOnCommitCallbacks(execute=True):+ publish_resource_edited(+ team=self.team,+ resource_type="HogFlow",+ resource_id="flow-123",+ updated_at="2026-06-16T00:00:00+00:00",+ ac_resource_type="hog_flow",+ )++ mock_ac_filter.assert_not_called()+ mock_get_producer.return_value.produce.assert_called_once()diff --git a/products/notifications/frontend/resourceEditedLogic.ts b/products/notifications/frontend/resourceEditedLogic.tsnew file mode 100644index 000000000000..d84d3f8a7e1d--- /dev/null+++ b/products/notifications/frontend/resourceEditedLogic.ts@@ -0,0 +1,23 @@+import { actions, kea, path } from 'kea'++import { ResourceEditedEvent } from '~/types'++import type { resourceEditedLogicType } from './resourceEditedLogicType'++/** Discriminator on `notification_type` for transient "edited elsewhere" events on the SSE stream. */+export const RESOURCE_EDITED_EVENT_TYPE = 'resource_edited'++/**+ * A tiny event bus that decouples the notifications SSE consumer from editors that care about+ * "this resource was edited elsewhere" events. The SSE consumer (sidePanelNotificationsLogic)+ * forwards matching events here; interested editors (e.g. workflowLogic) connect to the+ * `resourceEdited` action and decide what to do — silently refresh or warn before clobbering.+ *+ * Kept deliberately logic-free so neither side has to depend on the other's internals.+ */+export const resourceEditedLogic = kea<resourceEditedLogicType>([+ path(['products', 'notifications', 'frontend', 'resourceEditedLogic']),+ actions({+ resourceEdited: (event: ResourceEditedEvent) => ({ event }),+ }),+])diff --git a/products/notifications/package.json b/products/notifications/package.jsonindex 9aec9fc5759e..92c9ebb7b0f9 100644--- a/products/notifications/package.json+++ b/products/notifications/package.json@@ -2,5 +2,8 @@"name": "@posthog/products-notifications","scripts": {"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"+ },+ "dependencies": {+ "kea": "catalog:"}}diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex 93ad2425f4e2..87e2cb4d9c47 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -8,13 +8,14 @@ from django.core.exceptions import ValidationError as DjangoValidationErrorfrom django.db import transactionfrom django.db.models import QuerySetfrom django.utils import timezone+from django.utils.dateparse import parse_datetimeimport structlogimport posthoganalyticsfrom django_filters import BaseInFilter, CharFilter, FilterSetfrom django_filters.rest_framework import DjangoFilterBackendfrom drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field-from rest_framework import exceptions, serializers, viewsets+from rest_framework import exceptions, serializers, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.pagination import LimitOffsetPaginationfrom rest_framework.request import Request@@ -59,6 +60,7 @@ from products.feature_flags.backend.user_blast_radius import (get_user_blast_radius,get_user_blast_radius_persons,)+from products.notifications.backend.facade.api import publish_resource_editedfrom products.workflows.backend.api.graph_operations import apply_graph_operationsfrom products.workflows.backend.api.graph_validation import validate_graphfrom products.workflows.backend.api.hog_flow_batch_job import HogFlowBatchJobSerializer@@ -1139,6 +1141,14 @@ class HogFlowPagination(LimitOffsetPagination):max_limit = 500+class StaleWorkflowUpdateError(exceptions.APIException):+ status_code = status.HTTP_409_CONFLICT+ default_detail = (+ "This workflow was updated elsewhere since you loaded it. Reload to get the latest version before saving."+ )+ default_code = "stale_update"++@extend_schema(extensions={"x-product": "workflows"})class HogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMixin, viewsets.ModelViewSet):scope_object = "hog_flow"@@ -1230,6 +1240,19 @@ class HogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMixin, viedef _is_mcp_request(request: Request) -> bool:return request.headers.get("x-posthog-client") == "mcp"+ def _emit_resource_edited(self, instance: HogFlow) -> None:+ # 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.+ publish_resource_edited(+ team=self.team,+ resource_type="HogFlow",+ resource_id=str(instance.id),+ updated_at=instance.updated_at.isoformat(),+ actor_user_id=getattr(self.request.user, "id", None),+ ac_resource_type=self.scope_object,+ )+def perform_create(self, serializer):if self._is_mcp_request(self.request) and serializer.validated_data.get("status") == HogFlow.State.ACTIVE:raise exceptions.ValidationError(@@ -1239,6 +1262,7 @@ class HogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMixin, vieserializer.save()log_activity_from_viewset(self, serializer.instance, name=serializer.instance.name, detail_type="standard")+ self._emit_resource_edited(serializer.instance)try:# Count edges and actions@@ -1286,15 +1310,32 @@ class HogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMixin, vie# TODO(team-workflows): Atomically increment version, insert new object instead of default update behaviorinstance_id = serializer.instance.id- try:- # nosemgrep: semgrep.rules.idor-lookup-without-team (re-fetch of already-authorized instance for activity logging)- before_update = HogFlow.objects.get(pk=instance_id)- except HogFlow.DoesNotExist:- before_update = None+ # Optimistic concurrency: a client may send the `updated_at` it last loaded as `base_updated_at`.+ # If the stored row is strictly newer, another channel (a second UI tab, MCP, or the API) wrote in+ # between, so we reject with 409 rather than silently clobbering it. Strictly-newer (not equality)+ # avoids false positives from timestamp round-tripping — equal means the client is already current.+ # Callers that omit `base_updated_at` keep the previous last-writer-wins behavior.+ base_updated_at_raw = self.request.data.get("base_updated_at")+ base_updated_at = parse_datetime(base_updated_at_raw) if base_updated_at_raw else None+ # A timezone-less timestamp parses naive; comparing it to the tz-aware stored updated_at would+ # raise TypeError (500). Assume UTC so callers can send a bare ISO string.+ if base_updated_at is not None and timezone.is_naive(base_updated_at):+ base_updated_at = timezone.make_aware(base_updated_at)- serializer.save()+ with transaction.atomic():+ try:+ # nosemgrep: semgrep.rules.idor-lookup-without-team (re-fetch of already-authorized instance; locked for the staleness check + save)+ before_update = HogFlow.objects.select_for_update().get(pk=instance_id)+ except HogFlow.DoesNotExist:+ before_update = None++ if base_updated_at and before_update and before_update.updated_at > base_updated_at:+ raise StaleWorkflowUpdateError()++ serializer.save()log_activity_from_viewset(self, serializer.instance, name=serializer.instance.name, previous=before_update)+ self._emit_resource_edited(serializer.instance)# PostHog capture for hog_flow activated (draft -> active)if (@@ -1358,6 +1399,7 @@ class HogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMixin, vieserializer.save()log_activity_from_viewset(self, locked, name=locked.name, previous=before_update)+ self._emit_resource_edited(locked)return Response(self.get_serializer(locked).data)diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.pyindex e8610d44ea94..0abbdbe82c1c 100644--- a/products/workflows/backend/api/test/test_hog_flow.py+++ b/products/workflows/backend/api/test/test_hog_flow.py@@ -60,6 +60,91 @@ class TestHogFlowAPI(APIBaseTest):return hog_flow, action+ @patch("products.workflows.backend.api.hog_flow.publish_resource_edited")+ def test_emits_resource_edited_on_create_and_update(self, mock_emit):+ hog_flow, _ = self._create_hog_flow_with_action(+ {"template_id": "template-webhook", "inputs": {"url": {"value": "https://example.com"}}}+ )++ create_response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)+ assert create_response.status_code == 201, create_response.json()+ flow_id = create_response.json()["id"]++ assert mock_emit.call_count == 1+ create_kwargs = mock_emit.call_args.kwargs+ assert create_kwargs["resource_type"] == "HogFlow"+ assert create_kwargs["resource_id"] == str(flow_id)+ assert create_kwargs["updated_at"]++ mock_emit.reset_mock()+ update_response = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",+ {"name": "Renamed"},+ )+ assert update_response.status_code == 200, update_response.json()++ assert mock_emit.call_count == 1+ assert mock_emit.call_args.kwargs["resource_id"] == str(flow_id)++ def _create_simple_flow(self) -> str:+ hog_flow, _ = self._create_hog_flow_with_action(+ {"template_id": "template-webhook", "inputs": {"url": {"value": "https://example.com"}}}+ )+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)+ assert response.status_code == 201, response.json()+ return response.json()["id"]++ def test_stale_update_is_rejected_with_409(self):+ flow_id = self._create_simple_flow()+ flow = HogFlow.objects.get(pk=flow_id)+ current = flow.updated_at.isoformat()+ stale = (flow.updated_at - timedelta(seconds=1)).isoformat()++ # A client that based its edit on an older copy is rejected rather than clobbering the newer one.+ stale_response = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",+ {"name": "Stale edit", "base_updated_at": stale},+ )+ assert stale_response.status_code == 409, stale_response.json()+ assert HogFlow.objects.get(pk=flow_id).name != "Stale edit"++ # A client whose base matches the current server copy proceeds.+ fresh_response = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",+ {"name": "Fresh edit", "base_updated_at": current},+ )+ assert fresh_response.status_code == 200, fresh_response.json()+ assert HogFlow.objects.get(pk=flow_id).name == "Fresh edit"++ def test_update_without_base_updated_at_is_not_gated(self):+ # Backwards compatible: callers that don't opt in to the base timestamp keep last-writer-wins.+ flow_id = self._create_simple_flow()+ flow = HogFlow.objects.get(pk=flow_id)+ stale = (flow.updated_at - timedelta(seconds=10)).isoformat()+ assert stale # we hold a stale view but send no base++ response = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",+ {"name": "Ungated edit"},+ )+ assert response.status_code == 200, response.json()+ assert HogFlow.objects.get(pk=flow_id).name == "Ungated edit"++ def test_timezone_naive_base_updated_at_is_handled(self):+ # A base_updated_at with no timezone designator parses naive; it must be coerced to aware+ # (assumed UTC) rather than raising TypeError when compared to the tz-aware stored updated_at.+ flow_id = self._create_simple_flow()+ flow = HogFlow.objects.get(pk=flow_id)+ naive = flow.updated_at.replace(tzinfo=None).isoformat()+ assert "+" not in naive and not naive.endswith("Z")++ response = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",+ {"name": "Naive base edit", "base_updated_at": naive},+ )+ assert response.status_code == 200, response.json()+ assert HogFlow.objects.get(pk=flow_id).name == "Naive base edit"+def test_hog_flow_function_trigger_check(self):hog_flow = {"name": "Test Flow",@@ -1169,6 +1254,23 @@ class TestHogFlowAPI(APIBaseTest):assert actions["trigger_node"]["type"] == "trigger"assert "exit_1" in actions+ @patch("products.workflows.backend.api.hog_flow.publish_resource_edited")+ def test_graph_update_emits_resource_edited(self, mock_emit):+ # The surgical /graph path is the primary MCP edit route, so it must emit the same+ # "edited elsewhere" signal as the full update path — otherwise an open builder never+ # learns about MCP graph edits and the cross-channel awareness has a hole.+ flow_id = self._create_draft_flow_with_graph()+ mock_emit.reset_mock()++ response = self._patch_graph(flow_id, [{"op": "update_action", "id": "action_1", "patch": {"name": "renamed"}}])+ assert response.status_code == 200, response.json()++ assert mock_emit.call_count == 1+ kwargs = mock_emit.call_args.kwargs+ assert kwargs["resource_type"] == "HogFlow"+ assert kwargs["resource_id"] == str(flow_id)+ assert kwargs["updated_at"]+def test_graph_response_echoes_full_graph(self):flow_id = self._create_draft_flow_with_graph()response = self._patch_graph(flow_id, [{"op": "update_action", "id": "action_1", "patch": {"name": "renamed"}}])diff --git a/products/workflows/frontend/Workflows/Workflow.tsx b/products/workflows/frontend/Workflows/Workflow.tsxindex bb49d2d00a7a..fcc191553c3e 100644--- a/products/workflows/frontend/Workflows/Workflow.tsx+++ b/products/workflows/frontend/Workflows/Workflow.tsx@@ -1,15 +1,39 @@-import { useValues } from 'kea'+import { useActions, useValues } from 'kea'-import { SpinnerOverlay } from '@posthog/lemon-ui'+import { LemonBanner, LemonButton, SpinnerOverlay } from '@posthog/lemon-ui'import { HogFlowEditor } from './hogflows/HogFlowEditor'import { WorkflowLogicProps, workflowLogic } from './workflowLogic'export function Workflow(props: WorkflowLogicProps): JSX.Element {- const { originalWorkflow, workflowLoading } = useValues(workflowLogic(props))+ const { originalWorkflow, workflowLoading, externallyEdited, isSyncingExternalEdit } = useValues(+ workflowLogic(props)+ )+ const { loadWorkflow, keepMyWorkflowVersion } = useActions(workflowLogic(props))return (<div className="flex flex-col grow relative border rounded-md">+ {/* Brief working/disabled overlay while we reconcile to an edit made elsewhere (clean state). */}+ {isSyncingExternalEdit && <SpinnerOverlay />}+ {externallyEdited && (+ <LemonBanner type="warning" className="m-2">+ <div className="flex items-center justify-between gap-2">+ <span>+ This workflow was updated elsewhere (for example via the API or an AI assistant) while you+ have unsaved changes. Reload to get the latest version, or keep editing — saving will+ overwrite the other changes.+ </span>+ <div className="flex items-center gap-2 shrink-0">+ <LemonButton type="secondary" size="small" onClick={() => keepMyWorkflowVersion()}>+ Keep mine+ </LemonButton>+ <LemonButton type="primary" size="small" onClick={() => loadWorkflow()}>+ Reload+ </LemonButton>+ </div>+ </div>+ </LemonBanner>+ )}{!originalWorkflow && workflowLoading ? <SpinnerOverlay /> : <HogFlowEditor />}</div>)diff --git a/products/workflows/frontend/Workflows/workflowLogic.externalEdits.test.ts b/products/workflows/frontend/Workflows/workflowLogic.externalEdits.test.tsnew file mode 100644index 000000000000..205723defdfa--- /dev/null+++ b/products/workflows/frontend/Workflows/workflowLogic.externalEdits.test.ts@@ -0,0 +1,185 @@+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'+import { ResourceEditedEvent } from '~/types'++import { resourceEditedLogic } from 'products/notifications/frontend/resourceEditedLogic'++import { HogFlow } from './hogflows/types'+import { workflowLogic } from './workflowLogic'++const WORKFLOW_ID = 'wf-external-1'+const LOADED_AT = '2026-05-01T00:00:00.000Z'+const NEWER = '2026-06-01T00:00:00.000Z'+const OLDER = '2026-04-01T00:00:00.000Z'++const makeWorkflow = (overrides: Partial<HogFlow> = {}): HogFlow => ({+ id: WORKFLOW_ID,+ name: 'External edits test',+ actions: [+ {+ id: 'trigger_node',+ type: 'trigger',+ name: 'Trigger',+ description: '',+ created_at: 0,+ updated_at: 0,+ config: { type: 'event', filters: {} },+ },+ {+ id: 'exit_node',+ type: 'exit',+ name: 'Exit',+ description: '',+ created_at: 0,+ updated_at: 0,+ config: { reason: 'Default exit' },+ },+ ],+ edges: [{ from: 'trigger_node', to: 'exit_node', type: 'continue' }],+ conversion: { window_minutes: null, filters: [] },+ exit_condition: 'exit_only_at_end',+ version: 1,+ status: 'draft',+ team_id: 1,+ trigger: { type: 'event', filters: {} } as HogFlow['trigger'],+ created_at: '2026-05-01T00:00:00.000Z',+ updated_at: LOADED_AT,+ ...overrides,+})++const makeEvent = (overrides: Partial<ResourceEditedEvent> = {}): ResourceEditedEvent => ({+ notification_type: 'resource_edited',+ team_id: 1,+ resource_type: 'HogFlow',+ resource_id: WORKFLOW_ID,+ updated_at: NEWER,+ actor_user_id: 99,+ ...overrides,+})++describe('workflowLogic external edits', () => {+ let logic: ReturnType<typeof workflowLogic.build>+ let getCalls: number++ beforeEach(async () => {+ getCalls = 0+ useMocks({+ get: {+ '/api/environments/:team_id/hog_flows/:id/': () => {+ getCalls += 1+ return [200, makeWorkflow()]+ },+ '/api/projects/:team_id/hog_function_templates/': { results: [], count: 0 },+ },+ })+ initKeaTests()+ resourceEditedLogic.mount()+ logic = workflowLogic({ id: WORKFLOW_ID })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadWorkflowSuccess'])+ // The initial load counts as one GET; assertions below track edits beyond it.+ expect(getCalls).toBe(1)+ })++ it('silently reconciles (sync + reload) when the local state is clean', async () => {+ await expectLogic(logic, () => {+ resourceEditedLogic.actions.resourceEdited(makeEvent({ updated_at: NEWER }))+ }).toDispatchActions(['setSyncingExternalEdit', 'loadWorkflow', 'loadWorkflowSuccess'])++ // Reloaded from the server, no banner, and the syncing overlay clears on success.+ expect(getCalls).toBe(2)+ expect(logic.values.externallyEdited).toBe(false)+ expect(logic.values.isSyncingExternalEdit).toBe(false)+ })++ it('warns instead of clobbering when there are unsaved local edits', async () => {+ logic.actions.setAutoSaveEnabled(false)+ logic.actions.setWorkflowValue('name', 'My local edit')+ expect(logic.values.hasUnsavedChanges).toBe(true)++ await expectLogic(logic, () => {+ resourceEditedLogic.actions.resourceEdited(makeEvent({ updated_at: NEWER }))+ }).toDispatchActions(['setExternallyEdited'])++ // Banner shown, no destructive reload, no syncing overlay.+ expect(logic.values.externallyEdited).toBe(true)+ expect(logic.values.isSyncingExternalEdit).toBe(false)+ expect(getCalls).toBe(1)+ })++ it.each([+ ['equal updated_at (our own save echo)', { updated_at: LOADED_AT }],+ ['older updated_at', { updated_at: OLDER }],+ ['a different workflow', { resource_id: 'some-other-workflow' }],+ ['a different resource type', { resource_type: 'EmailTemplate' }],+ ])('ignores %s', async (_label, overrides) => {+ resourceEditedLogic.actions.resourceEdited(makeEvent(overrides as Partial<ResourceEditedEvent>))+ // Give any (unexpected) async reaction a chance to run.+ await new Promise((resolve) => setTimeout(resolve, 0))++ expect(getCalls).toBe(1)+ expect(logic.values.externallyEdited).toBe(false)+ expect(logic.values.isSyncingExternalEdit).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')+ resourceEditedLogic.actions.resourceEdited(makeEvent({ updated_at: NEWER }))+ await expectLogic(logic).toDispatchActions(['setExternallyEdited'])+ expect(logic.values.externallyEdited).toBe(true)++ await expectLogic(logic, () => {+ logic.actions.loadWorkflow()+ }).toDispatchActions(['loadWorkflowSuccess'])++ expect(logic.values.externallyEdited).toBe(false)+ })++ it('adopts the latest server baseline (and keeps edits) when the user chooses Keep mine', async () => {+ logic.actions.setAutoSaveEnabled(false)+ logic.actions.setWorkflowValue('name', 'My local edit')+ resourceEditedLogic.actions.resourceEdited(makeEvent({ updated_at: NEWER }))+ await expectLogic(logic).toDispatchActions(['setExternallyEdited'])+ expect(logic.values.externallyEdited).toBe(true)++ // The server copy has advanced; Keep mine adopts that timestamp so the user's next save wins.+ useMocks({+ get: {+ '/api/environments/:team_id/hog_flows/:id/': () => [200, makeWorkflow({ updated_at: NEWER })],+ '/api/projects/:team_id/hog_function_templates/': { results: [], count: 0 },+ },+ })++ await expectLogic(logic, () => {+ logic.actions.keepMyWorkflowVersion()+ }).toDispatchActions(['setSaveBaseUpdatedAt', 'setExternallyEdited'])++ expect(logic.values.externallyEdited).toBe(false)+ expect(logic.values.saveBaseUpdatedAt).toBe(NEWER)+ // The local edit is preserved — the canvas was not reloaded.+ expect(logic.values.workflow.name).toBe('My local edit')+ })++ it('shows the banner when a save is rejected as stale (409 backstop)', async () => {+ useMocks({+ get: {+ '/api/environments/:team_id/hog_flows/:id/': () => [200, makeWorkflow()],+ '/api/projects/:team_id/hog_function_templates/': { results: [], count: 0 },+ },+ patch: {+ '/api/environments/:team_id/hog_flows/:id/': () => [409, { detail: 'stale_update' }],+ },+ })+ logic.actions.setAutoSaveEnabled(false)+ logic.actions.setWorkflowValue('name', 'Conflicting edit')++ await expectLogic(logic, () => {+ logic.actions.saveWorkflow(logic.values.workflow)+ }).toDispatchActions(['saveWorkflowFailure'])++ expect(logic.values.externallyEdited).toBe(true)+ })+})diff --git a/products/workflows/frontend/Workflows/workflowLogic.ts b/products/workflows/frontend/Workflows/workflowLogic.tsindex bd6e6fe51f7e..f7af4e13e7ea 100644--- a/products/workflows/frontend/Workflows/workflowLogic.ts+++ b/products/workflows/frontend/Workflows/workflowLogic.ts@@ -6,7 +6,7 @@ import posthog from 'posthog-js'import { LemonDialog } from '@posthog/lemon-ui'-import api from 'lib/api'+import api, { ApiError } from 'lib/api'import { CyclotronJobInputsValidation } from 'lib/components/CyclotronJob/CyclotronJobInputsValidation'import { tryShowMCPHint } from 'lib/components/MCPHint/mcpHintLogic'import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'@@ -22,6 +22,8 @@ import { userLogic } from 'scenes/userLogic'import { HogFunctionTemplateType } from '~/types'+import { resourceEditedLogic } from 'products/notifications/frontend/resourceEditedLogic'+import { getRegisteredTriggerTypes } from './hogflows/registry/triggers/triggerTypeRegistry'import {DEFAULT_STATE,@@ -145,7 +147,7 @@ export const workflowLogic = kea<workflowLogicType>([),connect(() => ({values: [userLogic, ['user'], projectLogic, ['currentProjectId']],- actions: [workflowsLogic, ['archiveWorkflow']],+ actions: [workflowsLogic, ['archiveWorkflow'], resourceEditedLogic, ['resourceEdited']],})),actions({partialSetWorkflowActionConfig: (actionId: string, config: Partial<HogFlowAction['config']>) => ({@@ -183,8 +185,12 @@ export const workflowLogic = kea<workflowLogicType>([markAutoSave: (isAutoSave: boolean) => ({ isAutoSave }),setAutoSaveEnabled: (enabled: boolean) => ({ enabled }),clearAutoSavePending: true,+ setExternallyEdited: (externallyEdited: boolean) => ({ externallyEdited }),+ setSyncingExternalEdit: (syncing: boolean) => ({ syncing }),+ setSaveBaseUpdatedAt: (updatedAt: string | null) => ({ updatedAt }),+ keepMyWorkflowVersion: true,}),- loaders(({ props, values }) => ({+ loaders(({ props, values, actions }) => ({originalWorkflow: [null as HogFlow | null,{@@ -235,7 +241,22 @@ export const workflowLogic = kea<workflowLogicType>([return result}- return api.hogFlows.updateHogFlow(props.id, updates)+ try {+ return await api.hogFlows.updateHogFlow(props.id, {+ ...updates,+ // 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,+ })+ } catch (error) {+ if (error instanceof ApiError && error.status === 409) {+ // A newer version exists (SSE event likely missed) — surface the reconcile banner,+ // which carries the actionable Reload / Keep mine choice. No toast: it would just+ // duplicate the banner (the global kea handler already skips 409).+ actions.setExternallyEdited(true)+ }+ throw error+ }},},],@@ -371,6 +392,38 @@ export const workflowLogic = kea<workflowLogicType>([setAutoSaveEnabled: (_, { enabled }) => enabled,},],+ // Set when another channel (another UI tab, MCP, or the API) saved this workflow while we had+ // unsaved local edits. Surfaces a non-destructive "reload / keep mine" banner. Cleared whenever+ // we reload or save, since both reconcile us with the server copy.+ externallyEdited: [+ false as boolean,+ {+ setExternallyEdited: (_, { externallyEdited }) => externallyEdited,+ loadWorkflowSuccess: () => false,+ saveWorkflowSuccess: () => false,+ },+ ],+ // True while we silently reconcile to an external edit (clean local state). Drives a brief+ // overlay so the canvas is disabled and visibly "working" during the reload, like auto-save.+ isSyncingExternalEdit: [+ false as boolean,+ {+ setSyncingExternalEdit: (_, { syncing }) => syncing,+ loadWorkflowSuccess: () => false,+ loadWorkflowFailure: () => false,+ },+ ],+ // Overrides the base timestamp sent with the next save. Set when the user chooses "Keep mine" on+ // the conflict banner — we adopt the latest server updated_at so their save deliberately wins+ // instead of dead-ending on a 409. Reset once any load or save reconciles us with the server.+ saveBaseUpdatedAt: [+ null as string | null,+ {+ setSaveBaseUpdatedAt: (_, { updatedAt }) => updatedAt,+ loadWorkflowSuccess: () => null,+ saveWorkflowSuccess: () => null,+ },+ ],}),selectors({logicProps: [() => [(_, props: WorkflowLogicProps) => props], (props): WorkflowLogicProps => props],@@ -638,6 +691,43 @@ export const workflowLogic = kea<workflowLogicType>([// the setScheduleTimezone listener's wall-clock reinterpretation.actions.setSchedules(values.schedules)},+ resourceEdited: ({ event }) => {+ // Another channel (a second UI tab, MCP, or the API) saved this workflow. React only to+ // events for the workflow we currently have open.+ if (event.resource_type !== 'HogFlow' || event.resource_id !== props.id) {+ return+ }+ const loadedUpdatedAt = values.originalWorkflow?.updated_at+ // Strictly-newer comparison rather than equality: equal means the event is the echo of our+ // own save (originalWorkflow already carries that updated_at), so we ignore it. Only a server+ // copy that is genuinely ahead of what we loaded is a real external edit.+ if (!loadedUpdatedAt || !dayjs(event.updated_at).isAfter(dayjs(loadedUpdatedAt))) {+ return+ }+ if (values.hasUnsavedChanges) {+ // Don't clobber the user's in-progress edits — let them choose (banner).+ actions.setExternallyEdited(true)+ } else {+ // Clean slate: catch up to the external edit. Flag the sync first so the editor shows a+ // brief working/disabled overlay and re-enables once the fresh copy loads (like auto-save).+ actions.setSyncingExternalEdit(true)+ actions.loadWorkflow()+ }+ },+ 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+ // check and deliberately overwrites the other channel's version, instead of looping on 409.+ if (props.id && props.id !== 'new') {+ try {+ const latest = await api.hogFlows.getHogFlow(props.id)+ actions.setSaveBaseUpdatedAt(latest.updated_at)+ } catch {+ // If we can't fetch the latest timestamp, just dismiss; the 409 backstop still protects them.+ }+ }+ actions.setExternallyEdited(false)+ },saveWorkflowPartial: async ({ workflow }) => {const merged = { ...values.workflow, ...workflow }if (merged.status === 'active' && values.workflowHasActionErrors) {diff --git a/tach.toml b/tach.tomlindex 9efca5bb97a5..cc8dba7e4a78 100644--- a/tach.toml+++ b/tach.toml@@ -703,6 +703,7 @@ depends_on = ["products.actions","products.cdp","products.feature_flags",+ "products.notifications",]layer = "modules"