: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(customer-analytics): add customer event stream to customer analytics (#68659)
Sean Malliaea7681fee6df
diff --git a/.gitignore b/.gitignoreindex 3f28e3f2684e..233dbe220e88 100644--- a/.gitignore+++ b/.gitignore@@ -223,3 +223,6 @@ posthog/hogql/scripts/.local/# RocksDB state store created at runtime by cohort-stream-processorrust/cohort-store/rust/cohort-stream-processor/cohort-store/++# Local TLS certs (e.g. mkcert) — never commit private keys+*.pemdiff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex 353d128cf5de..77a87128dd31 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -130,6 +130,8 @@ rules:|EnterpriseEventDefinition|EnterprisePropertyDefinition|EventFilterConfig+ |EventStream+ |EventStreamMember|ErrorTrackingAssignmentRule|ErrorTrackingBypassRule|ErrorTrackingGroupingRule@@ -448,6 +450,8 @@ rules:|EnterpriseEventDefinition|EnterprisePropertyDefinition|EventFilterConfig+ |EventStream+ |EventStreamMember|ErrorTrackingAssignmentRule|ErrorTrackingBypassRule|ErrorTrackingGroupingRulediff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 7d86557d988e..62cbd0bde0d1 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6283,9 +6283,9 @@ snapshots:scenes-app-insights-error-empty-states--funnel-single-step--light:hash: v1.k794b7964.49098739cf73ac9854bc1d46cfd56405adcd40293f444d5ff8de1262b8bb1d1e.-7-iNk2KTD2g20fzTZf9fQyHGs647o8oWLMiUQ5XQ4Mscenes-app-insights-error-empty-states--long-loading--dark:- hash: v1.k794b7964.a4ef06f43150c35c271495c091ba62f54a37e5c5b36907254181945c123a9b2f.t7UYQk8Vhutgw1BLk6eTVGvlF79bBNM-Nq5JONt6QDA+ hash: v1.k794b7964.a6429bcd1656dc70e30624f2e2f222d77d001a2a0e6fd49e0715598251e08e5e.GjorOUsq0kK5NJezAdyIBqFjJBIveAR3brvuMItSSYcscenes-app-insights-error-empty-states--long-loading--light:- hash: v1.k794b7964.b7f6e68a896b184b5f4e3125da63f376e6660e237473454e64188495ed99a6f9.lcJSyjsLeSXf8NSS1_r8iVLlvr0WWivdQPyJAvAjtxU+ hash: v1.k794b7964.e3f760b8e3b6d5138169be92e3a8026a00e7ec2ee9e252e54b67218df282b804.z796JAdbdGr_wQgg7t4XD97z7nQoKC3qrjEVudqDDeUscenes-app-insights-error-empty-states--memory-limit-exceeded--dark:hash: v1.k794b7964.ef18ee16bcec4b43d74979a5131a3f325f8e0542b6b4cba050746f6b02699ab9.kOLq5BxzD8AlGlxKgleq3uJTw_ddM6GTSmML4MNaZ5oscenes-app-insights-error-empty-states--memory-limit-exceeded--light:diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex b011a5f2e144..9aee7a2972c9 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -958,7 +958,8 @@ export const productUrls = {customerAnalyticsNotes: (): string => '/customer_analytics/notes',customerAnalyticsAnnouncements: (): string => '/customer_analytics/announcements',customerAnalyticsJourneys: (): string => '/customer_analytics/journeys',- customerAnalyticsConfiguration: (): string => '/customer_analytics/configuration',+ customerAnalyticsConfiguration: (tab?: string): string =>+ `/customer_analytics/configuration${tab ? `?tab=${tab}` : ''}`,customerJourneyBuilder: (): string => '/customer_analytics/journeys/new',customerJourneyTemplates: (): string => '/customer_analytics/journeys/templates',customerJourneyEdit: (id: string): string => `/customer_analytics/journeys/${id}/edit`,diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsxindex 5c6ed8f4a63d..86b4e656fe2e 100644--- a/frontend/src/scenes/settings/SettingsMap.tsx+++ b/frontend/src/scenes/settings/SettingsMap.tsx@@ -46,6 +46,7 @@ import { AISection } from 'products/conversations/frontend/scenes/settings/AISecimport { GeneralSection } from 'products/conversations/frontend/scenes/settings/GeneralSection'import { NotificationsSection } from 'products/conversations/frontend/scenes/settings/NotificationsSection'import { ZendeskImportSection } from 'products/conversations/frontend/scenes/settings/ZendeskImportSection'+import { CustomerAnalyticsEventStream } from 'products/customer_analytics/frontend/components/EventStream/CustomerAnalyticsEventStream'import { CustomerAnalyticsAccountConfig } from 'products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomerAnalyticsAccountConfig'import {WarehouseGroupPropertiesSetting,@@ -443,6 +444,15 @@ export const SETTINGS_MAP: SettingSection[] = [flag: ['CUSTOMER_ANALYTICS', 'CUSTOMER_ANALYTICS_CSP'],keywords: ['accounts', 'group', 'b2b'],},+ {+ id: 'customer-analytics-event-stream',+ title: 'Event stream',+ description:+ "Stream selected customers' events to a Slack channel of your choice in real time. Each team member configures their own stream: pick your events and channel here, then add customers from their account profiles.",+ component: <CustomerAnalyticsEventStream />,+ flag: ['CUSTOMER_ANALYTICS', 'CUSTOMER_ANALYTICS_CSP'],+ keywords: ['event', 'stream', 'live', 'slack', 'accounts'],+ },{id: 'customer-analytics-person-properties',title: 'Person properties',diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.tsindex 39ca51a489c7..963836a7a499 100644--- a/frontend/src/scenes/settings/types.ts+++ b/frontend/src/scenes/settings/types.ts@@ -120,6 +120,7 @@ export type SettingId =| 'csp-reporting'| 'customer-analytics-accounts'| 'customer-analytics-dashboard-events'+ | 'customer-analytics-event-stream'| 'customer-analytics-group-properties'| 'customer-analytics-person-properties'| 'customer-analytics-usage-metrics'diff --git a/posthog/models/organization.py b/posthog/models/organization.pyindex 946dff4da3c9..fb051da79bc4 100644--- a/posthog/models/organization.py+++ b/posthog/models/organization.py@@ -755,6 +755,21 @@ def clean_up_alert_subscriptions_on_membership_removal(sender, instance: Organiz)+@receiver(models.signals.post_delete, sender=OrganizationMembership)+def clean_up_event_streams_on_membership_removal(sender, instance: OrganizationMembership, **kwargs):+ from products.customer_analytics.backend.facade.api import delete_event_streams_for_user++ deleted_count = delete_event_streams_for_user(user_id=instance.user_id, organization_id=instance.organization_id)++ if deleted_count > 0:+ logger.info(+ "Removed customer analytics event streams for user removed from organization",+ user_id=instance.user_id,+ organization_id=str(instance.organization_id),+ deleted_count=deleted_count,+ )++@receiver(models.signals.post_delete, sender=OrganizationMembership)def sync_billing_on_membership_removal(sender, instance: OrganizationMembership, **kwargs):from posthog.tasks.sync_billing import sync_members_to_billingdiff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txtindex e6bc5a89af69..f7af1a1a6406 100644--- a/posthog/test/setup_receivers_baseline.txt+++ b/posthog/test/setup_receivers_baseline.txt@@ -50,6 +50,7 @@ post_delete:posthog.models.global_rate_limit_threshold_config.update_redis_threspost_delete:posthog.models.integration.cleanup_ses_identity_on_integration_deletepost_delete:posthog.models.oauth._block_cimd_url_on_application_deletepost_delete:posthog.models.organization.clean_up_alert_subscriptions_on_membership_removal+post_delete:posthog.models.organization.clean_up_event_streams_on_membership_removalpost_delete:posthog.models.organization.pause_loops_on_membership_removalpost_delete:posthog.models.organization.sync_billing_on_membership_removalpost_delete:posthog.models.product_intent.product_intent._invalidate_product_intents_on_deletediff --git a/products/customer_analytics/backend/COMPROMISES.md b/products/customer_analytics/backend/COMPROMISES.mdindex dd21416d986d..5f0208405051 100644--- a/products/customer_analytics/backend/COMPROMISES.md+++ b/products/customer_analytics/backend/COMPROMISES.md@@ -78,6 +78,19 @@ Cutover checklist — when done, the sync and this section are deleted:in the payload and can be mapped by hand. Follow `next` pages in`getOutputMappingSuggestions` (workflows frontend registry) if teams that large show up.+## Event stream++- **Cascade deletions don't archive the Slack destination.** The managed HogFunction is archived+ in `delete_event_stream` (the facade, the only deliberate deletion path) and in+ `delete_event_streams_for_user` (called from core's `OrganizationMembership` post_delete, so a+ member leaving or being removed from the org stops their stream delivering) rather than a+ `pre_delete` signal on the stream itself, so plain ORM cascades still bypass it. Team deletion+ is harmless — the HogFunction is team-scoped and dies in the same cascade. Hard-deleting an+ owner (`created_by` CASCADE) usually archives via the membership post_delete firing in the same+ collector run, but the ordering isn't guaranteed. Accepted because user hard-deletion is rare+ (members are deactivated or removed from the org, not deleted); if it bites, archive the+ destinations explicitly in the user-deletion flow rather than reintroducing a signal.+## Tech debt- **Account property writes have no single choke point.** `Account._properties` is mutated from fourdiff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 8613050f04b7..f8c3ade7e209 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -31,7 +31,7 @@ from celery import current_appfrom pydantic import ValidationError as PydanticValidationErrorfrom posthog.exceptions_capture import capture_exception-from posthog.models import OrganizationMembership, Tag+from posthog.models import Integration, OrganizationMembership, Tagfrom posthog.models.activity_logging.activity_log import AuditableScope, Detail, changes_between, log_activityfrom posthog.models.tag import tagifyfrom posthog.models.tagged_item import TaggedItem@@ -54,6 +54,12 @@ from products.customer_analytics.backend.logic.custom_property_definitions imporcoerce_is_big_number,normalize_options,)+from products.customer_analytics.backend.logic.event_stream_destination import (+ archive_event_stream_destination,+ send_test_slack_message as send_test_slack_message,+ sync_event_stream_destination,+ sync_event_stream_destination_by_id as sync_event_stream_destination_by_id,+)from products.customer_analytics.backend.logic.person_property_projection import (person_properties_flag_enabled as person_properties_flag_enabled,)@@ -71,6 +77,8 @@ from products.customer_analytics.backend.models import (CustomPropertySource,CustomPropertySyncRun,DisplayType,+ EventStream,+ EventStreamMember,SyncStatus,TargetType,)@@ -2042,6 +2050,11 @@ def update_account_for_view(_set_tags(input.tags, account, actor=user)if input.properties_provided:_relationships_logic.sync_from_account_properties(account, created_by=user)+ if input.external_id_provided and account.external_id != previous.external_id:+ # The external_id is the account's group key — every stream filtering on+ # the old key must be rebuilt or it keeps streaming the stale key's events.+ for stream in _event_streams_containing_account(account):+ sync_event_stream_destination(stream, team=account.team, user=user)except PydanticValidationError as exc:raise AccountPropertiesValidationError(_format_pydantic_errors(exc))except IntegrityError:@@ -2082,7 +2095,15 @@ def delete_account_for_view(user=user,was_impersonated=was_impersonated,)- account.delete()+ with transaction.atomic():+ # Streams referencing this account must be captured before the delete cascades+ # their membership rows away, then resynced so the account's group key doesn't+ # linger in a Slack destination filter.+ streams = _event_streams_containing_account(account)+ team = account.team+ account.delete()+ for stream in streams:+ sync_event_stream_destination(stream, team=team, user=user)def _get_account_for_detail(team_id: int, account_id: str) -> Account:@@ -2551,6 +2572,168 @@ def end_account_relationship(return _to_account_relationship(relationship)+# --- EventStream ---+++class EventStreamValidationError(Exception):+ """Raised when an event-stream write references a Slack integration that isn't the+ team's (→ 400)."""+++class EventStreamConflictError(Exception):+ """Raised when a user creates a second event stream in a team (→ 409)."""+++def _own_streams(team_id: int, user: "User"):+ """Streams are per-user: every read and write is scoped to the caller's own stream."""+ return EventStream.objects.for_team(team_id).filter(created_by=user)+++def _to_event_stream_view(stream: EventStream) -> contracts.EventStreamView:+ account_ids = list(stream.members.order_by("created_at").values_list("account_id", flat=True))+ return contracts.EventStreamView(+ id=stream.id,+ enabled=stream.enabled,+ event_names=list(stream.event_names or []),+ slack_integration=stream.slack_integration_id,+ slack_channel_id=stream.slack_channel_id,+ slack_channel_name=stream.slack_channel_name,+ account_ids=account_ids,+ created_at=stream.created_at,+ created_by=stream.created_by_id,+ updated_at=stream.updated_at,+ )+++def _validate_slack_integration(team_id: int, integration_id: int | None) -> None:+ if integration_id is None:+ return+ if not Integration.objects.filter(team_id=team_id, id=integration_id, kind="slack").exists():+ raise EventStreamValidationError("Slack integration not found for this team.")+++def _normalize_event_names(event_names: Iterable[str]) -> list[str]:+ """Deduplicated, order-preserving event names with blanks dropped."""+ return [name for name in dict.fromkeys(event_names) if name and name.strip()]+++def list_event_streams(team_id: int, *, user: "User") -> list[contracts.EventStreamView]:+ """The caller's event streams — at most one exists per user (unique per team+owner)."""+ return [_to_event_stream_view(s) for s in _own_streams(team_id, user).order_by("created_at")]+++def create_event_stream(+ *,+ team_id: int,+ enabled: bool,+ event_names: list[str],+ slack_integration_id: int | None,+ slack_channel_id: str,+ slack_channel_name: str,+ user: "User",+) -> contracts.EventStreamView:+ """Create the caller's event stream. Raises :class:`EventStreamConflictError` when they+ already have one and :class:`EventStreamValidationError` for a foreign Slack integration."""+ _validate_slack_integration(team_id, slack_integration_id)+ try:+ stream = EventStream.objects.for_team(team_id).create(+ team_id=team_id,+ created_by=user,+ enabled=enabled,+ event_names=_normalize_event_names(event_names),+ slack_integration_id=slack_integration_id,+ slack_channel_id=slack_channel_id,+ slack_channel_name=slack_channel_name,+ )+ except IntegrityError as exc:+ if "unique" not in str(exc).lower() and "duplicate" not in str(exc).lower():+ raise+ raise EventStreamConflictError("You already have an event stream in this project.")+ return _to_event_stream_view(stream)+++def update_event_stream(+ *, team_id: int, stream_id: str | UUID, fields: dict[str, Any], user: "User"+) -> contracts.EventStreamView | None:+ """Apply ``fields`` (enabled / event_names / slack_integration_id / slack_channel_id /+ slack_channel_name) to the caller's stream. Returns None (→ 404) when no stream matches."""+ stream = _own_streams(team_id, user).filter(id=stream_id).first()+ if stream is None:+ return None+ if "slack_integration_id" in fields:+ _validate_slack_integration(team_id, fields["slack_integration_id"])+ if "event_names" in fields:+ fields = {**fields, "event_names": _normalize_event_names(fields["event_names"])}+ for attr, value in fields.items():+ setattr(stream, attr, value)+ stream.save()+ return _to_event_stream_view(stream)+++def delete_event_stream(*, team_id: int, stream_id: str | UUID, user: "User") -> bool:+ """Delete the caller's stream (memberships cascade) and archive its managed Slack+ destination so it can't keep delivering. Returns False when none matched (→ 404)."""+ stream = _own_streams(team_id, user).filter(id=stream_id).first()+ if stream is None:+ return False+ with transaction.atomic():+ archive_event_stream_destination(stream)+ stream.delete()+ return True+++def delete_event_streams_for_user(*, user_id: int, organization_id: UUID | str) -> int:+ """Archive and delete every event stream the user owns across the organization's teams.+ Called by core when the user's organization membership is removed — a departed member's+ stream must stop delivering customer events to their Slack channel. Returns the number+ of streams deleted."""+ streams = list(EventStream.objects.unscoped().filter(created_by_id=user_id, team__organization_id=organization_id))+ for stream in streams:+ with transaction.atomic():+ archive_event_stream_destination(stream)+ stream.delete()+ return len(streams)+++def _event_streams_containing_account(account: Account) -> list[EventStream]:+ return list(EventStream.objects.for_team(account.team_id).filter(members__account=account))+++def set_event_stream_member(+ *,+ team_id: int,+ stream_id: str | UUID,+ account_id: str | UUID,+ included: bool,+ user: "User",+ user_access_control: "UserAccessControl",+) -> contracts.EventStreamView | None:+ """Add or remove an account from the caller's stream. Idempotent in both directions.+ Returns None (→ 404) when no stream matches; raises ``Account_DoesNotExist`` for a+ foreign, unknown, or (when adding) object-level-denied account."""+ stream = _own_streams(team_id, user).filter(id=stream_id).first()+ if stream is None:+ return None+ account = Account.objects.for_team(team_id).filter(id=account_id).first()+ if account is None:+ raise Account_DoesNotExist()+ if included:+ # Adding an account pipes its events into Slack, so a denied account must behave+ # like an unknown one. Removal stays team-scoped: members must be droppable even+ # after access to them is revoked.+ if get_accessible_account_id(team_id, str(account.id), user_access_control) is None:+ raise Account_DoesNotExist()+ # for_team() filters don't propagate into creation — team_id must be in defaults.+ EventStreamMember.objects.for_team(team_id).get_or_create(+ stream=stream,+ account=account,+ defaults={"team_id": team_id, "created_by": user},+ )+ else:+ EventStreamMember.objects.for_team(team_id).filter(stream=stream, account=account).delete()+ return _to_event_stream_view(stream)++# --- Announcements ---diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pyindex 280084de3d97..052d94bf239c 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -26,6 +26,10 @@ class InvalidCustomPropertyOptions(ValueError):"""Raised when a select property's options fail validation; the viewset maps it to a 400."""+class EventStreamTestMessageError(Exception):+ """The test message could not be sent — unconfigured stream or a Slack API failure."""++@dataclass(frozen=True)class AccountAssignment:"""A user assigned to an account role (CSM, account executive, account owner)."""@@ -538,6 +542,29 @@ class ExternalAccountCustomPropertiesResult:error_field: str | None = None+@stdlib_dataclass(frozen=True)+class EventStreamView:+ """A user's event stream as returned by the event-stream endpoints.++ One stream per user per team (``created_by`` is the owner): the events to watch+ (``event_names``), the owner's Slack delivery target, and the member accounts+ (``account_ids``) whose users' events are streamed.+ Defaults exist so the wrapping serializer can parse partial request bodies (see+ :class:`AccountView`).+ """++ id: UUID | None = None+ enabled: bool = False+ event_names: list[str] = field(default_factory=list)+ slack_integration: int | None = None+ slack_channel_id: str = ""+ slack_channel_name: str = ""+ account_ids: list[UUID] = field(default_factory=list)+ created_at: datetime | None = None+ created_by: int | None = None+ updated_at: datetime | None = None++class AnnouncementValidationError(ValueError):def __init__(self, detail: str | dict[str, str]) -> None:super().__init__(str(detail))diff --git a/products/customer_analytics/backend/logic/event_stream_destination.py b/products/customer_analytics/backend/logic/event_stream_destination.pynew file mode 100644index 000000000000..c5705247fded--- /dev/null+++ b/products/customer_analytics/backend/logic/event_stream_destination.py@@ -0,0 +1,231 @@+"""Provision the managed Slack HogFunction behind a Customer analytics event stream.++The stream's delivery is a regular ``template-slack`` real-time destination. Its filters+are rebuilt on every config or membership change: ``(event1 OR event2 …) AND+$group_{account_group_type_index} IN [member account group keys]``. The function is kept+disabled unless the stream is enabled AND has events AND has at least one member with a+group key — so a half-configured stream can never broadcast the whole project's traffic.+"""++from types import SimpleNamespace+from typing import TYPE_CHECKING, Any++import structlog+from slack_sdk.errors import SlackApiError++from posthog.models.integration import Integration, SlackIntegration++from products.cdp.backend.facade.api import HogFunctionSerializer+from products.cdp.backend.facade.models import HogFunction+from products.customer_analytics.backend.facade.contracts import EventStreamTestMessageError+from products.customer_analytics.backend.models import EventStream, TeamCustomerAnalyticsConfig++if TYPE_CHECKING:+ from posthog.models import Team, User++logger = structlog.get_logger(__name__)+++_SLACK_TEMPLATE = "template-slack"+_DESTINATION_TYPE = "destination"++# `exact` on an empty list compiles, but an accidental fall-through must never match a real+# group key — pair the disabled state with a filter value no group can have.+_NO_MEMBERS_SENTINEL = "$customer_analytics_event_stream_no_members"+++def account_group_type_index(team_id: int) -> int | None:+ """The group type index Customer analytics accounts map onto, or ``None`` when unset."""+ return (+ TeamCustomerAnalyticsConfig.objects.filter(team_id=team_id)+ .values_list("account_group_type_index", flat=True)+ .first()+ )+++def member_group_keys(stream: EventStream) -> list[str]:+ """Group keys (``Account.external_id``) of the stream's members. Accounts without an+ external_id have no analytics identity, so they can't be matched to events and are skipped."""+ keys = (+ stream.members.filter(account__external_id__isnull=False)+ .exclude(account__external_id="")+ .values_list("account__external_id", flat=True)+ )+ return sorted(key for key in keys if key is not None)+++def _build_filters(stream: EventStream, group_type_index: int, group_keys: list[str]) -> dict[str, Any]:+ return {+ "events": [{"id": name, "type": "events", "order": index} for index, name in enumerate(stream.event_names)],+ "properties": [+ {+ "key": f"$group_{group_type_index}",+ "value": group_keys or [_NO_MEMBERS_SENTINEL],+ "operator": "exact",+ "type": "event",+ }+ ],+ }+++def _slack_blocks(group_type_index: int) -> list[dict[str, Any]]:+ group_key_template = f"{{event.properties.$group_{group_type_index}}}"+ return [+ {+ "type": "section",+ "text": {"type": "mrkdwn", "text": "*<{person.url}|{person.name}>* triggered *{event.event}*"},+ },+ {+ "type": "context",+ "elements": [+ {"type": "mrkdwn", "text": f"Account: {group_key_template}"},+ {"type": "mrkdwn", "text": "Project: <{project.url}|{project.name}>"},+ {"type": "mrkdwn", "text": "<{event.url}|View event>"},+ ],+ },+ ]+++def _destination_config(stream: EventStream, group_type_index: int | None, group_keys: list[str]) -> dict[str, Any]:+ channel_display = stream.slack_channel_name or stream.slack_channel_id or "channel"+ enabled = bool(+ stream.enabled+ and stream.event_names+ and group_keys+ and stream.slack_integration_id+ and stream.slack_channel_id+ and group_type_index is not None+ )+ return {+ "type": _DESTINATION_TYPE,+ "enabled": enabled,+ "template_id": _SLACK_TEMPLATE,+ "name": f"Customer analytics event stream → Slack #{channel_display.lstrip('#')}",+ "description": "Streams selected customers' events live to Slack. Managed by Customer analytics.",+ "filters": _build_filters(stream, group_type_index if group_type_index is not None else 0, group_keys),+ "inputs": {+ "slack_workspace": {"value": stream.slack_integration_id},+ "channel": {"value": stream.slack_channel_id},+ "blocks": {"value": _slack_blocks(group_type_index if group_type_index is not None else 0)},+ "text": {"value": "*{person.name}* triggered *{event.event}*"},+ },+ }+++def sync_event_stream_destination(stream: EventStream, *, team: "Team", user: "User | None") -> None:+ """Reconcile the stream's managed HogFunction with its current config and membership.++ Creates the function on first sync and updates it in place afterwards, so the CDP+ workers keep a single stable function per stream. A failure propagates — the caller+ runs this inside its write transaction so a stream is never saved pointing at a+ destination that doesn't match it.+ """+ group_type_index = account_group_type_index(team.id)+ group_keys = member_group_keys(stream)+ config = _destination_config(stream, group_type_index, group_keys)++ instance = _managed_hog_function(stream)+ has_slack_config = bool(stream.slack_integration_id and stream.slack_channel_id)+ if not has_slack_config:+ if instance is None:+ # Nothing to provision yet — the template's Slack inputs are required, so the+ # function can only be created once a workspace and channel are configured.+ return+ # Keep the existing (disabled) function's inputs instead of writing null Slack values,+ # which the template's input validation rejects.+ config.pop("inputs")+ context = {+ # HogFunctionSerializer.create() reads context["request"].user for created_by.+ "request": SimpleNamespace(user=user),+ "team_id": team.id,+ "get_team": lambda: team,+ "is_create": instance is None,+ }+ if instance is not None:+ serializer = HogFunctionSerializer(instance, data=config, partial=True, context=context)+ else:+ serializer = HogFunctionSerializer(data=config, context=context)+ serializer.is_valid(raise_exception=True)+ hog_function = serializer.save()+ logger.info(+ "customer_analytics_event_stream_destination_synced",+ team_id=team.id,+ stream_id=str(stream.id),+ hog_function_id=str(hog_function.id),+ created=instance is None,+ enabled=hog_function.enabled,+ member_count=len(group_keys),+ )++ if stream.hog_function_id != hog_function.id:+ stream.hog_function_id = hog_function.id+ stream.save(update_fields=["hog_function_id"])+++def sync_event_stream_destination_by_id(*, team: "Team", stream_id: str, user: "User | None") -> None:+ """Load the stream by id and reconcile its destination — the view layer works with+ facade contracts, so it hands over ids rather than model instances."""+ stream = EventStream.objects.for_team(team.id).filter(id=stream_id).first()+ if stream is not None:+ sync_event_stream_destination(stream, team=team, user=user)+++def send_test_slack_message(*, team_id: int, stream_id: str, user: "User") -> str | None:+ """Post a test message to the caller's stream's configured Slack channel, mirroring how+ the managed destination delivers. Returns the channel id on success, ``None`` when the+ caller has no such stream; raises :class:`EventStreamTestMessageError` when the stream+ has no Slack config or Slack rejects the message."""+ stream = EventStream.objects.for_team(team_id).filter(id=stream_id, created_by=user).first()+ if stream is None:+ return None+ if not (stream.slack_integration_id and stream.slack_channel_id):+ raise EventStreamTestMessageError("Save a Slack workspace and channel before sending a test message.")+ integration = Integration.objects.filter(team_id=team_id, id=stream.slack_integration_id, kind="slack").first()+ if integration is None:+ raise EventStreamTestMessageError("The stream's Slack workspace is no longer connected.")++ try:+ SlackIntegration(integration).client.chat_postMessage(+ channel=stream.slack_channel_id,+ text=(+ ":wave: This is a test message from PostHog Customer analytics — "+ "your event stream will post matching events to this channel."+ ),+ )+ except SlackApiError as e:+ error = e.response.get("error", "unknown_error") if e.response else "unknown_error"+ logger.warning(+ "customer_analytics_event_stream_test_message_failed",+ team_id=team_id,+ stream_id=str(stream_id),+ error=error,+ )+ hint = " Invite the PostHog bot to the channel and try again." if error == "not_in_channel" else ""+ raise EventStreamTestMessageError(f"Slack rejected the test message: {error}.{hint}")+ return stream.slack_channel_id+++def archive_event_stream_destination(stream: EventStream) -> None:+ """Disable and soft-delete the stream's managed HogFunction. Invoked by the facade's+ ``delete_event_stream`` — the single deletion path for event streams."""+ function = _managed_hog_function(stream)+ if function is None:+ return+ function.enabled = False+ function.deleted = True+ # .save() (not .update()) so the post_save signal deregisters the function from the workers.+ function.save()+ logger.info(+ "customer_analytics_event_stream_destination_archived",+ team_id=stream.team_id,+ stream_id=str(stream.id),+ hog_function_id=str(function.id),+ )+++def _managed_hog_function(stream: EventStream) -> HogFunction | None:+ if not stream.hog_function_id:+ return None+ return HogFunction.objects.filter(+ team_id=stream.team_id, id=stream.hog_function_id, type=_DESTINATION_TYPE, deleted=False+ ).first()diff --git a/products/customer_analytics/backend/migrations/0022_eventstream_eventstreammember.py b/products/customer_analytics/backend/migrations/0022_eventstream_eventstreammember.pynew file mode 100644index 000000000000..6a362756cb39--- /dev/null+++ b/products/customer_analytics/backend/migrations/0022_eventstream_eventstreammember.py@@ -0,0 +1,146 @@+# Generated by Django 5.2.14 on 2026-07-03 19:47++import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++import posthog.models.utils+from posthog.migration_helpers import AddForeignKeyNotValid+++class Migration(migrations.Migration):+ dependencies = [+ ("customer_analytics", "0021_custompropertysource_column_descriptions"),+ ("posthog", "1247_oauthaccesstoken_token_idx"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.CreateModel(+ name="EventStream",+ fields=[+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7, editable=False, primary_key=True, serialize=False+ ),+ ),+ ("enabled", models.BooleanField(default=False)),+ ("event_names", models.JSONField(default=list)),+ ("slack_channel_id", models.CharField(blank=True, default="", max_length=200)),+ ("slack_channel_name", models.CharField(blank=True, default="", max_length=200)),+ ("hog_function_id", models.UUIDField(blank=True, null=True)),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "slack_integration",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to="posthog.integration",+ ),+ ),+ (+ "team",+ models.OneToOneField(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="customer_analytics_event_stream",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "abstract": False,+ },+ ),+ migrations.CreateModel(+ name="EventStreamMember",+ fields=[+ ("created_at", models.DateTimeField(auto_now_add=True)),+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7, editable=False, primary_key=True, serialize=False+ ),+ ),+ (+ "account",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="event_stream_memberships",+ to="customer_analytics.account",+ ),+ ),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "stream",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="members",+ to="customer_analytics.eventstream",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False, on_delete=django.db.models.deletion.CASCADE, to="posthog.team"+ ),+ ),+ ],+ options={+ "constraints": [+ models.UniqueConstraint(fields=("stream", "account"), name="unique_event_stream_member")+ ],+ },+ ),+ AddForeignKeyNotValid(+ model_name="eventstream",+ name="eventstream_team_id_fk",+ column="team_id",+ to_table="posthog_team",+ to_column="id",+ ),+ AddForeignKeyNotValid(+ model_name="eventstream",+ name="eventstream_created_by_id_fk",+ column="created_by_id",+ to_table="posthog_user",+ to_column="id",+ ),+ AddForeignKeyNotValid(+ model_name="eventstreammember",+ name="eventstreammember_team_id_fk",+ column="team_id",+ to_table="posthog_team",+ to_column="id",+ ),+ AddForeignKeyNotValid(+ model_name="eventstreammember",+ name="eventstreammember_created_by_id_fk",+ column="created_by_id",+ to_table="posthog_user",+ to_column="id",+ ),+ ]diff --git a/products/customer_analytics/backend/migrations/0023_eventstream_validate_fks.py b/products/customer_analytics/backend/migrations/0023_eventstream_validate_fks.pynew file mode 100644index 000000000000..652f3a8780ab--- /dev/null+++ b/products/customer_analytics/backend/migrations/0023_eventstream_validate_fks.py@@ -0,0 +1,16 @@+from django.db import migrations++from posthog.migration_helpers import ValidateForeignKey+++class Migration(migrations.Migration):+ dependencies = [+ ("customer_analytics", "0022_eventstream_eventstreammember"),+ ]++ operations = [+ ValidateForeignKey(model_name="eventstream", name="eventstream_team_id_fk"),+ ValidateForeignKey(model_name="eventstream", name="eventstream_created_by_id_fk"),+ ValidateForeignKey(model_name="eventstreammember", name="eventstreammember_team_id_fk"),+ ValidateForeignKey(model_name="eventstreammember", name="eventstreammember_created_by_id_fk"),+ ]diff --git a/products/customer_analytics/backend/migrations/0024_alter_eventstream_team_and_more.py b/products/customer_analytics/backend/migrations/0024_alter_eventstream_team_and_more.pynew file mode 100644index 000000000000..f01bf2bc8dca--- /dev/null+++ b/products/customer_analytics/backend/migrations/0024_alter_eventstream_team_and_more.py@@ -0,0 +1,30 @@+# Generated by Django 5.2.14 on 2026-07-09 17:18++import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("customer_analytics", "0023_eventstream_validate_fks"),+ ("posthog", "1247_oauthaccesstoken_token_idx"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.AlterField(+ model_name="eventstream",+ name="team",+ field=models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ migrations.AddConstraint(+ model_name="eventstream",+ constraint=models.UniqueConstraint(fields=("team", "created_by"), name="unique_event_stream_per_user"),+ ),+ ]diff --git a/products/customer_analytics/backend/migrations/0025_alter_eventstream_created_by.py b/products/customer_analytics/backend/migrations/0025_alter_eventstream_created_by.pynew file mode 100644index 000000000000..42621e512e84--- /dev/null+++ b/products/customer_analytics/backend/migrations/0025_alter_eventstream_created_by.py@@ -0,0 +1,24 @@+# Generated by Django 5.2.14 on 2026-07-09 18:16++import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("customer_analytics", "0024_alter_eventstream_team_and_more"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.AlterField(+ model_name="eventstream",+ name="created_by",+ field=models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ ]diff --git a/products/customer_analytics/backend/migrations/max_migration.txt b/products/customer_analytics/backend/migrations/max_migration.txtindex 577e8dc2359b..ec2bcbf40ba8 100644--- a/products/customer_analytics/backend/migrations/max_migration.txt+++ b/products/customer_analytics/backend/migrations/max_migration.txt@@ -1 +1 @@-0021_custompropertysource_column_descriptions+0025_alter_eventstream_created_bydiff --git a/products/customer_analytics/backend/models/__init__.py b/products/customer_analytics/backend/models/__init__.pyindex b344fed42be7..32c36079822a 100644--- a/products/customer_analytics/backend/models/__init__.py+++ b/products/customer_analytics/backend/models/__init__.py@@ -13,6 +13,7 @@ from .custom_property_sync_run import CustomPropertySyncRun, SyncStatus, SyncTrifrom .custom_property_value import CustomPropertyValuefrom .customer_journey import CustomerJourneyfrom .customer_profile_config import CustomerProfileConfig+from .event_stream import EventStream, EventStreamMemberfrom .relationship import AccountRelationship, AccountRelationshipDefinitionfrom .team_customer_analytics_config import TeamCustomerAnalyticsConfig@@ -31,6 +32,8 @@ __all__ = ["CustomerProfileConfig","DataType","DisplayType",+ "EventStream",+ "EventStreamMember","RelationshipDefinition","SyncStatus","SyncTrigger",diff --git a/products/customer_analytics/backend/models/event_stream.py b/products/customer_analytics/backend/models/event_stream.pynew file mode 100644index 000000000000..7e543caa345c--- /dev/null+++ b/products/customer_analytics/backend/models/event_stream.py@@ -0,0 +1,57 @@+from django.db import models++from posthog.models.scoping.root_mixin import TeamScopedRootMixin+from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel+++class EventStream(TeamScopedRootMixin, UUIDModel, CreatedMetaFields, UpdatedMetaFields):+ """A live feed of selected customers' events, delivered to a Slack channel.++ One per user per team (``created_by`` is the owner): each team member picks their own+ channel and member accounts. Delivery happens through a managed ``template-slack``+ HogFunction destination (referenced by ``hog_function_id``) whose filters are rebuilt+ from ``event_names`` and the members' account group keys on every change.+ """++ team = models.ForeignKey(+ "posthog.Team",+ on_delete=models.CASCADE,+ db_constraint=False,+ related_name="+",+ )+ created_by = models.ForeignKey("posthog.User", on_delete=models.CASCADE, db_constraint=False)++ enabled = models.BooleanField(default=False)+ event_names = models.JSONField(default=list)++ slack_integration = models.ForeignKey(+ "posthog.Integration", on_delete=models.SET_NULL, null=True, blank=True, related_name="+"+ )+ slack_channel_id = models.CharField(max_length=200, blank=True, default="")+ slack_channel_name = models.CharField(max_length=200, blank=True, default="")++ hog_function_id = models.UUIDField(null=True, blank=True)++ class Meta:+ constraints = [+ models.UniqueConstraint(fields=["team", "created_by"], name="unique_event_stream_per_user"),+ ]+++class EventStreamMember(TeamScopedRootMixin, UUIDModel, CreatedMetaFields):+ """An account included in the team's event stream."""++ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)+ created_by = models.ForeignKey(+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False+ )++ stream = models.ForeignKey(EventStream, on_delete=models.CASCADE, related_name="members")+ account = models.ForeignKey(+ "customer_analytics.Account", on_delete=models.CASCADE, related_name="event_stream_memberships"+ )++ class Meta:+ constraints = [+ models.UniqueConstraint(fields=["stream", "account"], name="unique_event_stream_member"),+ ]diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.pyindex a80ef2e2e908..57a639e0b6ff 100644--- a/products/customer_analytics/backend/presentation/views/serializers.py+++ b/products/customer_analytics/backend/presentation/views/serializers.py@@ -45,6 +45,7 @@ from products.customer_analytics.backend.facade.contracts import (CustomPropertyReference,CustomPropertySourceView,CustomPropertySyncRunView,+ EventStreamView,)# Scope (value, label) pairs, kept in sync with ``CustomerProfileConfig.Scope``. Declared@@ -773,3 +774,84 @@ class AccountRelationshipWriteSerializer(serializers.Serializer):user = serializers.IntegerField(help_text="PostHog user id of the assignee. Must be a member of the account's organization.")+++class EventStreamSerializer(DataclassSerializer):+ """The caller's event stream — a live feed of selected accounts' events posted to a+ Slack channel of their choice. One stream per user per project."""++ id = serializers.UUIDField(read_only=True)+ enabled = serializers.BooleanField(+ required=False,+ default=False,+ help_text=(+ "Whether the stream delivers to Slack. Delivery also requires at least one event, "+ "at least one member account with an external ID, and a Slack workspace + channel."+ ),+ )+ event_names = serializers.ListField(+ child=serializers.CharField(max_length=400),+ required=False,+ default=list,+ help_text="Names of the events to stream (matched exactly). Duplicates and blanks are dropped.",+ )+ slack_integration = serializers.IntegerField(+ required=False,+ allow_null=True,+ help_text="ID of the team's Slack workspace integration to deliver through.",+ )+ slack_channel_id = serializers.CharField(+ max_length=200,+ required=False,+ allow_blank=True,+ default="",+ help_text="Slack channel ID to post to (e.g. C0123ABC).",+ )+ slack_channel_name = serializers.CharField(+ max_length=200,+ required=False,+ allow_blank=True,+ default="",+ help_text="Display name of the Slack channel (e.g. #customer-events). Informational only.",+ )+ account_ids = serializers.ListField(+ child=serializers.UUIDField(),+ read_only=True,+ help_text=(+ "UUIDs of the member accounts whose users' events are streamed. "+ "Managed via the add_account/remove_account endpoints."+ ),+ )+ created_at = serializers.DateTimeField(read_only=True)+ created_by = serializers.IntegerField(read_only=True, allow_null=True)+ updated_at = serializers.DateTimeField(read_only=True, allow_null=True)++ class Meta:+ dataclass = EventStreamView+ ref_name = "EventStream"+ fields = [+ "id",+ "enabled",+ "event_names",+ "slack_integration",+ "slack_channel_id",+ "slack_channel_name",+ "account_ids",+ "created_at",+ "created_by",+ "updated_at",+ ]+++class EventStreamMemberWriteSerializer(serializers.Serializer):+ """Request body for adding or removing an event-stream member account."""++ account_id = serializers.UUIDField(help_text="UUID of the account to add to or remove from the stream.")+++class EventStreamTestMessageSerializer(serializers.Serializer):+ """Result of posting an event-stream test message to Slack."""++ channel_id = serializers.CharField(+ read_only=True, help_text="Slack channel ID the test message was posted to (e.g. C0123ABC)."+ )diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.pyindex 6acfa944d1a9..fc1c9e8399ee 100644--- a/products/customer_analytics/backend/presentation/views/views.py+++ b/products/customer_analytics/backend/presentation/views/views.py@@ -17,6 +17,8 @@ from dataclasses import asdictfrom typing import Any, castfrom uuid import UUID+from django.db import transaction+from drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter, extend_schemafrom rest_framework import mixins, status, viewsets@@ -24,6 +26,7 @@ from rest_framework.decorators import actionfrom rest_framework.exceptions import PermissionDenied, ValidationErrorfrom rest_framework.request import Requestfrom rest_framework.response import Response+from rest_framework.throttling import UserRateThrottlefrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.tagged_item import TaggedItemViewSetMixin@@ -52,6 +55,9 @@ from products.customer_analytics.backend.presentation.views.serializers import (CustomPropertyValueSerializer,CustomPropertyValueSuggestionsResponseSerializer,CustomPropertyValueWriteSerializer,+ EventStreamMemberWriteSerializer,+ EventStreamSerializer,+ EventStreamTestMessageSerializer,)from ee.hogai.tools.create_notebook.tiptap import markdown_to_tiptap_nodes@@ -1408,3 +1414,174 @@ class AccountRelationshipViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixif relationship is None:return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)return Response(AccountRelationshipSerializer(relationship).data)+++_EVENT_STREAM_ID_PARAM = OpenApiParameter(+ "id",+ OpenApiTypes.STR,+ OpenApiParameter.PATH,+ description="A UUID string identifying this event stream.",+)+++class EventStreamTestMessageThrottle(UserRateThrottle):+ """Each test message posts to Slack, so cap the rate per user regardless of auth method."""++ scope = "event_stream_test_message"+ rate = "6/minute"+++@extend_schema(tags=["customer_analytics"])+class EventStreamViewSet(+ TeamAndOrgViewSetMixin,+ AccessControlViewSetMixin,+ mixins.CreateModelMixin,+ mixins.UpdateModelMixin,+ mixins.DestroyModelMixin,+ mixins.ListModelMixin,+ viewsets.GenericViewSet,+):+ """The caller's event stream: a live feed of selected accounts' events posted to a+ Slack channel of their choice. Per-user — each team member owns at most one stream, and+ every endpoint is scoped to the caller's own. Delivery runs through a managed CDP+ destination that is re-provisioned inside the same transaction as every write, so+ config and delivery can't drift apart."""++ scope_object = "account"+ serializer_class = EventStreamSerializer+ pagination_class = None # at most one stream exists per team (one-to-one) — nothing to paginate+ queryset = None # data is reached through the facade; declared for router/schema only++ def list(self, request: Request, *args, **kwargs) -> Response:+ streams = api.list_event_streams(self.team_id, user=cast(User, request.user))+ return Response(EventStreamSerializer(instance=streams, many=True).data)++ def create(self, request: Request, *args, **kwargs) -> Response:+ serializer = EventStreamSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ data = serializer.validated_data+ user = cast(User, request.user)+ try:+ with transaction.atomic():+ stream = api.create_event_stream(+ team_id=self.team_id,+ enabled=data.enabled,+ event_names=data.event_names,+ slack_integration_id=data.slack_integration,+ slack_channel_id=data.slack_channel_id,+ slack_channel_name=data.slack_channel_name,+ user=user,+ )+ api.sync_event_stream_destination_by_id(team=self.team, stream_id=str(stream.id), user=user)+ except api.EventStreamValidationError as e:+ raise ValidationError(str(e))+ except api.EventStreamConflictError as e:+ raise Conflict(str(e))+ return Response(EventStreamSerializer(instance=stream).data, status=status.HTTP_201_CREATED)++ @extend_schema(parameters=[_EVENT_STREAM_ID_PARAM])+ def update(self, request: Request, *args, **kwargs) -> Response:+ partial = kwargs.pop("partial", False)+ serializer = EventStreamSerializer(data=request.data, partial=partial)+ serializer.is_valid(raise_exception=True)+ user = cast(User, request.user)+ try:+ with transaction.atomic():+ stream = api.update_event_stream(+ team_id=self.team_id,+ stream_id=self.kwargs["pk"],+ fields=_event_stream_write_fields(serializer.validated_data, request.data),+ user=user,+ )+ if stream is None:+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)+ api.sync_event_stream_destination_by_id(team=self.team, stream_id=str(stream.id), user=user)+ except api.EventStreamValidationError as e:+ raise ValidationError(str(e))+ return Response(EventStreamSerializer(instance=stream).data)++ @extend_schema(parameters=[_EVENT_STREAM_ID_PARAM])+ def partial_update(self, request: Request, *args, **kwargs) -> Response:+ kwargs["partial"] = True+ return self.update(request, *args, **kwargs)++ @extend_schema(parameters=[_EVENT_STREAM_ID_PARAM])+ def destroy(self, request: Request, *args, **kwargs) -> Response:+ deleted = api.delete_event_stream(+ team_id=self.team_id, stream_id=self.kwargs["pk"], user=cast(User, request.user)+ )+ if not deleted:+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)+ return Response(status=status.HTTP_204_NO_CONTENT)++ @extend_schema(+ parameters=[_EVENT_STREAM_ID_PARAM],+ request=EventStreamMemberWriteSerializer,+ responses={200: EventStreamSerializer},+ )+ @action(methods=["POST"], detail=True)+ def add_account(self, request: Request, *args, **kwargs) -> Response:+ return self._set_member(request, included=True)++ @extend_schema(+ parameters=[_EVENT_STREAM_ID_PARAM],+ request=EventStreamMemberWriteSerializer,+ responses={200: EventStreamSerializer},+ )+ @action(methods=["POST"], detail=True)+ def remove_account(self, request: Request, *args, **kwargs) -> Response:+ return self._set_member(request, included=False)++ @extend_schema(+ parameters=[_EVENT_STREAM_ID_PARAM],+ request=None,+ responses={200: EventStreamTestMessageSerializer},+ )+ @action(methods=["POST"], detail=True, throttle_classes=[EventStreamTestMessageThrottle])+ def send_test_message(self, request: Request, *args, **kwargs) -> Response:+ try:+ channel_id = api.send_test_slack_message(+ team_id=self.team_id, stream_id=self.kwargs["pk"], user=cast(User, request.user)+ )+ except contracts.EventStreamTestMessageError as e:+ raise ValidationError(str(e))+ if channel_id is None:+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)+ return Response(EventStreamTestMessageSerializer(instance={"channel_id": channel_id}).data)++ def _set_member(self, request: Request, *, included: bool) -> Response:+ write = EventStreamMemberWriteSerializer(data=request.data)+ write.is_valid(raise_exception=True)+ user = cast(User, request.user)+ try:+ with transaction.atomic():+ stream = api.set_event_stream_member(+ team_id=self.team_id,+ stream_id=self.kwargs["pk"],+ account_id=write.validated_data["account_id"],+ included=included,+ user=user,+ user_access_control=self.user_access_control,+ )+ if stream is None:+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)+ api.sync_event_stream_destination_by_id(team=self.team, stream_id=str(stream.id), user=user)+ except api.Account_DoesNotExist:+ raise ValidationError({"account_id": "Account not found for this team."})+ return Response(EventStreamSerializer(instance=stream).data)+++# Request field -> model column, for translating a write body into facade update fields.+_EVENT_STREAM_WRITE_FIELDS = {+ "enabled": "enabled",+ "event_names": "event_names",+ "slack_integration": "slack_integration_id",+ "slack_channel_id": "slack_channel_id",+ "slack_channel_name": "slack_channel_name",+}+++def _event_stream_write_fields(validated, raw_data: dict) -> dict:+ """The event-stream columns the caller actually sent, so a PATCH that omits a field+ leaves it untouched (the serializer fields carry defaults for create)."""+ return {column: getattr(validated, key) for key, column in _EVENT_STREAM_WRITE_FIELDS.items() if key in raw_data}diff --git a/products/customer_analytics/backend/routes.py b/products/customer_analytics/backend/routes.pyindex 44f83163a5a5..75e553de0f4e 100644--- a/products/customer_analytics/backend/routes.py+++ b/products/customer_analytics/backend/routes.py@@ -15,6 +15,7 @@ from products.customer_analytics.backend.presentation.views.views import (CustomPropertyDefinitionViewSet,CustomPropertySourceViewSet,CustomPropertyValueViewSet,+ EventStreamViewSet,)@@ -62,6 +63,12 @@ def register_routes(routers: RouterRegistry) -> None:"project_account_notes",["team_id"],)+ routers.projects.register(+ r"event_streams",+ EventStreamViewSet,+ "project_event_streams",+ ["team_id"],+ )project_accounts_router = routers.projects.register(r"accounts", AccountViewSet, "project_accounts", ["team_id"])project_accounts_router.register(r"notebooks", AccountNotebookViewSet, "project_account_notebooks", ["team_id", "account_id"]diff --git a/products/customer_analytics/backend/test/test_event_stream.py b/products/customer_analytics/backend/test/test_event_stream.pynew file mode 100644index 000000000000..c935b60274ed--- /dev/null+++ b/products/customer_analytics/backend/test/test_event_stream.py@@ -0,0 +1,352 @@+from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django.core.cache import cache++from rest_framework import status+from slack_sdk.errors import SlackApiError++from posthog.cdp.templates.hog_function_template import sync_template_to_db+from posthog.cdp.templates.slack.template_slack import template as template_slack+from posthog.constants import AvailableFeature+from posthog.models import Integration, Organization, OrganizationMembership, Team++from products.cdp.backend.models.hog_functions.hog_function import HogFunction+from products.customer_analytics.backend.logic.event_stream_destination import _NO_MEMBERS_SENTINEL+from products.customer_analytics.backend.models import EventStream, EventStreamMember, TeamCustomerAnalyticsConfig+from products.customer_analytics.backend.test.factories import create_account++from ee.models.rbac.access_control import AccessControl+++class TestEventStreamViewSet(APIBaseTest):+ def setUp(self):+ super().setUp()+ # Throttle history lives in the process-local cache and would leak across tests.+ cache.clear()+ sync_template_to_db(template_slack)+ TeamCustomerAnalyticsConfig.objects.update_or_create(team=self.team, defaults={"account_group_type_index": 0})+ self.integration = Integration.objects.create(+ team=self.team, kind="slack", config={"team": {"id": "T123"}}, sensitive_config={"access_token": "x"}+ )+ self.base_url = f"/api/projects/{self.team.id}/event_streams/"+ self.valid_data = {+ "enabled": True,+ "event_names": ["$pageview", "dashboard_created"],+ "slack_integration": self.integration.id,+ "slack_channel_id": "C0123ABC",+ "slack_channel_name": "#customer-events",+ }++ def _create_stream(self, data: dict | None = None) -> dict:+ response = self.client.post(self.base_url, data or self.valid_data, format="json")+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ return response.json()++ def _destination(self, stream: dict) -> HogFunction:+ hog_function_id = EventStream.objects.unscoped().get(id=stream["id"]).hog_function_id+ assert hog_function_id is not None+ return HogFunction.objects.get(id=hog_function_id)++ def _group_filter(self, function: HogFunction) -> dict:+ return (function.filters or {})["properties"][0]++ def _inputs(self, function: HogFunction) -> dict:+ return function.inputs or {}++ def _filtered_events(self, function: HogFunction) -> list[dict]:+ return (function.filters or {})["events"]++ def test_create_without_slack_defers_destination_until_channel_is_set(self):+ stream = self._create_stream({"event_names": ["$pageview"]})++ self.assertIsNone(EventStream.objects.unscoped().get(id=stream["id"]).hog_function_id)++ response = self.client.patch(+ f"{self.base_url}{stream['id']}/",+ {"slack_integration": self.integration.id, "slack_channel_id": "C0123ABC"},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ function = self._destination(stream)+ self.assertEqual(self._inputs(function)["slack_workspace"]["value"], self.integration.id)+ self.assertEqual(self._inputs(function)["channel"]["value"], "C0123ABC")++ def test_clearing_channel_keeps_existing_destination_inputs(self):+ stream = self._create_stream()++ response = self.client.patch(f"{self.base_url}{stream['id']}/", {"slack_channel_id": ""}, format="json")++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ function = self._destination(stream)+ self.assertFalse(function.enabled)+ self.assertEqual(self._inputs(function)["slack_workspace"]["value"], self.integration.id)+ self.assertEqual(self._inputs(function)["channel"]["value"], "C0123ABC")++ def test_create_provisions_disabled_destination_until_members_exist(self):+ stream = self._create_stream()++ function = self._destination(stream)+ self.assertEqual(function.template_id, "template-slack")+ self.assertEqual(function.type, "destination")+ self.assertFalse(function.enabled)+ self.assertEqual(self._group_filter(function)["value"], [_NO_MEMBERS_SENTINEL])+ self.assertEqual(self._inputs(function)["slack_workspace"]["value"], self.integration.id)+ self.assertEqual(self._inputs(function)["channel"]["value"], "C0123ABC")++ def test_add_and_remove_account_resyncs_destination_filters(self):+ stream = self._create_stream()+ acme = create_account(team_id=self.team.id, name="Acme", external_id="org-acme")+ globex = create_account(team_id=self.team.id, name="Globex", external_id="org-globex")++ for account in (acme, globex):+ response = self.client.post(+ f"{self.base_url}{stream['id']}/add_account/", {"account_id": str(account.id)}, format="json"+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())++ self.assertCountEqual(response.json()["account_ids"], [str(acme.id), str(globex.id)])+ function = self._destination(stream)+ self.assertTrue(function.enabled)+ self.assertEqual(+ self._group_filter(function),+ {"key": "$group_0", "value": ["org-acme", "org-globex"], "operator": "exact", "type": "event"},+ )+ self.assertEqual([event["id"] for event in self._filtered_events(function)], ["$pageview", "dashboard_created"])++ for account in (acme, globex):+ response = self.client.post(+ f"{self.base_url}{stream['id']}/remove_account/", {"account_id": str(account.id)}, format="json"+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())++ self.assertEqual(response.json()["account_ids"], [])+ function.refresh_from_db()+ self.assertFalse(function.enabled)+ self.assertEqual(self._group_filter(function)["value"], [_NO_MEMBERS_SENTINEL])++ def test_account_without_external_id_does_not_enable_destination(self):+ stream = self._create_stream()+ account = create_account(team_id=self.team.id, name="No group key", external_id=None)++ response = self.client.post(+ f"{self.base_url}{stream['id']}/add_account/", {"account_id": str(account.id)}, format="json"+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ self.assertEqual(response.json()["account_ids"], [str(account.id)])+ function = self._destination(stream)+ self.assertFalse(function.enabled)+ self.assertEqual(self._group_filter(function)["value"], [_NO_MEMBERS_SENTINEL])++ def test_second_stream_for_same_user_conflicts(self):+ self._create_stream()++ response = self.client.post(self.base_url, self.valid_data, format="json")++ self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)+ self.assertEqual(EventStream.objects.unscoped().filter(team_id=self.team.id).count(), 1)++ def test_deleting_owner_deletes_stream(self):+ stream = self._create_stream()++ self.user.delete()++ self.assertFalse(EventStream.objects.unscoped().filter(id=stream["id"]).exists())++ def test_streams_are_per_user(self):+ stream = self._create_stream()+ teammate = self._create_user("[email protected]")+ self.client.force_login(teammate)++ self.assertEqual(self.client.get(self.base_url).json(), [])+ response = self.client.patch(f"{self.base_url}{stream['id']}/", {"enabled": False}, format="json")+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)++ response = self.client.post(self.base_url, self.valid_data, format="json")+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())+ self.assertEqual(EventStream.objects.unscoped().filter(team_id=self.team.id).count(), 2)++ def test_foreign_slack_integration_is_rejected(self):+ other_org = Organization.objects.create(name="other org")+ other_team = Team.objects.create(organization=other_org, name="other team")+ foreign_integration = Integration.objects.create(team=other_team, kind="slack", config={}, sensitive_config={})++ response = self.client.post(+ self.base_url, {**self.valid_data, "slack_integration": foreign_integration.id}, format="json"+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertFalse(EventStream.objects.unscoped().filter(team_id=self.team.id).exists())++ def test_foreign_account_is_rejected_on_add(self):+ stream = self._create_stream()+ other_org = Organization.objects.create(name="other org")+ other_team = Team.objects.create(organization=other_org, name="other team")+ foreign_account = create_account(team_id=other_team.id, name="Foreign", external_id="org-foreign")++ response = self.client.post(+ f"{self.base_url}{stream['id']}/add_account/", {"account_id": str(foreign_account.id)}, format="json"+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertFalse(EventStreamMember.objects.unscoped().filter(stream_id=stream["id"]).exists())+ self.assertEqual(self._group_filter(self._destination(stream))["value"], [_NO_MEMBERS_SENTINEL])++ def test_object_level_denied_account_is_rejected_on_add_but_still_removable(self):+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save()+ stream = self._create_stream()+ account = create_account(team_id=self.team.id, name="Denied", external_id="org-denied")+ self.client.post(f"{self.base_url}{stream['id']}/add_account/", {"account_id": str(account.id)}, format="json")+ AccessControl.objects.create(+ team=self.team,+ resource="account",+ resource_id=str(account.id),+ access_level="none",+ organization_member=self.organization_membership,+ )++ response = self.client.post(+ f"{self.base_url}{stream['id']}/add_account/", {"account_id": str(account.id)}, format="json"+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ response = self.client.post(+ f"{self.base_url}{stream['id']}/remove_account/", {"account_id": str(account.id)}, format="json"+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ self.assertEqual(response.json()["account_ids"], [])+ self.assertFalse(EventStreamMember.objects.unscoped().filter(stream_id=stream["id"]).exists())++ def test_update_resyncs_destination_and_normalizes_event_names(self):+ stream = self._create_stream()+ account = create_account(team_id=self.team.id, name="Acme", external_id="org-acme")+ self.client.post(f"{self.base_url}{stream['id']}/add_account/", {"account_id": str(account.id)}, format="json")++ response = self.client.patch(+ f"{self.base_url}{stream['id']}/",+ {"event_names": ["signup", "signup", "invoice_paid"]},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ self.assertEqual(response.json()["event_names"], ["signup", "invoice_paid"])+ function = self._destination(stream)+ self.assertEqual([event["id"] for event in self._filtered_events(function)], ["signup", "invoice_paid"])+ self.assertTrue(function.enabled)++ response = self.client.patch(f"{self.base_url}{stream['id']}/", {"enabled": False}, format="json")++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ function.refresh_from_db()+ self.assertFalse(function.enabled)++ def test_destroy_archives_destination(self):+ stream = self._create_stream()+ function = self._destination(stream)++ response = self.client.delete(f"{self.base_url}{stream['id']}/")++ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)+ self.assertFalse(EventStream.objects.unscoped().filter(id=stream["id"]).exists())+ function.refresh_from_db()+ self.assertTrue(function.deleted)+ self.assertFalse(function.enabled)++ @patch("products.customer_analytics.backend.logic.event_stream_destination.SlackIntegration")+ def test_send_test_message_posts_to_configured_channel(self, mock_slack):+ stream = self._create_stream()++ response = self.client.post(f"{self.base_url}{stream['id']}/send_test_message/")++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ self.assertEqual(response.json(), {"channel_id": "C0123ABC"})+ self.assertEqual(mock_slack.return_value.client.chat_postMessage.call_args.kwargs["channel"], "C0123ABC")++ @patch("products.customer_analytics.backend.logic.event_stream_destination.SlackIntegration")+ def test_send_test_message_requires_saved_slack_config(self, mock_slack):+ stream = self._create_stream({"event_names": ["$pageview"]})++ response = self.client.post(f"{self.base_url}{stream['id']}/send_test_message/")++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ mock_slack.return_value.client.chat_postMessage.assert_not_called()++ @patch("products.customer_analytics.backend.logic.event_stream_destination.SlackIntegration")+ def test_send_test_message_surfaces_slack_rejection(self, mock_slack):+ mock_slack.return_value.client.chat_postMessage.side_effect = SlackApiError(+ "error", {"error": "not_in_channel"}+ )+ stream = self._create_stream()++ response = self.client.post(f"{self.base_url}{stream['id']}/send_test_message/")++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertIn("not_in_channel", response.json()["detail"])++ def test_list_is_team_scoped(self):+ stream = self._create_stream()+ other_org = Organization.objects.create(name="other org")+ other_team = Team.objects.create(organization=other_org, name="other team")+ other_owner = self._create_user("[email protected]")+ EventStream.objects.unscoped().create(team=other_team, created_by=other_owner, event_names=["foreign_event"])++ response = self.client.get(self.base_url)++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual([row["id"] for row in response.json()], [stream["id"]])++ def test_membership_removal_deletes_stream_and_archives_destination(self):+ teammate = self._create_user("[email protected]")+ self.client.force_login(teammate)+ stream = self._create_stream()+ function = self._destination(stream)++ OrganizationMembership.objects.get(user=teammate, organization=self.organization).delete()++ self.assertFalse(EventStream.objects.unscoped().filter(id=stream["id"]).exists())+ function.refresh_from_db()+ self.assertTrue(function.deleted)+ self.assertFalse(function.enabled)++ @patch("products.customer_analytics.backend.logic.event_stream_destination.SlackIntegration")+ def test_send_test_message_is_rate_limited(self, mock_slack):+ stream = self._create_stream()++ for _ in range(6):+ response = self.client.post(f"{self.base_url}{stream['id']}/send_test_message/")+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())++ response = self.client.post(f"{self.base_url}{stream['id']}/send_test_message/")++ self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)++ def test_account_deletion_resyncs_destination_filters(self):+ stream = self._create_stream()+ account = create_account(team_id=self.team.id, name="Acme", external_id="org-acme")+ self.client.post(f"{self.base_url}{stream['id']}/add_account/", {"account_id": str(account.id)}, format="json")+ function = self._destination(stream)+ self.assertTrue(function.enabled)++ response = self.client.delete(f"/api/projects/{self.team.id}/accounts/{account.id}/")++ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)+ function.refresh_from_db()+ self.assertFalse(function.enabled)+ self.assertEqual(self._group_filter(function)["value"], [_NO_MEMBERS_SENTINEL])++ def test_account_external_id_change_resyncs_destination_filters(self):+ stream = self._create_stream()+ account = create_account(team_id=self.team.id, name="Acme", external_id="org-acme")+ self.client.post(f"{self.base_url}{stream['id']}/add_account/", {"account_id": str(account.id)}, format="json")++ response = self.client.patch(+ f"/api/projects/{self.team.id}/accounts/{account.id}/", {"external_id": "org-acme-2"}, format="json"+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ self.assertEqual(self._group_filter(self._destination(stream))["value"], ["org-acme-2"])diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex c6ae5da5f4d8..62df1e7e4b88 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -25,13 +25,14 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_HOGQL_DATA_NODE_KEY, acc│ AccountsOverviewTilesButton + AccountsColumnConfigurator on the right├── AccountsOverviewTiles metric tiles across the filtered set└── AccountsHogQLTable the DataTable; per-column renderers; controlled row expansion- └── AccountNotebooksExpansion expanded row: sidebar (Useful links + active-relationships summary) + LemonTabs(Notes/Users/Relationships/Usage/Spend/Opportunities)+ └── AccountNotebooksExpansion expanded row: sidebar (Useful links + active-relationships summary) + LemonTabs(Notes/Users/Relationships/Usage/Spend/Opportunities/Event stream)├── (notes) paginated/searchable/sortable LemonTable + "New note" button (accountNotebooksLogic, keyed by accountId)├── (users) AccountRelatedUsersExpansion (accountRelatedUsersLogic, keyed by externalId)├── (relationships) AccountRelationshipsExpansion (accountRelationshipsLogic, keyed by accountId — full assignment timeline, paginated; assign/end controls + definition filter, current assignments sorted on top)├── (usage) AccountBillingExpansion kind="usage" (accountBillingLogic — a saved billing-usage insight)├── (spend) AccountBillingExpansion kind="spend" (accountBillingLogic — saved billing-spend insights)└── (opportunities) AccountOpportunitiesExpansion (accountOpportunitiesLogic, keyed by accountId — DWH Salesforce opportunities)+ └── (event_stream) AccountEventStreamToggle (`../EventStream/`) flag-gated tab (CUSTOMER_ANALYTICS_CSP); membership toggle for the Slack event stream```### Logics and what each owns@@ -73,7 +74,7 @@ Sort safety: removing the sorted column drops the sort (`clearSortIfColumnRemove## The expanded row-`AccountsHogQLTable.useExpandable()` makes expansion **controlled** by `accountsExpansionLogic`: `isRowExpanded` reads `expandedAccountIds`, `onRowExpand`/`onRowCollapse` dispatch `toggleAccountExpanded`. The body is `AccountNotebooksExpansion`, a `LemonTabs` over `notes` / `users` / `relationships` / `usage` / `spend` / `opportunities` (`AccountExpansionTab`) plus the sidebar (Useful links + an active-relationships summary, `ActiveRelationships`, hidden when nothing is assigned). Active tab comes from `activeTabFor(accountId)` (defaults to `notes`).+`AccountsHogQLTable.useExpandable()` makes expansion **controlled** by `accountsExpansionLogic`: `isRowExpanded` reads `expandedAccountIds`, `onRowExpand`/`onRowCollapse` dispatch `toggleAccountExpanded`. The body is `AccountNotebooksExpansion`, a `LemonTabs` over `notes` / `users` / `relationships` / `usage` / `spend` / `opportunities` / `event_stream` (`AccountExpansionTab`; the `event_stream` tab is gated by the `CUSTOMER_ANALYTICS_CSP` flag) plus the sidebar (Useful links + an active-relationships summary, `ActiveRelationships`, hidden when nothing is assigned). Active tab comes from `activeTabFor(accountId)` (defaults to `notes`).**Tab data is cached for the row's expanded lifetime, not refetched per tab switch.** `LemonTabs` only renders the active tab's content (keyed by `activeKey`), so a tab's logic would normally unmount the moment you switch away and refetch on return. To avoid that, `AccountNotebooksExpansion` holds a mount reference to each per-tab logic via `useMountedLogic` — `accountRelatedUsersLogic({ externalId })`, `accountRelationshipsLogic({ accountId })`, `accountBillingLogic` for both `kind: 'usage'` and `kind: 'spend'`, and `accountOpportunitiesLogic({ accountId })`. Since `AccountNotebooksExpansion` stays mounted for as long as the row is expanded (it's the `expandedRowRender` body), those keyed instances survive tab switches and only tear down when the row collapses. The `useMountedLogic` props must stay identical to the `useValues` props in the tab components (`AccountRelatedUsersExpansion`, `AccountRelationshipsExpansion`, `AccountBillingExpansion`, `AccountOpportunitiesExpansion`) so both resolve to the same keyed instance. `accountNotebooksLogic` and `accountLinksLogic` already mount at this level (Notes content and the always-rendered sidebar), so they need no explicit mount reference. Data is loaded once on mount and not auto-refreshed while the row stays open — acceptable since this data needn't be live.@@ -193,10 +194,13 @@ We track user actions on the Accounts list with `posthog.capture()`. Conventions| `customer analytics accounts note created` | `accountNotebooksLogic` `createNoteSuccess` listener | `notebook_short_id` || `customer analytics accounts notes searched` | `accountNotebooksLogic` `setSearchTerm` listener (post-debounce) | `has_query`, `query_length` (no raw text) || `customer analytics accounts notes sorted` | `accountNotebooksLogic` `setSorting` listener | `column` (`created_at` \| `created_by` \| null), `direction` (`asc` \| `desc` \| `cleared`) |-| `customer analytics account tab viewed` | `accountsExpansionLogic` `setActiveTab` listener (genuine tab clicks only; programmatic `openAccountTab` navigation does not fire it) | `tab` (`notes` \| `users` \| `relationships` \| `usage` \| `spend` \| `opportunities`) |+| `customer analytics account tab viewed` | `accountsExpansionLogic` `setActiveTab` listener (genuine tab clicks only; programmatic `openAccountTab` navigation does not fire it) | `tab` (`notes` \| `users` \| `relationships` \| `usage` \| `spend` \| `opportunities` \| `event_stream`) || `customer analytics account usage series toggled` | `accountBillingLogic` `toggleHiddenSeriesKey` listener (dispatched by the `AccountBillingSeriesToggle` chips) | `kind` (`usage` \| `spend`), `is_hidden` (the post-click state), `series_count` (no series label / no PII) || `customer analytics account related user clicked` | `AccountRelatedUsersExpansion.tsx` user `<Link>` `onClick` | _(none — customer end-user PII kept out)_ || `customer analytics account opportunity clicked` | `AccountOpportunitiesExpansion.tsx` opportunity name `<Link>` `onClick` | _(none — CRM record id/url kept out)_ |+| `customer analytics account event stream toggled` | `eventStreamLogic` (`../EventStream/`) `setAccountMembership` listener — the "Include in event stream" toggle in the expanded row's Event stream tab | `account_id`, `included`, `member_count` |+| `customer analytics event stream config saved` | `eventStreamLogic` `saveEventStreamSuccess` listener — the Save button in the Event stream settings section | `enabled`, `event_count`, `has_slack_channel`, `member_count` |+| `customer analytics event stream test message sent` | `eventStreamLogic` `sendTestMessageSuccess` listener — the "Send test message" button in the Event stream settings section | `event_count`, `member_count` || `customer analytics notes tab viewed` | `accountNotesLogic` (`../AccountNotes/`) `afterMount` — the top-level Notes tab, not the per-account expansion | _(none — funnel anchor)_ || `customer analytics notes tab searched` | `accountNotesLogic` `setSearch` listener (post-debounce) | `has_query`, `query_length` (no raw text) || `customer analytics notes tab filtered` | `accountNotesLogic` `reportFilterChange` listener (dispatched by the filter controls only, so the "My notes"/"My accounts" cascade doesn't double-fire) | `filter_type` (`created_by` \| `account` \| `my_notes` \| `my_accounts`), `is_cleared`; for `created_by` also `user_count`; for `my_notes`/`my_accounts` also `value` (no account id/name logged) |diff --git a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsxindex 06f637dc5423..59f3c087de63 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx@@ -15,13 +15,16 @@ import {} from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'+import { FEATURE_FLAGS } from 'lib/constants'import { IconSlack } from 'lib/lemon-ui/icons'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { fullName } from 'lib/utils/strings'import { notebookPanelLogic } from 'scenes/notebooks/NotebookPanel/notebookPanelLogic'import { urls } from 'scenes/urls'import type { AccountNotebookApi } from 'products/customer_analytics/frontend/generated/api.schemas'+import { AccountEventStreamToggle } from '../EventStream/AccountEventStreamToggle'import { AccountBillingExpansion } from './AccountBillingExpansion'import { accountBillingLogic } from './accountBillingLogic'import { accountLinksLogic } from './accountLinksLogic'@@ -141,6 +144,7 @@ export function AccountNotebooksExpansion({useMountedLogic(accountBillingLogic({ accountId, externalId, kind: 'spend' }))useMountedLogic(accountOpportunitiesLogic({ accountId }))const { setSearchTerm, setSorting, createNote } = useActions(logic)+ const { featureFlags } = useValues(featureFlagLogic)const { activeTabFor } = useValues(accountsExpansionLogic)const { setActiveTab } = useActions(accountsExpansionLogic)const { selectNotebook } = useActions(notebookPanelLogic)@@ -305,6 +309,12 @@ export function AccountNotebooksExpansion({label: 'Opportunities',content: <AccountOpportunitiesExpansion accountId={accountId} />,},+ // Flag-gated here (not just inside the component) so the tab label hides too.+ !!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP] && {+ key: 'event_stream' as const,+ label: 'Event stream',+ content: <AccountEventStreamToggle accountId={accountId} externalId={externalId} />,+ },]}/></div>diff --git a/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.tsindex 2cab60be2052..5388d687c46e 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts@@ -3,7 +3,14 @@ import posthog from 'posthog-js'import { AccountsEvents } from './constants'-export type AccountExpansionTab = 'notes' | 'users' | 'relationships' | 'usage' | 'spend' | 'opportunities'+export type AccountExpansionTab =+ | 'notes'+ | 'users'+ | 'relationships'+ | 'usage'+ | 'spend'+ | 'opportunities'+ | 'event_stream'export const ACCOUNT_EXPANSION_TABS: AccountExpansionTab[] = ['notes',@@ -12,6 +19,7 @@ export const ACCOUNT_EXPANSION_TABS: AccountExpansionTab[] = ['usage','spend','opportunities',+ 'event_stream',]export const DEFAULT_ACCOUNT_TAB: AccountExpansionTab = 'notes'diff --git a/products/customer_analytics/frontend/components/Accounts/constants.ts b/products/customer_analytics/frontend/components/Accounts/constants.tsindex a52ce8f58c1a..a65f0ad2fa68 100644--- a/products/customer_analytics/frontend/components/Accounts/constants.ts+++ b/products/customer_analytics/frontend/components/Accounts/constants.ts@@ -50,6 +50,9 @@ export const AccountsEvents = {UsageSeriesToggled: 'customer analytics account usage series toggled',RelatedUserClicked: 'customer analytics account related user clicked',OpportunityClicked: 'customer analytics account opportunity clicked',+ EventStreamMembershipToggled: 'customer analytics account event stream toggled',+ EventStreamConfigSaved: 'customer analytics event stream config saved',+ EventStreamTestMessageSent: 'customer analytics event stream test message sent',NotesTabViewed: 'customer analytics notes tab viewed',NotesTabSearched: 'customer analytics notes tab searched',NotesTabFiltered: 'customer analytics notes tab filtered',diff --git a/products/customer_analytics/frontend/components/EventStream/AccountEventStreamToggle.tsx b/products/customer_analytics/frontend/components/EventStream/AccountEventStreamToggle.tsxnew file mode 100644index 000000000000..47e6db2bbaae--- /dev/null+++ b/products/customer_analytics/frontend/components/EventStream/AccountEventStreamToggle.tsx@@ -0,0 +1,60 @@+import { useActions, useValues } from 'kea'++import { IconGear } from '@posthog/icons'+import { LemonButton, LemonSwitch } from '@posthog/lemon-ui'++import { urls } from 'scenes/urls'++import { eventStreamLogic } from './eventStreamLogic'++// Rendered as flag-gated tab content (AccountNotebooksExpansion), so eventStreamLogic+// only mounts — and only fires its load — when the tab is actually opened.+export function AccountEventStreamToggle({+ accountId,+ externalId,+}: {+ accountId: string+ externalId: string+}): JSX.Element {+ const { eventStream, eventStreamLoading, membershipUpdatingIds, isAccountInStream } = useValues(eventStreamLogic)+ const { setAccountMembership } = useActions(eventStreamLogic)++ const included = isAccountInStream(accountId)+ const updating = membershipUpdatingIds.includes(accountId)++ return (+ <div className="flex flex-col gap-2 items-start">+ <div className="flex items-center gap-1">+ <h4 className="secondary uppercase text-secondary mb-0">Event stream</h4>+ <LemonButton+ size="xsmall"+ type="tertiary"+ icon={<IconGear />}+ tooltip="Configure the event stream"+ data-attr="configure-event-stream"+ to={urls.customerAnalyticsConfiguration('customer-analytics-event-stream')}+ />+ </div>+ <p className="mb-0 text-secondary">Stream this customer's events to your Slack channel in real time.</p>+ <LemonSwitch+ checked={included}+ onChange={(checked) => setAccountMembership(accountId, checked)}+ disabledReason={+ !eventStream && !eventStreamLoading+ ? 'Set up your event stream in settings first'+ : eventStreamLoading || updating+ ? 'Updating…'+ : undefined+ }+ label="Include in my event stream"+ size="small"+ bordered+ />+ {included && !externalId ? (+ <span className="text-xs text-secondary">+ This account has no external ID, so its events can't be matched and won't stream.+ </span>+ ) : null}+ </div>+ )+}diff --git a/products/customer_analytics/frontend/components/EventStream/CustomerAnalyticsEventStream.tsx b/products/customer_analytics/frontend/components/EventStream/CustomerAnalyticsEventStream.tsxnew file mode 100644index 000000000000..2e1742833073--- /dev/null+++ b/products/customer_analytics/frontend/components/EventStream/CustomerAnalyticsEventStream.tsx@@ -0,0 +1,150 @@+import { useActions, useValues } from 'kea'++import { IconPlus } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonSelect, LemonSkeleton, LemonSwitch, Link } from '@posthog/lemon-ui'++import { EventSelect } from 'lib/components/EventSelect/EventSelect'+import { SlackChannelPicker } from 'lib/integrations/SlackIntegrationHelpers'+import { urls } from 'scenes/urls'++import { eventStreamLogic } from './eventStreamLogic'++function ConnectSlackPrompt(): JSX.Element {+ return (+ <LemonBanner type="info">+ <Link to={urls.settings('environment-integrations', 'integration-slack')}>Connect a Slack workspace</Link>{' '}+ to deliver the event stream to a channel.+ </LemonBanner>+ )+}++export function CustomerAnalyticsEventStream(): JSX.Element {+ const {+ eventStream,+ eventStreamLoading,+ draft,+ hasChanges,+ testMessageLoading,+ isInitialLoading,+ integrations,+ selectedIntegration,+ slackChannelValue,+ memberCount,+ testMessageDisabledReason,+ } = useValues(eventStreamLogic)+ const { setDraft, resetDraft, saveEventStream, sendTestMessage, setSlackIntegration, setSlackChannel } =+ useActions(eventStreamLogic)++ if (isInitialLoading) {+ return <LemonSkeleton className="h-20 w-full" />+ }++ return (+ <div className="flex flex-col gap-4">+ <p className="mb-0">+ Stream the events of selected customers to a Slack channel of your choice in real time. This is your+ personal stream — each team member configures their own. Choose which events to watch here, then add+ customers to the stream from their account profiles.+ </p>++ <div className="flex flex-col gap-2">+ <h4 className="secondary uppercase text-secondary mb-0">Events to stream</h4>+ <EventSelect+ onChange={(names) => setDraft({ event_names: names })}+ selectedEvents={draft.event_names}+ addElement={+ <LemonButton size="small" type="secondary" icon={<IconPlus />}>+ Add event+ </LemonButton>+ }+ />+ </div>++ <div className="flex flex-col gap-2">+ <h4 className="secondary uppercase text-secondary mb-0">Slack delivery</h4>+ {integrations.length === 0 ? (+ <ConnectSlackPrompt />+ ) : (+ <div className="flex flex-col gap-2 max-w-160">+ {integrations.length > 1 && (+ <LemonSelect+ value={selectedIntegration?.id ?? null}+ placeholder="Select a Slack workspace"+ options={integrations.map((integration) => ({+ value: integration.id,+ label: integration.display_name,+ }))}+ onChange={setSlackIntegration}+ />+ )}+ {selectedIntegration && (+ <SlackChannelPicker+ integration={selectedIntegration}+ value={slackChannelValue}+ onChange={setSlackChannel}+ />+ )}+ <div>+ <LemonButton+ type="secondary"+ size="small"+ onClick={sendTestMessage}+ loading={testMessageLoading}+ disabledReason={testMessageDisabledReason}+ data-attr="event-stream-send-test-message"+ >+ Send test message+ </LemonButton>+ </div>+ </div>+ )}+ </div>++ <div className="flex flex-col gap-2">+ <h4 className="secondary uppercase text-secondary mb-0">Customers in your stream</h4>+ <p className="mb-0 text-secondary">+ {memberCount === 0+ ? 'No customers yet — open an account in '+ : `${memberCount} ${memberCount === 1 ? 'customer' : 'customers'} in your stream. Manage them from `}+ <Link to={urls.customerAnalyticsAccounts()}>the accounts list</Link> and use the "Include in event+ stream" toggle on the account's profile.+ </p>+ </div>++ <LemonSwitch+ checked={draft.enabled}+ onChange={(enabled) => setDraft({ enabled })}+ label="Enable event stream"+ bordered+ />+ {eventStream?.enabled &&+ (!eventStream.event_names?.length || !eventStream.slack_channel_id || memberCount === 0) && (+ <LemonBanner type="warning">+ The stream is enabled but won't deliver anything yet — it still needs+ {!eventStream.event_names?.length ? ' at least one event,' : ''}+ {!eventStream.slack_channel_id ? ' a Slack channel,' : ''}+ {memberCount === 0 ? ' at least one customer,' : ''} before events start flowing.+ </LemonBanner>+ )}++ <div className="flex flex-row gap-2 pt-2">+ <LemonButton+ type="secondary"+ onClick={resetDraft}+ disabledReason={hasChanges ? undefined : 'No changes'}+ >+ Clear changes+ </LemonButton>+ <LemonButton+ data-attr="save-customer-analytics-event-stream"+ type="primary"+ onClick={saveEventStream}+ loading={eventStreamLoading}+ disabledReason={hasChanges ? undefined : 'No changes'}+ >+ Save+ </LemonButton>+ </div>+ </div>+ )+}diff --git a/products/customer_analytics/frontend/components/EventStream/eventStreamLogic.ts b/products/customer_analytics/frontend/components/EventStream/eventStreamLogic.tsnew file mode 100644index 000000000000..cb62cba78ff4--- /dev/null+++ b/products/customer_analytics/frontend/components/EventStream/eventStreamLogic.ts@@ -0,0 +1,365 @@+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'++import { integrationsLogic } from 'lib/integrations/integrationsLogic'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { objectsEqual } from 'lib/utils/objects'+import { teamLogic } from 'scenes/teamLogic'++import type { IntegrationType } from '~/types'++import {+ eventStreamsAddAccountCreate,+ eventStreamsCreate,+ eventStreamsList,+ eventStreamsPartialUpdate,+ eventStreamsRemoveAccountCreate,+ eventStreamsSendTestMessageCreate,+} from 'products/customer_analytics/frontend/generated/api'+import type {+ EventStreamApi,+ EventStreamTestMessageApi,+ PatchedEventStreamApi,+} from 'products/customer_analytics/frontend/generated/api.schemas'++import { AccountsEvents } from '../Accounts/constants'++/** Locally staged edits to the stream config, applied on Save. */+export interface EventStreamDraft {+ enabled: boolean+ event_names: string[]+ slack_integration: number | null+ slack_channel_id: string+ slack_channel_name: string+}++function draftFromStream(stream: EventStreamApi | null): EventStreamDraft {+ return {+ enabled: stream?.enabled ?? false,+ event_names: stream?.event_names ?? [],+ slack_integration: stream?.slack_integration ?? null,+ slack_channel_id: stream?.slack_channel_id ?? '',+ slack_channel_name: stream?.slack_channel_name ?? '',+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface eventStreamLogicValues {+ integrationsLoading: boolean // integrationsLogic+ slackIntegrations: IntegrationType[] | undefined // integrationsLogic+ currentTeamId: number | null // teamLogic+ draft: EventStreamDraft+ eventStream: EventStreamApi | null+ eventStreamLoading: boolean+ hasChanges: boolean+ integrations: IntegrationType[]+ isAccountInStream: (accountId: string) => boolean+ isInitialLoading: boolean+ memberCount: number+ membershipUpdatingIds: string[]+ selectedIntegration: IntegrationType | null+ slackChannelValue: string | undefined+ testMessage: EventStreamTestMessageApi | null+ testMessageDisabledReason: string | undefined+ testMessageLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface eventStreamLogicActions {+ loadEventStream: () => any+ loadEventStreamFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadEventStreamSuccess: (+ eventStream: EventStreamApi | null,+ payload?: any+ ) => {+ eventStream: EventStreamApi | null+ payload?: any+ }+ membershipUpdateFinished: (accountId: string) => {+ accountId: string+ }+ membershipUpdateStarted: (accountId: string) => {+ accountId: string+ }+ resetDraft: () => {+ value: true+ }+ saveEventStream: () => any+ saveEventStreamFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ saveEventStreamSuccess: (+ eventStream: EventStreamApi | null,+ payload?: any+ ) => {+ eventStream: EventStreamApi | null+ payload?: any+ }+ sendTestMessage: () => any+ sendTestMessageFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ sendTestMessageSuccess: (+ testMessage: EventStreamTestMessageApi | null,+ payload?: any+ ) => {+ testMessage: EventStreamTestMessageApi | null+ payload?: any+ }+ setAccountMembership: (+ accountId: string,+ included: boolean+ ) => {+ accountId: string+ included: boolean+ }+ setDraft: (draft: Partial<EventStreamDraft>) => {+ draft: Partial<EventStreamDraft>+ }+ setSlackChannel: (value: string | null) => {+ value: string | null+ }+ setSlackIntegration: (integrationId: number | null) => {+ integrationId: number | null+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface eventStreamLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ hasChanges: (draft: EventStreamDraft, eventStream: EventStreamApi | null) => boolean+ isAccountInStream: (eventStream: EventStreamApi | null) => (accountId: string) => boolean+ isInitialLoading: (+ integrationsLoading: boolean,+ slackIntegrations: IntegrationType[] | undefined,+ eventStreamLoading: boolean,+ eventStream: EventStreamApi | null+ ) => boolean+ integrations: (slackIntegrations: IntegrationType[] | undefined) => IntegrationType[]+ selectedIntegration: (integrations: IntegrationType[], draft: EventStreamDraft) => IntegrationType | null+ slackChannelValue: (draft: EventStreamDraft) => string | undefined+ memberCount: (eventStream: EventStreamApi | null) => number+ testMessageDisabledReason: (eventStream: EventStreamApi | null, hasChanges: boolean) => string | undefined+ }+}++export type eventStreamLogicType = MakeLogicType<+ eventStreamLogicValues,+ eventStreamLogicActions,+ Record<string, any>,+ eventStreamLogicMeta+>++export const eventStreamLogic = kea<eventStreamLogicType>([+ path(['products', 'customerAnalytics', 'eventStream', 'eventStreamLogic']),+ connect(() => ({+ values: [teamLogic, ['currentTeamId'], integrationsLogic, ['slackIntegrations', 'integrationsLoading']],+ })),+ actions({+ setDraft: (draft: Partial<EventStreamDraft>) => ({ draft }),+ resetDraft: true,+ setSlackIntegration: (integrationId: number | null) => ({ integrationId }),+ setSlackChannel: (value: string | null) => ({ value }),+ setAccountMembership: (accountId: string, included: boolean) => ({ accountId, included }),+ membershipUpdateStarted: (accountId: string) => ({ accountId }),+ membershipUpdateFinished: (accountId: string) => ({ accountId }),+ }),+ loaders(({ values }) => ({+ eventStream: [+ null as EventStreamApi | null,+ {+ loadEventStream: async (): Promise<EventStreamApi | null> => {+ // At most one stream exists per team, so the list is the 0-or-1 streams.+ const streams = await eventStreamsList(String(values.currentTeamId))+ return streams[0] ?? null+ },+ // Creates the team's stream on first save, updates it afterwards.+ saveEventStream: async (): Promise<EventStreamApi | null> => {+ const projectId = String(values.currentTeamId)+ const current = values.eventStream+ const patch: PatchedEventStreamApi = { ...values.draft }+ return current+ ? await eventStreamsPartialUpdate(projectId, current.id, patch)+ : await eventStreamsCreate(projectId, patch as EventStreamApi)+ },+ },+ ],+ testMessage: [+ null as EventStreamTestMessageApi | null,+ {+ sendTestMessage: async (): Promise<EventStreamTestMessageApi | null> => {+ const stream = values.eventStream+ if (!stream?.id) {+ return null+ }+ return await eventStreamsSendTestMessageCreate(String(values.currentTeamId), stream.id)+ },+ },+ ],+ })),+ reducers({+ draft: [+ draftFromStream(null),+ {+ setDraft: (state, { draft }) => ({ ...state, ...draft }),+ loadEventStreamSuccess: (_, { eventStream }) => draftFromStream(eventStream),+ saveEventStreamSuccess: (_, { eventStream }) => draftFromStream(eventStream),+ },+ ],+ membershipUpdatingIds: [+ [] as string[],+ {+ membershipUpdateStarted: (state, { accountId }) => [...state, accountId],+ membershipUpdateFinished: (state, { accountId }) => state.filter((id) => id !== accountId),+ },+ ],+ }),+ selectors({+ hasChanges: [+ (s) => [s.draft, s.eventStream],+ (draft: EventStreamDraft, eventStream: EventStreamApi | null): boolean =>+ !objectsEqual(draft, draftFromStream(eventStream)),+ ],+ isAccountInStream: [+ (s) => [s.eventStream],+ (eventStream: EventStreamApi | null) =>+ (accountId: string): boolean =>+ !!eventStream?.account_ids?.includes(accountId),+ ],+ isInitialLoading: [+ (s) => [s.integrationsLoading, s.slackIntegrations, s.eventStreamLoading, s.eventStream],+ (+ integrationsLoading: boolean,+ slackIntegrations: IntegrationType[] | undefined,+ eventStreamLoading: boolean,+ eventStream: EventStreamApi | null+ ): boolean =>+ (integrationsLoading && slackIntegrations === undefined) ||+ (eventStreamLoading && eventStream === null),+ ],+ integrations: [+ (s) => [s.slackIntegrations],+ (slackIntegrations: IntegrationType[] | undefined): IntegrationType[] => slackIntegrations ?? [],+ ],+ selectedIntegration: [+ (s) => [s.integrations, s.draft],+ (integrations: IntegrationType[], draft: EventStreamDraft): IntegrationType | null =>+ integrations.find((integration) => integration.id === draft.slack_integration) ??+ (integrations.length === 1 ? integrations[0] : null),+ ],+ slackChannelValue: [+ (s) => [s.draft],+ (draft: EventStreamDraft): string | undefined =>+ draft.slack_channel_id ? `${draft.slack_channel_id}|${draft.slack_channel_name || ''}` : undefined,+ ],+ memberCount: [+ (s) => [s.eventStream],+ (eventStream: EventStreamApi | null): number => eventStream?.account_ids?.length ?? 0,+ ],+ testMessageDisabledReason: [+ (s) => [s.eventStream, s.hasChanges],+ (eventStream: EventStreamApi | null, hasChanges: boolean): string | undefined =>+ !eventStream?.slack_integration+ ? 'Save a Slack workspace and channel first'+ : !eventStream?.slack_channel_id+ ? 'Save a Slack channel first'+ : hasChanges+ ? 'Save your changes first — the test uses the saved configuration'+ : undefined,+ ],+ }),+ listeners(({ actions, values }) => ({+ resetDraft: () => {+ actions.setDraft(draftFromStream(values.eventStream))+ },+ setSlackIntegration: ({ integrationId }) => {+ // Switching workspaces clears the channel — it won't exist in the new workspace.+ actions.setDraft({ slack_integration: integrationId, slack_channel_id: '', slack_channel_name: '' })+ },+ setSlackChannel: ({ value }) => {+ const integration = values.selectedIntegration+ if (!integration) {+ return+ }+ const [channelId, ...nameParts] = (value ?? '').split('|')+ actions.setDraft({+ slack_integration: integration.id,+ slack_channel_id: channelId,+ slack_channel_name: nameParts.join('|'),+ })+ },+ saveEventStreamSuccess: ({ eventStream }) => {+ lemonToast.success('Event stream configuration saved')+ posthog.capture(AccountsEvents.EventStreamConfigSaved, {+ enabled: eventStream?.enabled ?? false,+ event_count: eventStream?.event_names?.length ?? 0,+ has_slack_channel: !!eventStream?.slack_channel_id,+ member_count: eventStream?.account_ids?.length ?? 0,+ })+ },+ saveEventStreamFailure: ({ error, errorObject }) => {+ posthog.captureException(errorObject ?? new Error(error), { scope: 'eventStreamLogic.saveEventStream' })+ lemonToast.error('Failed to save the event stream configuration')+ },+ loadEventStreamFailure: ({ error, errorObject }) => {+ posthog.captureException(errorObject ?? new Error(error), { scope: 'eventStreamLogic.loadEventStream' })+ },+ sendTestMessageSuccess: ({ testMessage }) => {+ if (testMessage) {+ const channel = values.eventStream?.slack_channel_name || testMessage.channel_id+ lemonToast.success(`Test message sent to ${channel}`)+ posthog.capture(AccountsEvents.EventStreamTestMessageSent, {+ event_count: values.eventStream?.event_names?.length ?? 0,+ member_count: values.eventStream?.account_ids?.length ?? 0,+ })+ }+ },+ sendTestMessageFailure: ({ error, errorObject }) => {+ posthog.captureException(errorObject ?? new Error(error), { scope: 'eventStreamLogic.sendTestMessage' })+ const detail = (errorObject as { detail?: string } | undefined)?.detail+ lemonToast.error(detail || 'Failed to send the test message')+ },+ setAccountMembership: async ({ accountId, included }) => {+ const stream = values.eventStream+ if (!stream || values.membershipUpdatingIds.includes(accountId)) {+ return+ }+ actions.membershipUpdateStarted(accountId)+ try {+ const projectId = String(values.currentTeamId)+ const updated = included+ ? await eventStreamsAddAccountCreate(projectId, stream.id, { account_id: accountId })+ : await eventStreamsRemoveAccountCreate(projectId, stream.id, { account_id: accountId })+ actions.loadEventStreamSuccess(updated)+ posthog.capture(AccountsEvents.EventStreamMembershipToggled, {+ account_id: accountId,+ included,+ member_count: updated.account_ids?.length ?? 0,+ })+ } catch (error) {+ posthog.captureException(error as Error, { scope: 'eventStreamLogic.setAccountMembership' })+ lemonToast.error('Failed to update the event stream membership')+ } finally {+ actions.membershipUpdateFinished(accountId)+ }+ },+ })),+ afterMount(({ actions }) => {+ actions.loadEventStream()+ }),+])diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex 89d2b36a7d93..2e6c23c7229c 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -1083,6 +1083,96 @@ export interface PatchedCustomerProfileConfigApi {readonly updated_at?: string | null}+/**+ * The caller's event stream — a live feed of selected accounts' events posted to a+ * Slack channel of their choice. One stream per user per project.+ */+export interface EventStreamApi {+ readonly id: string+ /** Whether the stream delivers to Slack. Delivery also requires at least one event, at least one member account with an external ID, and a Slack workspace + channel. */+ enabled?: boolean+ /**+ * Names of the events to stream (matched exactly). Duplicates and blanks are dropped.+ * @items.maxLength 400+ */+ event_names?: string[]+ /**+ * ID of the team's Slack workspace integration to deliver through.+ * @nullable+ */+ slack_integration?: number | null+ /**+ * Slack channel ID to post to (e.g. C0123ABC).+ * @maxLength 200+ */+ slack_channel_id?: string+ /**+ * Display name of the Slack channel (e.g. #customer-events). Informational only.+ * @maxLength 200+ */+ slack_channel_name?: string+ /** UUIDs of the member accounts whose users' events are streamed. Managed via the add_account/remove_account endpoints. */+ readonly account_ids: readonly string[]+ readonly created_at: string+ /** @nullable */+ readonly created_by: number | null+ /** @nullable */+ readonly updated_at: string | null+}++/**+ * The caller's event stream — a live feed of selected accounts' events posted to a+ * Slack channel of their choice. One stream per user per project.+ */+export interface PatchedEventStreamApi {+ readonly id?: string+ /** Whether the stream delivers to Slack. Delivery also requires at least one event, at least one member account with an external ID, and a Slack workspace + channel. */+ enabled?: boolean+ /**+ * Names of the events to stream (matched exactly). Duplicates and blanks are dropped.+ * @items.maxLength 400+ */+ event_names?: string[]+ /**+ * ID of the team's Slack workspace integration to deliver through.+ * @nullable+ */+ slack_integration?: number | null+ /**+ * Slack channel ID to post to (e.g. C0123ABC).+ * @maxLength 200+ */+ slack_channel_id?: string+ /**+ * Display name of the Slack channel (e.g. #customer-events). Informational only.+ * @maxLength 200+ */+ slack_channel_name?: string+ /** UUIDs of the member accounts whose users' events are streamed. Managed via the add_account/remove_account endpoints. */+ readonly account_ids?: readonly string[]+ readonly created_at?: string+ /** @nullable */+ readonly created_by?: number | null+ /** @nullable */+ readonly updated_at?: string | null+}++/**+ * Request body for adding or removing an event-stream member account.+ */+export interface EventStreamMemberWriteApi {+ /** UUID of the account to add to or remove from the stream. */+ account_id: string+}++/**+ * Result of posting an event-stream test message to Slack.+ */+export interface EventStreamTestMessageApi {+ /** Slack channel ID the test message was posted to (e.g. C0123ABC). */+ readonly channel_id: string+}+/*** * `numeric` - numeric* * `currency` - currencydiff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.tsindex 222191cee0ba..1d3b6586c4a5 100644--- a/products/customer_analytics/frontend/generated/api.ts+++ b/products/customer_analytics/frontend/generated/api.ts@@ -38,6 +38,9 @@ import type {CustomerJourneysListParams,CustomerProfileConfigApi,CustomerProfileConfigsListParams,+ EventStreamApi,+ EventStreamMemberWriteApi,+ EventStreamTestMessageApi,ExternalAccountListPageApi,GroupUsageMetricApi,GroupsTypesMetricsListParams,@@ -58,6 +61,7 @@ import type {PatchedCustomPropertySourceUpdateApi,PatchedCustomerJourneyApi,PatchedCustomerProfileConfigApi,+ PatchedEventStreamApi,PatchedGroupUsageMetricApi,} from './api.schemas'@@ -1170,6 +1174,188 @@ export const customerProfileConfigsDestroy = async (})}+export const getEventStreamsListUrl = (projectId: string) => {+ return `/api/projects/${projectId}/event_streams/`+}++/**+ * The caller's event stream: a live feed of selected accounts' events posted to a+ * Slack channel of their choice. Per-user — each team member owns at most one stream, and+ * every endpoint is scoped to the caller's own. Delivery runs through a managed CDP+ * destination that is re-provisioned inside the same transaction as every write, so+ * config and delivery can't drift apart.+ */+export const eventStreamsList = async (projectId: string, options?: RequestInit): Promise<EventStreamApi[]> => {+ return apiMutator<EventStreamApi[]>(getEventStreamsListUrl(projectId), {+ ...options,+ method: 'GET',+ })+}++export const getEventStreamsCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/event_streams/`+}++/**+ * The caller's event stream: a live feed of selected accounts' events posted to a+ * Slack channel of their choice. Per-user — each team member owns at most one stream, and+ * every endpoint is scoped to the caller's own. Delivery runs through a managed CDP+ * destination that is re-provisioned inside the same transaction as every write, so+ * config and delivery can't drift apart.+ */+export const eventStreamsCreate = async (+ projectId: string,+ eventStreamApi?: NonReadonly<EventStreamApi>,+ options?: RequestInit+): Promise<EventStreamApi> => {+ return apiMutator<EventStreamApi>(getEventStreamsCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(eventStreamApi),+ })+}++export const getEventStreamsUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/event_streams/${id}/`+}++/**+ * The caller's event stream: a live feed of selected accounts' events posted to a+ * Slack channel of their choice. Per-user — each team member owns at most one stream, and+ * every endpoint is scoped to the caller's own. Delivery runs through a managed CDP+ * destination that is re-provisioned inside the same transaction as every write, so+ * config and delivery can't drift apart.+ */+export const eventStreamsUpdate = async (+ projectId: string,+ id: string,+ eventStreamApi?: NonReadonly<EventStreamApi>,+ options?: RequestInit+): Promise<EventStreamApi> => {+ return apiMutator<EventStreamApi>(getEventStreamsUpdateUrl(projectId, id), {+ ...options,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(eventStreamApi),+ })+}++export const getEventStreamsPartialUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/event_streams/${id}/`+}++/**+ * The caller's event stream: a live feed of selected accounts' events posted to a+ * Slack channel of their choice. Per-user — each team member owns at most one stream, and+ * every endpoint is scoped to the caller's own. Delivery runs through a managed CDP+ * destination that is re-provisioned inside the same transaction as every write, so+ * config and delivery can't drift apart.+ */+export const eventStreamsPartialUpdate = async (+ projectId: string,+ id: string,+ patchedEventStreamApi?: NonReadonly<PatchedEventStreamApi>,+ options?: RequestInit+): Promise<EventStreamApi> => {+ return apiMutator<EventStreamApi>(getEventStreamsPartialUpdateUrl(projectId, id), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedEventStreamApi),+ })+}++export const getEventStreamsDestroyUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/event_streams/${id}/`+}++/**+ * The caller's event stream: a live feed of selected accounts' events posted to a+ * Slack channel of their choice. Per-user — each team member owns at most one stream, and+ * every endpoint is scoped to the caller's own. Delivery runs through a managed CDP+ * destination that is re-provisioned inside the same transaction as every write, so+ * config and delivery can't drift apart.+ */+export const eventStreamsDestroy = async (projectId: string, id: string, options?: RequestInit): Promise<void> => {+ return apiMutator<void>(getEventStreamsDestroyUrl(projectId, id), {+ ...options,+ method: 'DELETE',+ })+}++export const getEventStreamsAddAccountCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/event_streams/${id}/add_account/`+}++/**+ * The caller's event stream: a live feed of selected accounts' events posted to a+ * Slack channel of their choice. Per-user — each team member owns at most one stream, and+ * every endpoint is scoped to the caller's own. Delivery runs through a managed CDP+ * destination that is re-provisioned inside the same transaction as every write, so+ * config and delivery can't drift apart.+ */+export const eventStreamsAddAccountCreate = async (+ projectId: string,+ id: string,+ eventStreamMemberWriteApi: EventStreamMemberWriteApi,+ options?: RequestInit+): Promise<EventStreamApi> => {+ return apiMutator<EventStreamApi>(getEventStreamsAddAccountCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(eventStreamMemberWriteApi),+ })+}++export const getEventStreamsRemoveAccountCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/event_streams/${id}/remove_account/`+}++/**+ * The caller's event stream: a live feed of selected accounts' events posted to a+ * Slack channel of their choice. Per-user — each team member owns at most one stream, and+ * every endpoint is scoped to the caller's own. Delivery runs through a managed CDP+ * destination that is re-provisioned inside the same transaction as every write, so+ * config and delivery can't drift apart.+ */+export const eventStreamsRemoveAccountCreate = async (+ projectId: string,+ id: string,+ eventStreamMemberWriteApi: EventStreamMemberWriteApi,+ options?: RequestInit+): Promise<EventStreamApi> => {+ return apiMutator<EventStreamApi>(getEventStreamsRemoveAccountCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(eventStreamMemberWriteApi),+ })+}++export const getEventStreamsSendTestMessageCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/event_streams/${id}/send_test_message/`+}++/**+ * The caller's event stream: a live feed of selected accounts' events posted to a+ * Slack channel of their choice. Per-user — each team member owns at most one stream, and+ * every endpoint is scoped to the caller's own. Delivery runs through a managed CDP+ * destination that is re-provisioned inside the same transaction as every write, so+ * config and delivery can't drift apart.+ */+export const eventStreamsSendTestMessageCreate = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<EventStreamTestMessageApi> => {+ return apiMutator<EventStreamTestMessageApi>(getEventStreamsSendTestMessageCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}+export const getGroupsTypesMetricsListUrl = (projectId: string,groupTypeIndex: number,diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.tsindex 2b928f104784..15453ebbe51b 100644--- a/products/customer_analytics/frontend/generated/api.zod.ts+++ b/products/customer_analytics/frontend/generated/api.zod.ts@@ -713,6 +713,173 @@ export const CustomerProfileConfigsPartialUpdateBody = /* @__PURE__ */ zod.objecsidebar: zod.unknown().optional(),})+/**+ * The caller's event stream: a live feed of selected accounts' events posted to a+ * Slack channel of their choice. Per-user — each team member owns at most one stream, and+ * every endpoint is scoped to the caller's own. Delivery runs through a managed CDP+ * destination that is re-provisioned inside the same transaction as every write, so+ * config and delivery can't drift apart.+ */+export const eventStreamsCreateBodyEnabledDefault = false+export const eventStreamsCreateBodyEventNamesItemMax = 400++export const eventStreamsCreateBodySlackChannelIdDefault = ``+export const eventStreamsCreateBodySlackChannelIdMax = 200++export const eventStreamsCreateBodySlackChannelNameDefault = ``+export const eventStreamsCreateBodySlackChannelNameMax = 200++export const EventStreamsCreateBody = /* @__PURE__ */ zod+ .object({+ enabled: zod+ .boolean()+ .default(eventStreamsCreateBodyEnabledDefault)+ .describe(+ 'Whether the stream delivers to Slack. Delivery also requires at least one event, at least one member account with an external ID, and a Slack workspace + channel.'+ ),+ event_names: zod+ .array(zod.string().max(eventStreamsCreateBodyEventNamesItemMax))+ .optional()+ .describe('Names of the events to stream (matched exactly). Duplicates and blanks are dropped.'),+ slack_integration: zod+ .number()+ .nullish()+ .describe("ID of the team's Slack workspace integration to deliver through."),+ slack_channel_id: zod+ .string()+ .max(eventStreamsCreateBodySlackChannelIdMax)+ .default(eventStreamsCreateBodySlackChannelIdDefault)+ .describe('Slack channel ID to post to (e.g. C0123ABC).'),+ slack_channel_name: zod+ .string()+ .max(eventStreamsCreateBodySlackChannelNameMax)+ .default(eventStreamsCreateBodySlackChannelNameDefault)+ .describe('Display name of the Slack channel (e.g. #customer-events). Informational only.'),+ })+ .describe(+ "The caller's event stream — a live feed of selected accounts' events posted to a\nSlack channel of their choice. One stream per user per project."+ )++/**+ * The caller's event stream: a live feed of selected accounts' events posted to a+ * Slack channel of their choice. Per-user — each team member owns at most one stream, and+ * every endpoint is scoped to the caller's own. Delivery runs through a managed CDP+ * destination that is re-provisioned inside the same transaction as every write, so+ * config and delivery can't drift apart.+ */+export const eventStreamsUpdateBodyEnabledDefault = false+export const eventStreamsUpdateBodyEventNamesItemMax = 400++export const eventStreamsUpdateBodySlackChannelIdDefault = ``+export const eventStreamsUpdateBodySlackChannelIdMax = 200++export const eventStreamsUpdateBodySlackChannelNameDefault = ``+export const eventStreamsUpdateBodySlackChannelNameMax = 200++export const EventStreamsUpdateBody = /* @__PURE__ */ zod+ .object({+ enabled: zod+ .boolean()+ .default(eventStreamsUpdateBodyEnabledDefault)+ .describe(+ 'Whether the stream delivers to Slack. Delivery also requires at least one event, at least one member account with an external ID, and a Slack workspace + channel.'+ ),+ event_names: zod+ .array(zod.string().max(eventStreamsUpdateBodyEventNamesItemMax))+ .optional()+ .describe('Names of the events to stream (matched exactly). Duplicates and blanks are dropped.'),+ slack_integration: zod+ .number()+ .nullish()+ .describe("ID of the team's Slack workspace integration to deliver through."),+ slack_channel_id: zod+ .string()+ .max(eventStreamsUpdateBodySlackChannelIdMax)+ .default(eventStreamsUpdateBodySlackChannelIdDefault)+ .describe('Slack channel ID to post to (e.g. C0123ABC).'),+ slack_channel_name: zod+ .string()+ .max(eventStreamsUpdateBodySlackChannelNameMax)+ .default(eventStreamsUpdateBodySlackChannelNameDefault)+ .describe('Display name of the Slack channel (e.g. #customer-events). Informational only.'),+ })+ .describe(+ "The caller's event stream — a live feed of selected accounts' events posted to a\nSlack channel of their choice. One stream per user per project."+ )++/**+ * The caller's event stream: a live feed of selected accounts' events posted to a+ * Slack channel of their choice. Per-user — each team member owns at most one stream, and+ * every endpoint is scoped to the caller's own. Delivery runs through a managed CDP+ * destination that is re-provisioned inside the same transaction as every write, so+ * config and delivery can't drift apart.+ */+export const eventStreamsPartialUpdateBodyEnabledDefault = false+export const eventStreamsPartialUpdateBodyEventNamesItemMax = 400++export const eventStreamsPartialUpdateBodySlackChannelIdDefault = ``+export const eventStreamsPartialUpdateBodySlackChannelIdMax = 200++export const eventStreamsPartialUpdateBodySlackChannelNameDefault = ``+export const eventStreamsPartialUpdateBodySlackChannelNameMax = 200++export const EventStreamsPartialUpdateBody = /* @__PURE__ */ zod+ .object({+ enabled: zod+ .boolean()+ .default(eventStreamsPartialUpdateBodyEnabledDefault)+ .describe(+ 'Whether the stream delivers to Slack. Delivery also requires at least one event, at least one member account with an external ID, and a Slack workspace + channel.'+ ),+ event_names: zod+ .array(zod.string().max(eventStreamsPartialUpdateBodyEventNamesItemMax))+ .optional()+ .describe('Names of the events to stream (matched exactly). Duplicates and blanks are dropped.'),+ slack_integration: zod+ .number()+ .nullish()+ .describe("ID of the team's Slack workspace integration to deliver through."),+ slack_channel_id: zod+ .string()+ .max(eventStreamsPartialUpdateBodySlackChannelIdMax)+ .default(eventStreamsPartialUpdateBodySlackChannelIdDefault)+ .describe('Slack channel ID to post to (e.g. C0123ABC).'),+ slack_channel_name: zod+ .string()+ .max(eventStreamsPartialUpdateBodySlackChannelNameMax)+ .default(eventStreamsPartialUpdateBodySlackChannelNameDefault)+ .describe('Display name of the Slack channel (e.g. #customer-events). Informational only.'),+ })+ .describe(+ "The caller's event stream — a live feed of selected accounts' events posted to a\nSlack channel of their choice. One stream per user per project."+ )++/**+ * The caller's event stream: a live feed of selected accounts' events posted to a+ * Slack channel of their choice. Per-user — each team member owns at most one stream, and+ * every endpoint is scoped to the caller's own. Delivery runs through a managed CDP+ * destination that is re-provisioned inside the same transaction as every write, so+ * config and delivery can't drift apart.+ */+export const EventStreamsAddAccountCreateBody = /* @__PURE__ */ zod+ .object({+ account_id: zod.uuid().describe('UUID of the account to add to or remove from the stream.'),+ })+ .describe('Request body for adding or removing an event-stream member account.')++/**+ * The caller's event stream: a live feed of selected accounts' events posted to a+ * Slack channel of their choice. Per-user — each team member owns at most one stream, and+ * every endpoint is scoped to the caller's own. Delivery runs through a managed CDP+ * destination that is re-provisioned inside the same transaction as every write, so+ * config and delivery can't drift apart.+ */+export const EventStreamsRemoveAccountCreateBody = /* @__PURE__ */ zod+ .object({+ account_id: zod.uuid().describe('UUID of the account to add to or remove from the stream.'),+ })+ .describe('Request body for adding or removing an event-stream member account.')+export const groupsTypesMetricsCreateBodyNameMax = 255export const groupsTypesMetricsCreateBodyFormatDefault = `numeric`diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/customerAnalyticsConfigurationSceneLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/customerAnalyticsConfigurationSceneLogic.tsindex 3975fd326c1b..48f3525c932a 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/customerAnalyticsConfigurationSceneLogic.ts+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/customerAnalyticsConfigurationSceneLogic.ts@@ -15,6 +15,7 @@ export type ConfigurationSceneTabType =| 'customer-analytics-usage-metrics'| 'customer-analytics-dashboard-events'| 'customer-analytics-accounts'+ | 'customer-analytics-event-stream'export interface CustomerAnalyticsConfigurationSceneLogicProps {initialTab?: ConfigurationSceneTabTypediff --git a/products/customer_analytics/manifest.tsx b/products/customer_analytics/manifest.tsxindex 913475ae27e9..e46abacda701 100644--- a/products/customer_analytics/manifest.tsx+++ b/products/customer_analytics/manifest.tsx@@ -67,7 +67,8 @@ export const manifest: ProductManifest = {customerAnalyticsNotes: (): string => '/customer_analytics/notes',customerAnalyticsAnnouncements: (): string => '/customer_analytics/announcements',customerAnalyticsJourneys: (): string => '/customer_analytics/journeys',- customerAnalyticsConfiguration: (): string => '/customer_analytics/configuration',+ customerAnalyticsConfiguration: (tab?: string): string =>+ `/customer_analytics/configuration${tab ? `?tab=${tab}` : ''}`,customerJourneyBuilder: (): string => '/customer_analytics/journeys/new',customerJourneyTemplates: (): string => '/customer_analytics/journeys/templates',customerJourneyEdit: (id: string): string => `/customer_analytics/journeys/${id}/edit`,diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yamlindex a9f21c152787..8b2341b07e34 100644--- a/products/customer_analytics/mcp/tools.yaml+++ b/products/customer_analytics/mcp/tools.yaml@@ -653,6 +653,116 @@ tools:customer-profile-configs-update:operation: customer_profile_configs_updateenabled: false+ event-streams-add-account:+ operation: event_streams_add_account_create+ enabled: true+ scopes:+ - account:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ title: Add account to my event stream+ description: >+ Add a Customer Analytics account to the caller's event stream so its users' matching events start posting to+ their Slack channel. Provide the stream `id` and the `account_id` to add. Idempotent — adding an account+ that is already in the stream is a no-op. Only accounts with an `external_id` actually deliver (the+ external_id is how events are matched to the account).+ feature_flag: customer-analytics-csp+ event-streams-create:+ operation: event_streams_create+ enabled: true+ scopes:+ - account:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Create my event stream+ description: >+ Create the caller's personal Customer Analytics event stream — a live feed of selected accounts' events+ posted to a Slack channel of their choice. Each user has at most one stream per project (409 if one already+ exists; use event-streams-list first). Provide `event_names` to watch, and optionally `slack_integration` ++ `slack_channel_id` for delivery — the stream only delivers once events, a Slack channel, and at least one+ member account are all configured and `enabled` is true.+ feature_flag: customer-analytics-csp+ event-streams-destroy:+ operation: event_streams_destroy+ enabled: true+ scopes:+ - account:write+ annotations:+ readOnly: false+ destructive: true+ idempotent: true+ title: Delete my event stream+ description: >+ Delete the caller's event stream and its account memberships, and stop its Slack delivery. Only the caller's+ own stream can be deleted.+ feature_flag: customer-analytics-csp+ event-streams-list:+ operation: event_streams_list+ enabled: true+ scopes:+ - account:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Get my event stream+ description: >+ The caller's Customer Analytics event stream, as a 0-or-1 element array — each user has at most one stream+ per project. Returns its `id` (needed by the other event-stream tools), enabled state, watched+ `event_names`, Slack delivery target, and member `account_ids`.+ feature_flag: customer-analytics-csp+ event-streams-partial-update:+ operation: event_streams_partial_update+ enabled: true+ scopes:+ - account:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ title: Update my event stream+ description: >+ Update the caller's event stream configuration — `enabled`, watched `event_names`, or the Slack delivery+ target (`slack_integration`, `slack_channel_id`, `slack_channel_name`). Omitted fields are left unchanged.+ Manage member accounts via the add/remove account tools, not here.+ feature_flag: customer-analytics-csp+ event-streams-remove-account:+ operation: event_streams_remove_account_create+ enabled: true+ scopes:+ - account:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ title: Remove account from my event stream+ description: >+ Remove a Customer Analytics account from the caller's event stream so its events stop posting to their Slack+ channel. Provide the stream `id` and the `account_id` to remove. Idempotent — removing an account that is+ not in the stream is a no-op.+ feature_flag: customer-analytics-csp+ event-streams-send-test-message:+ operation: event_streams_send_test_message_create+ enabled: true+ scopes:+ - account:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Send event stream test message+ description: >+ Post a test message to the Slack channel configured on the caller's event stream, to verify delivery works+ end to end. Fails with a validation error when the stream has no saved Slack workspace + channel, or when+ Slack rejects the message (e.g. the PostHog bot is not in the channel).+ feature_flag: customer-analytics-csp+ event-streams-update:+ operation: event_streams_update+ enabled: falseusage-metrics-create:operation: groups_types_metrics_createenabled: truediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex bd0d50bc81e4..8a69255cf61b 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -3616,6 +3616,111 @@"readOnlyHint": true}},+ "event-streams-add-account": {+ "description": "Add a Customer Analytics account to the caller's event stream so its users' matching events start posting to their Slack channel. Provide the stream `id` and the `account_id` to add. Idempotent — adding an account that is already in the stream is a no-op. Only accounts with an `external_id` actually deliver (the external_id is how events are matched to the account).",+ "category": "Customer analytics",+ "feature": "customer_analytics",+ "summary": "Add account to my event stream",+ "title": "Add account to my event stream",+ "required_scopes": ["account:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "customer-analytics-csp"+ },+ "event-streams-create": {+ "description": "Create the caller's personal Customer Analytics event stream — a live feed of selected accounts' events posted to a Slack channel of their choice. Each user has at most one stream per project (409 if one already exists; use event-streams-list first). Provide `event_names` to watch, and optionally `slack_integration` + `slack_channel_id` for delivery — the stream only delivers once events, a Slack channel, and at least one member account are all configured and `enabled` is true.",+ "category": "Customer analytics",+ "feature": "customer_analytics",+ "summary": "Create my event stream",+ "title": "Create my event stream",+ "required_scopes": ["account:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "customer-analytics-csp"+ },+ "event-streams-destroy": {+ "description": "Delete the caller's event stream and its account memberships, and stop its Slack delivery. Only the caller's own stream can be deleted.",+ "category": "Customer analytics",+ "feature": "customer_analytics",+ "summary": "Delete my event stream",+ "title": "Delete my event stream",+ "required_scopes": ["account:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "customer-analytics-csp"+ },+ "event-streams-list": {+ "description": "The caller's Customer Analytics event stream, as a 0-or-1 element array — each user has at most one stream per project. Returns its `id` (needed by the other event-stream tools), enabled state, watched `event_names`, Slack delivery target, and member `account_ids`.",+ "category": "Customer analytics",+ "feature": "customer_analytics",+ "summary": "Get my event stream",+ "title": "Get my event stream",+ "required_scopes": ["account:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "customer-analytics-csp"+ },+ "event-streams-partial-update": {+ "description": "Update the caller's event stream configuration — `enabled`, watched `event_names`, or the Slack delivery target (`slack_integration`, `slack_channel_id`, `slack_channel_name`). Omitted fields are left unchanged. Manage member accounts via the add/remove account tools, not here.",+ "category": "Customer analytics",+ "feature": "customer_analytics",+ "summary": "Update my event stream",+ "title": "Update my event stream",+ "required_scopes": ["account:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "customer-analytics-csp"+ },+ "event-streams-remove-account": {+ "description": "Remove a Customer Analytics account from the caller's event stream so its events stop posting to their Slack channel. Provide the stream `id` and the `account_id` to remove. Idempotent — removing an account that is not in the stream is a no-op.",+ "category": "Customer analytics",+ "feature": "customer_analytics",+ "summary": "Remove account from my event stream",+ "title": "Remove account from my event stream",+ "required_scopes": ["account:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "customer-analytics-csp"+ },+ "event-streams-send-test-message": {+ "description": "Post a test message to the Slack channel configured on the caller's event stream, to verify delivery works end to end. Fails with a validation error when the stream has no saved Slack workspace + channel, or when Slack rejects the message (e.g. the PostHog bot is not in the channel).",+ "category": "Customer analytics",+ "feature": "customer_analytics",+ "summary": "Send event stream test message",+ "title": "Send event stream test message",+ "required_scopes": ["account:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "customer-analytics-csp"+ },"experiment-activity": {"description": "Get the audit trail for a specific experiment by ID. Returns a paginated list of changes to the experiment and its holdouts and shared metrics: who made each change, what was changed (field-level before/after values), and when, newest first. Lifecycle actions (launch, end, ship variant, etc.) appear as updates to the underlying fields (start_date, end_date, conclusion, ...). Use limit and page query params for pagination. Note: changes to the experiment's linked feature flag (rollout, targeting) are logged on the flag itself — use feature-flags-activity-retrieve with the flag's ID for those.","category": "Experiments",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex c52d924ef47e..6dde8ebd93cc 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -3771,6 +3771,111 @@"readOnlyHint": false}},+ "event-streams-add-account": {+ "description": "Add a Customer Analytics account to the caller's event stream so its users' matching events start posting to their Slack channel. Provide the stream `id` and the `account_id` to add. Idempotent — adding an account that is already in the stream is a no-op. Only accounts with an `external_id` actually deliver (the external_id is how events are matched to the account).",+ "category": "Customer analytics",+ "feature": "customer_analytics",+ "summary": "Add account to my event stream",+ "title": "Add account to my event stream",+ "required_scopes": ["account:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "customer-analytics-csp"+ },+ "event-streams-create": {+ "description": "Create the caller's personal Customer Analytics event stream — a live feed of selected accounts' events posted to a Slack channel of their choice. Each user has at most one stream per project (409 if one already exists; use event-streams-list first). Provide `event_names` to watch, and optionally `slack_integration` + `slack_channel_id` for delivery — the stream only delivers once events, a Slack channel, and at least one member account are all configured and `enabled` is true.",+ "category": "Customer analytics",+ "feature": "customer_analytics",+ "summary": "Create my event stream",+ "title": "Create my event stream",+ "required_scopes": ["account:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "customer-analytics-csp"+ },+ "event-streams-destroy": {+ "description": "Delete the caller's event stream and its account memberships, and stop its Slack delivery. Only the caller's own stream can be deleted.",+ "category": "Customer analytics",+ "feature": "customer_analytics",+ "summary": "Delete my event stream",+ "title": "Delete my event stream",+ "required_scopes": ["account:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "customer-analytics-csp"+ },+ "event-streams-list": {+ "description": "The caller's Customer Analytics event stream, as a 0-or-1 element array — each user has at most one stream per project. Returns its `id` (needed by the other event-stream tools), enabled state, watched `event_names`, Slack delivery target, and member `account_ids`.",+ "category": "Customer analytics",+ "feature": "customer_analytics",+ "summary": "Get my event stream",+ "title": "Get my event stream",+ "required_scopes": ["account:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "customer-analytics-csp"+ },+ "event-streams-partial-update": {+ "description": "Update the caller's event stream configuration — `enabled`, watched `event_names`, or the Slack delivery target (`slack_integration`, `slack_channel_id`, `slack_channel_name`). Omitted fields are left unchanged. Manage member accounts via the add/remove account tools, not here.",+ "category": "Customer analytics",+ "feature": "customer_analytics",+ "summary": "Update my event stream",+ "title": "Update my event stream",+ "required_scopes": ["account:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "customer-analytics-csp"+ },+ "event-streams-remove-account": {+ "description": "Remove a Customer Analytics account from the caller's event stream so its events stop posting to their Slack channel. Provide the stream `id` and the `account_id` to remove. Idempotent — removing an account that is not in the stream is a no-op.",+ "category": "Customer analytics",+ "feature": "customer_analytics",+ "summary": "Remove account from my event stream",+ "title": "Remove account from my event stream",+ "required_scopes": ["account:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "customer-analytics-csp"+ },+ "event-streams-send-test-message": {+ "description": "Post a test message to the Slack channel configured on the caller's event stream, to verify delivery works end to end. Fails with a validation error when the stream has no saved Slack workspace + channel, or when Slack rejects the message (e.g. the PostHog bot is not in the channel).",+ "category": "Customer analytics",+ "feature": "customer_analytics",+ "summary": "Send event stream test message",+ "title": "Send event stream test message",+ "required_scopes": ["account:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "customer-analytics-csp"+ },"execute-sql": {"description": "Use this tool to execute an SQL query (or HogQL, which is PostHog's variant of SQL that supports most of ClickHouse SQL). We're going to use terms \"HogQL\" and \"SQL\" interchangeably. For more information, see the querying-posthog-data skill.\nBEFORE writing any query, you should follow these steps:\n1. Discover the available tables, views, columns, and their types before querying. Do NOT guess table or column names.\n2. Call posthog:read-data-schema to discover available events, properties, and property values. Do NOT rely on training data or PostHog defaults.\n3. Only after completing steps 1 and 2, write and execute your SQL query using verified table and column names.\nUse system tables with the system. prefix for PostHog-created data. For example, count SQL insight variables with:\n```sql\nSELECT count() AS total FROM system.insight_variables\n```\nAn example query to retrieve columns of a custom data warehouse table:\n```sql\nSELECT columns FROM system.data_warehouse_tables WHERE name = 'my_table'\n```\nIMPORTANT: By default, large JSON values in results (like full `properties` objects) are truncated. If you anticipate that results might be large or you are selecting the full `properties` object (e.g., `SELECT properties FROM events`), you should dump the results to a file instead of outputting them directly. Use bash commands to process the file. Alternatively, cherry-pick only the specific properties you need (e.g., `properties.$browser`) instead of selecting the entire object.\nPROPERTY ACCESS: dot notation (`properties.$browser`) only works for keys that are valid identifiers — they must start with a letter, underscore, or `$` and contain only letters, digits, underscores, and `$` (`^[A-Za-z_$][A-Za-z0-9_$]*$`). Keys that break this rule (hyphens, dots, spaces, or a leading digit) cannot use dot notation; for example `properties.$survey_response_0196e96d-7705-7d32` is parsed as a subtraction and fails. Use bracket notation with a quoted string for those keys: `properties['$survey_response_0196e96d-7705-7d32']`. This applies to all JSON columns (e.g. `person.properties[...]`).","category": "SQL",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 9006250e303a..268e93098fa5 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -25683,6 +25683,59 @@ export namespace Schemas {readonly updated_at: string;}+ /**+ * The caller's event stream — a live feed of selected accounts' events posted to a+ * Slack channel of their choice. One stream per user per project.+ */+ export interface EventStream {+ readonly id: string;+ /** Whether the stream delivers to Slack. Delivery also requires at least one event, at least one member account with an external ID, and a Slack workspace + channel. */+ enabled?: boolean;+ /**+ * Names of the events to stream (matched exactly). Duplicates and blanks are dropped.+ * @items.maxLength 400+ */+ event_names?: string[];+ /**+ * ID of the team's Slack workspace integration to deliver through.+ * @nullable+ */+ slack_integration?: number | null;+ /**+ * Slack channel ID to post to (e.g. C0123ABC).+ * @maxLength 200+ */+ slack_channel_id?: string;+ /**+ * Display name of the Slack channel (e.g. #customer-events). Informational only.+ * @maxLength 200+ */+ slack_channel_name?: string;+ /** UUIDs of the member accounts whose users' events are streamed. Managed via the add_account/remove_account endpoints. */+ readonly account_ids: readonly string[];+ readonly created_at: string;+ /** @nullable */+ readonly created_by: number | null;+ /** @nullable */+ readonly updated_at: string | null;+ }++ /**+ * Request body for adding or removing an event-stream member account.+ */+ export interface EventStreamMemberWrite {+ /** UUID of the account to add to or remove from the stream. */+ account_id: string;+ }++ /**+ * Result of posting an event-stream test message to Slack.+ */+ export interface EventStreamTestMessage {+ /** Slack channel ID the test message was posted to (e.g. C0123ABC). */+ readonly channel_id: string;+ }+export interface EventSuggestionsResponse {/** Ranked candidate events for conversion goals */candidates: CandidateEvent[];@@ -47999,6 +48052,43 @@ export namespace Schemas {readonly updated_at?: string;}+ /**+ * The caller's event stream — a live feed of selected accounts' events posted to a+ * Slack channel of their choice. One stream per user per project.+ */+ export interface PatchedEventStream {+ readonly id?: string;+ /** Whether the stream delivers to Slack. Delivery also requires at least one event, at least one member account with an external ID, and a Slack workspace + channel. */+ enabled?: boolean;+ /**+ * Names of the events to stream (matched exactly). Duplicates and blanks are dropped.+ * @items.maxLength 400+ */+ event_names?: string[];+ /**+ * ID of the team's Slack workspace integration to deliver through.+ * @nullable+ */+ slack_integration?: number | null;+ /**+ * Slack channel ID to post to (e.g. C0123ABC).+ * @maxLength 200+ */+ slack_channel_id?: string;+ /**+ * Display name of the Slack channel (e.g. #customer-events). Informational only.+ * @maxLength 200+ */+ slack_channel_name?: string;+ /** UUIDs of the member accounts whose users' events are streamed. Managed via the add_account/remove_account endpoints. */+ readonly account_ids?: readonly string[];+ readonly created_at?: string;+ /** @nullable */+ readonly created_by?: number | null;+ /** @nullable */+ readonly updated_at?: string | null;+ }+/*** A holdout group — a stable slice of users excluded from experiment exposure.*/diff --git a/services/mcp/src/generated/customer_analytics/api.ts b/services/mcp/src/generated/customer_analytics/api.tsindex 8294f42bff6b..c4b03ac56574 100644--- a/services/mcp/src/generated/customer_analytics/api.ts+++ b/services/mcp/src/generated/customer_analytics/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 37 enabled ops+ * PostHog API - MCP 44 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -811,6 +811,205 @@ export const CustomPropertySourcesSyncParams = /* @__PURE__ */ zod.object({),})+/**+ * The caller's event stream: a live feed of selected accounts' events posted to a+ * Slack channel of their choice. Per-user — each team member owns at most one stream, and+ * every endpoint is scoped to the caller's own. Delivery runs through a managed CDP+ * destination that is re-provisioned inside the same transaction as every write, so+ * config and delivery can't drift apart.+ */+export const EventStreamsListParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++/**+ * The caller's event stream: a live feed of selected accounts' events posted to a+ * Slack channel of their choice. Per-user — each team member owns at most one stream, and+ * every endpoint is scoped to the caller's own. Delivery runs through a managed CDP+ * destination that is re-provisioned inside the same transaction as every write, so+ * config and delivery can't drift apart.+ */+export const EventStreamsCreateParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const eventStreamsCreateBodyEnabledDefault = false+export const eventStreamsCreateBodyEventNamesItemMax = 400++export const eventStreamsCreateBodySlackChannelIdDefault = ``+export const eventStreamsCreateBodySlackChannelIdMax = 200++export const eventStreamsCreateBodySlackChannelNameDefault = ``+export const eventStreamsCreateBodySlackChannelNameMax = 200++export const EventStreamsCreateBody = /* @__PURE__ */ zod+ .object({+ enabled: zod+ .boolean()+ .default(eventStreamsCreateBodyEnabledDefault)+ .describe(+ 'Whether the stream delivers to Slack. Delivery also requires at least one event, at least one member account with an external ID, and a Slack workspace + channel.'+ ),+ event_names: zod+ .array(zod.string().max(eventStreamsCreateBodyEventNamesItemMax))+ .optional()+ .describe('Names of the events to stream (matched exactly). Duplicates and blanks are dropped.'),+ slack_integration: zod+ .number()+ .nullish()+ .describe("ID of the team's Slack workspace integration to deliver through."),+ slack_channel_id: zod+ .string()+ .max(eventStreamsCreateBodySlackChannelIdMax)+ .default(eventStreamsCreateBodySlackChannelIdDefault)+ .describe('Slack channel ID to post to (e.g. C0123ABC).'),+ slack_channel_name: zod+ .string()+ .max(eventStreamsCreateBodySlackChannelNameMax)+ .default(eventStreamsCreateBodySlackChannelNameDefault)+ .describe('Display name of the Slack channel (e.g. #customer-events). Informational only.'),+ })+ .describe(+ "The caller's event stream — a live feed of selected accounts' events posted to a\nSlack channel of their choice. One stream per user per project."+ )++/**+ * The caller's event stream: a live feed of selected accounts' events posted to a+ * Slack channel of their choice. Per-user — each team member owns at most one stream, and+ * every endpoint is scoped to the caller's own. Delivery runs through a managed CDP+ * destination that is re-provisioned inside the same transaction as every write, so+ * config and delivery can't drift apart.+ */+export const EventStreamsPartialUpdateParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this event stream.'),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const eventStreamsPartialUpdateBodyEventNamesItemMax = 400++export const eventStreamsPartialUpdateBodySlackChannelIdMax = 200++export const eventStreamsPartialUpdateBodySlackChannelNameMax = 200++export const EventStreamsPartialUpdateBody = /* @__PURE__ */ zod+ .object({+ enabled: zod+ .boolean()+ .optional()+ .describe(+ 'Whether the stream delivers to Slack. Delivery also requires at least one event, at least one member account with an external ID, and a Slack workspace + channel.'+ ),+ event_names: zod+ .array(zod.string().max(eventStreamsPartialUpdateBodyEventNamesItemMax))+ .optional()+ .describe('Names of the events to stream (matched exactly). Duplicates and blanks are dropped.'),+ slack_integration: zod+ .number()+ .nullish()+ .describe("ID of the team's Slack workspace integration to deliver through."),+ slack_channel_id: zod+ .string()+ .max(eventStreamsPartialUpdateBodySlackChannelIdMax)+ .optional()+ .describe('Slack channel ID to post to (e.g. C0123ABC).'),+ slack_channel_name: zod+ .string()+ .max(eventStreamsPartialUpdateBodySlackChannelNameMax)+ .optional()+ .describe('Display name of the Slack channel (e.g. #customer-events). Informational only.'),+ })+ .describe(+ "The caller's event stream — a live feed of selected accounts' events posted to a\nSlack channel of their choice. One stream per user per project."+ )++/**+ * The caller's event stream: a live feed of selected accounts' events posted to a+ * Slack channel of their choice. Per-user — each team member owns at most one stream, and+ * every endpoint is scoped to the caller's own. Delivery runs through a managed CDP+ * destination that is re-provisioned inside the same transaction as every write, so+ * config and delivery can't drift apart.+ */+export const EventStreamsDestroyParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this event stream.'),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++/**+ * The caller's event stream: a live feed of selected accounts' events posted to a+ * Slack channel of their choice. Per-user — each team member owns at most one stream, and+ * every endpoint is scoped to the caller's own. Delivery runs through a managed CDP+ * destination that is re-provisioned inside the same transaction as every write, so+ * config and delivery can't drift apart.+ */+export const EventStreamsAddAccountCreateParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this event stream.'),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const EventStreamsAddAccountCreateBody = /* @__PURE__ */ zod+ .object({+ account_id: zod.string().describe('UUID of the account to add to or remove from the stream.'),+ })+ .describe('Request body for adding or removing an event-stream member account.')++/**+ * The caller's event stream: a live feed of selected accounts' events posted to a+ * Slack channel of their choice. Per-user — each team member owns at most one stream, and+ * every endpoint is scoped to the caller's own. Delivery runs through a managed CDP+ * destination that is re-provisioned inside the same transaction as every write, so+ * config and delivery can't drift apart.+ */+export const EventStreamsRemoveAccountCreateParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this event stream.'),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const EventStreamsRemoveAccountCreateBody = /* @__PURE__ */ zod+ .object({+ account_id: zod.string().describe('UUID of the account to add to or remove from the stream.'),+ })+ .describe('Request body for adding or removing an event-stream member account.')++/**+ * The caller's event stream: a live feed of selected accounts' events posted to a+ * Slack channel of their choice. Per-user — each team member owns at most one stream, and+ * every endpoint is scoped to the caller's own. Delivery runs through a managed CDP+ * destination that is re-provisioned inside the same transaction as every write, so+ * config and delivery can't drift apart.+ */+export const EventStreamsSendTestMessageCreateParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this event stream.'),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})+export const groupsTypesMetricsListPathGroupTypeIndexMin = -2147483648export const groupsTypesMetricsListPathGroupTypeIndexMax = 2147483647diff --git a/services/mcp/src/tools/generated/customer_analytics.ts b/services/mcp/src/tools/generated/customer_analytics.tsindex 021b938a0de3..bf44d8ca3c30 100644--- a/services/mcp/src/tools/generated/customer_analytics.ts+++ b/services/mcp/src/tools/generated/customer_analytics.ts@@ -45,6 +45,15 @@ import {CustomPropertySourcesRunsListParams,CustomPropertySourcesRunsListQueryParams,CustomPropertySourcesSyncParams,+ EventStreamsAddAccountCreateBody,+ EventStreamsAddAccountCreateParams,+ EventStreamsCreateBody,+ EventStreamsDestroyParams,+ EventStreamsPartialUpdateBody,+ EventStreamsPartialUpdateParams,+ EventStreamsRemoveAccountCreateBody,+ EventStreamsRemoveAccountCreateParams,+ EventStreamsSendTestMessageCreateParams,GroupsTypesMetricsCreateBody,GroupsTypesMetricsCreateParams,GroupsTypesMetricsDestroyParams,@@ -836,6 +845,165 @@ const customPropertySourcesSync = (): ToolBase<typeof CustomPropertySourcesSyncS},})+const EventStreamsAddAccountSchema = EventStreamsAddAccountCreateParams.omit({ project_id: true }).extend(+ EventStreamsAddAccountCreateBody.shape+)++const eventStreamsAddAccount = (): ToolBase<typeof EventStreamsAddAccountSchema, Schemas.EventStream> => ({+ name: 'event-streams-add-account',+ schema: EventStreamsAddAccountSchema,+ handler: async (context: Context, params: z.infer<typeof EventStreamsAddAccountSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.account_id !== undefined) {+ body['account_id'] = params.account_id+ }+ const result = await context.api.request<Schemas.EventStream>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/event_streams/${encodeURIComponent(String(params.id))}/add_account/`,+ body,+ })+ return result+ },+})++const EventStreamsCreateSchema = EventStreamsCreateBody++const eventStreamsCreate = (): ToolBase<typeof EventStreamsCreateSchema, Schemas.EventStream> => ({+ name: 'event-streams-create',+ schema: EventStreamsCreateSchema,+ handler: async (context: Context, params: z.infer<typeof EventStreamsCreateSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.enabled !== undefined) {+ body['enabled'] = params.enabled+ }+ if (params.event_names !== undefined) {+ body['event_names'] = params.event_names+ }+ if (params.slack_integration !== undefined) {+ body['slack_integration'] = params.slack_integration+ }+ if (params.slack_channel_id !== undefined) {+ body['slack_channel_id'] = params.slack_channel_id+ }+ if (params.slack_channel_name !== undefined) {+ body['slack_channel_name'] = params.slack_channel_name+ }+ const result = await context.api.request<Schemas.EventStream>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/event_streams/`,+ body,+ })+ return result+ },+})++const EventStreamsDestroySchema = EventStreamsDestroyParams.omit({ project_id: true })++const eventStreamsDestroy = (): ToolBase<typeof EventStreamsDestroySchema, unknown> => ({+ name: 'event-streams-destroy',+ schema: EventStreamsDestroySchema,+ handler: async (context: Context, params: z.infer<typeof EventStreamsDestroySchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<unknown>({+ method: 'DELETE',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/event_streams/${encodeURIComponent(String(params.id))}/`,+ })+ return result+ },+})++const EventStreamsListSchema = z.object({})++const eventStreamsList = (): ToolBase<typeof EventStreamsListSchema, Schemas.EventStream[]> => ({+ name: 'event-streams-list',+ schema: EventStreamsListSchema,+ // eslint-disable-next-line no-unused-vars+ handler: async (context: Context, params: z.infer<typeof EventStreamsListSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.EventStream[]>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/event_streams/`,+ })+ return result+ },+})++const EventStreamsPartialUpdateSchema = EventStreamsPartialUpdateParams.omit({ project_id: true }).extend(+ EventStreamsPartialUpdateBody.shape+)++const eventStreamsPartialUpdate = (): ToolBase<typeof EventStreamsPartialUpdateSchema, Schemas.EventStream> => ({+ name: 'event-streams-partial-update',+ schema: EventStreamsPartialUpdateSchema,+ handler: async (context: Context, params: z.infer<typeof EventStreamsPartialUpdateSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.enabled !== undefined) {+ body['enabled'] = params.enabled+ }+ if (params.event_names !== undefined) {+ body['event_names'] = params.event_names+ }+ if (params.slack_integration !== undefined) {+ body['slack_integration'] = params.slack_integration+ }+ if (params.slack_channel_id !== undefined) {+ body['slack_channel_id'] = params.slack_channel_id+ }+ if (params.slack_channel_name !== undefined) {+ body['slack_channel_name'] = params.slack_channel_name+ }+ const result = await context.api.request<Schemas.EventStream>({+ method: 'PATCH',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/event_streams/${encodeURIComponent(String(params.id))}/`,+ body,+ })+ return result+ },+})++const EventStreamsRemoveAccountSchema = EventStreamsRemoveAccountCreateParams.omit({ project_id: true }).extend(+ EventStreamsRemoveAccountCreateBody.shape+)++const eventStreamsRemoveAccount = (): ToolBase<typeof EventStreamsRemoveAccountSchema, Schemas.EventStream> => ({+ name: 'event-streams-remove-account',+ schema: EventStreamsRemoveAccountSchema,+ handler: async (context: Context, params: z.infer<typeof EventStreamsRemoveAccountSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.account_id !== undefined) {+ body['account_id'] = params.account_id+ }+ const result = await context.api.request<Schemas.EventStream>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/event_streams/${encodeURIComponent(String(params.id))}/remove_account/`,+ body,+ })+ return result+ },+})++const EventStreamsSendTestMessageSchema = EventStreamsSendTestMessageCreateParams.omit({ project_id: true })++const eventStreamsSendTestMessage = (): ToolBase<+ typeof EventStreamsSendTestMessageSchema,+ Schemas.EventStreamTestMessage+> => ({+ name: 'event-streams-send-test-message',+ schema: EventStreamsSendTestMessageSchema,+ handler: async (context: Context, params: z.infer<typeof EventStreamsSendTestMessageSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.EventStreamTestMessage>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/event_streams/${encodeURIComponent(String(params.id))}/send_test_message/`,+ })+ return result+ },+})+const UsageMetricsCreateSchema = GroupsTypesMetricsCreateParams.omit({ project_id: true }).extend(GroupsTypesMetricsCreateBody.shape).extend({@@ -1031,6 +1199,13 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'custom-property-sources-retrieve': customPropertySourcesRetrieve,'custom-property-sources-runs-list': customPropertySourcesRunsList,'custom-property-sources-sync': customPropertySourcesSync,+ 'event-streams-add-account': eventStreamsAddAccount,+ 'event-streams-create': eventStreamsCreate,+ 'event-streams-destroy': eventStreamsDestroy,+ 'event-streams-list': eventStreamsList,+ 'event-streams-partial-update': eventStreamsPartialUpdate,+ 'event-streams-remove-account': eventStreamsRemoveAccount,+ 'event-streams-send-test-message': eventStreamsSendTestMessage,'usage-metrics-create': usageMetricsCreate,'usage-metrics-destroy': usageMetricsDestroy,'usage-metrics-list': usageMetricsList,diff --git a/tach.toml b/tach.tomlindex 5b84cd97839d..cbbe4ba03b58 100644--- a/tach.toml+++ b/tach.toml@@ -693,7 +693,9 @@ path = "products.customer_analytics"depends_on = ["ee","posthog",+ "products.cdp","products.conversations",+ "products.data_warehouse","products.notebooks","products.notifications","products.product_analytics",