From 46b8b8a68ddd5dac55e7da0e454b61050e9606cd Mon Sep 17 00:00:00 2001 From: openhands Date: Fri, 18 Sep 2026 16:20:50 +0000 Subject: [PATCH] OSS-13530: Tag Enterprise telemetry deployment kind Co-authored-by: openhands --- .../providers/posthog-wrapper.test.tsx | 34 ++++++++++++++++++ .../components/providers/posthog-wrapper.tsx | 35 +++++++++++++++++++ openhands/analytics/__init__.py | 5 ++- openhands/analytics/analytics_service.py | 17 ++++++--- .../app_lifespan/saas_app_lifespan_service.py | 1 + tests/unit/test_analytics_service.py | 24 +++++++++++++ tests/unit/test_saas_lifespan.py | 2 ++ 7 files changed, 113 insertions(+), 5 deletions(-) diff --git a/frontend/__tests__/components/providers/posthog-wrapper.test.tsx b/frontend/__tests__/components/providers/posthog-wrapper.test.tsx index 7a071a2897..c718f14acd 100644 --- a/frontend/__tests__/components/providers/posthog-wrapper.test.tsx +++ b/frontend/__tests__/components/providers/posthog-wrapper.test.tsx @@ -161,6 +161,40 @@ describe("PostHogWrapper", () => { ); }); + it("should stamp deployment_kind on every PostHog event", async () => { + vi.spyOn(OptionService, "getConfig").mockResolvedValue( + createMockWebClientConfig({ + app_mode: "saas", + posthog_client_key: "configured-posthog-key", + feature_flags: { + ...createMockWebClientConfig().feature_flags, + deployment_mode: "cloud", + }, + }), + ); + + render( + +
+ , + ); + + await screen.findByTestId("child"); + + const [{ options }] = mockPostHogProvider.mock.calls[0]; + const event = options.before_send({ + event: "test_event", + properties: { custom: "value" }, + }); + + expect(event.properties).toEqual( + expect.objectContaining({ + custom: "value", + deployment_kind: "remote", + }), + ); + }); + it("should initialize without bootstrap when neither hash nor sessionStorage has IDs", async () => { render( diff --git a/frontend/src/components/providers/posthog-wrapper.tsx b/frontend/src/components/providers/posthog-wrapper.tsx index 182efbcb24..544909210e 100644 --- a/frontend/src/components/providers/posthog-wrapper.tsx +++ b/frontend/src/components/providers/posthog-wrapper.tsx @@ -1,10 +1,41 @@ import React from "react"; +import type { CaptureResult } from "posthog-js"; import { PostHogProvider } from "posthog-js/react"; import { queryClient } from "#/query-client-config"; import OptionService from "#/api/option-service/option-service.api"; import { QUERY_KEYS, CONFIG_CACHE_OPTIONS } from "#/hooks/query/query-keys"; import { displayErrorToast } from "#/utils/custom-toast-handlers"; +type DeploymentKind = "local" | "remote"; + +type WebClientTelemetryConfig = Awaited< + ReturnType +>; + +function getDeploymentKind(config: WebClientTelemetryConfig): DeploymentKind { + if ( + config.app_mode === "saas" && + config.feature_flags?.deployment_mode !== "self_hosted" + ) { + return "remote"; + } + return "local"; +} + +function addDeploymentKind( + event: CaptureResult | null, + deploymentKind: DeploymentKind, +): CaptureResult | null { + if (!event) return null; + return { + ...event, + properties: { + ...event.properties, + deployment_kind: deploymentKind, + }, + }; +} + const POSTHOG_BOOTSTRAP_KEY = "posthog_bootstrap"; function getBootstrapIds() { @@ -43,6 +74,8 @@ export function PostHogWrapper({ children }: { children: React.ReactNode }) { const [posthogClientKey, setPosthogClientKey] = React.useState( null, ); + const [deploymentKind, setDeploymentKind] = + React.useState("local"); const [isLoading, setIsLoading] = React.useState(true); const bootstrapIds = React.useMemo(() => getBootstrapIds(), []); @@ -58,6 +91,7 @@ export function PostHogWrapper({ children }: { children: React.ReactNode }) { const isEnterpriseSelfHosted = config.app_mode === "saas" && config.feature_flags?.deployment_mode === "self_hosted"; + setDeploymentKind(getDeploymentKind(config)); setPosthogClientKey( isEnterpriseSelfHosted ? null : config.posthog_client_key, ); @@ -85,6 +119,7 @@ export function PostHogWrapper({ children }: { children: React.ReactNode }) { }, capture_exceptions: true, bootstrap: bootstrapIds, + before_send: (event) => addDeploymentKind(event, deploymentKind), __add_tracing_headers: [window.location.hostname], }} > diff --git a/openhands/analytics/__init__.py b/openhands/analytics/__init__.py index b7e0f45ca6..981357a7c0 100644 --- a/openhands/analytics/__init__.py +++ b/openhands/analytics/__init__.py @@ -19,7 +19,7 @@ AnalyticsContext, resolve_analytics_context, ) -from openhands.analytics.analytics_service import AnalyticsService +from openhands.analytics.analytics_service import AnalyticsService, DeploymentKind from openhands.server.types import AppMode _analytics_service: AnalyticsService | None = None @@ -30,6 +30,7 @@ def init_analytics_service( host: str, app_mode: AppMode, is_feature_env: bool, + deployment_kind: DeploymentKind | None = None, ) -> AnalyticsService: """Create and store the module-level AnalyticsService singleton. @@ -42,6 +43,7 @@ def init_analytics_service( host=host, app_mode=app_mode, is_feature_env=is_feature_env, + deployment_kind=deployment_kind, ) return _analytics_service @@ -57,6 +59,7 @@ def get_analytics_service() -> AnalyticsService | None: __all__ = [ 'AnalyticsContext', 'AnalyticsService', + 'DeploymentKind', 'get_analytics_service', 'init_analytics_service', 'resolve_analytics_context', diff --git a/openhands/analytics/analytics_service.py b/openhands/analytics/analytics_service.py index 78775a2128..64897f698b 100644 --- a/openhands/analytics/analytics_service.py +++ b/openhands/analytics/analytics_service.py @@ -4,7 +4,8 @@ - Consent gate: all calls are no-ops when consented=False - OSS/SaaS dual-mode: $process_person_profile is set to False in OSS mode; set_person_properties and group_identify are SaaS-only -- Common properties: app_mode, is_feature_env added to every event +- Common properties: app_mode, deployment_kind, is_feature_env added to every + event - Feature-env distinct_id prefix: FEATURE_ prefix for staging/feature envs - SDK error isolation: all exceptions are caught and logged, never raised @@ -13,7 +14,7 @@ """ from datetime import datetime, timezone -from typing import Any +from typing import Any, Literal from posthog import Posthog @@ -42,6 +43,8 @@ from openhands.app_server.utils.logger import openhands_logger as logger from openhands.server.types import AppMode +DeploymentKind = Literal['local', 'remote'] + # Maps the enterprise ConversationTrigger enum values to the unified # ``conversation_source`` property that both the SDK agent-server telemetry # and the enterprise analytics emit to PostHog. Keeping the mapping in one @@ -73,9 +76,13 @@ def __init__( host: str, app_mode: AppMode, is_feature_env: bool, + deployment_kind: DeploymentKind | None = None, ) -> None: self._app_mode = app_mode self._is_feature_env = is_feature_env + self._deployment_kind = deployment_kind or ( + 'remote' if app_mode == AppMode.SAAS else 'local' + ) self._client: Posthog = Posthog( project_api_key=api_key, host=host, @@ -96,8 +103,9 @@ def capture( """Capture a server-side event. Consent gate: returns immediately when ctx.consented=False. - Common properties (app_mode, is_feature_env, and optionally org_id / - $session_id / $process_person_profile) are merged with caller-provided + Common properties (app_mode, deployment_kind, is_feature_env, and + optionally org_id / $session_id / $process_person_profile) are merged + with caller-provided properties before forwarding to PostHog. """ if not ctx.consented: @@ -723,6 +731,7 @@ def _common_properties( """Build the base property dict included on every event.""" props: dict[str, Any] = { 'app_mode': self._app_mode.value, + 'deployment_kind': self._deployment_kind, 'is_feature_env': self._is_feature_env, } diff --git a/server/app_lifespan/saas_app_lifespan_service.py b/server/app_lifespan/saas_app_lifespan_service.py index 58693a6fcc..115f8c5942 100644 --- a/server/app_lifespan/saas_app_lifespan_service.py +++ b/server/app_lifespan/saas_app_lifespan_service.py @@ -79,6 +79,7 @@ async def __aenter__(self): host=host, app_mode=AppMode.SAAS, is_feature_env=IS_FEATURE_ENV, + deployment_kind=('local' if DEPLOYMENT_MODE == 'self_hosted' else 'remote'), ) await self._reconcile_org_condenser_defaults() return self diff --git a/tests/unit/test_analytics_service.py b/tests/unit/test_analytics_service.py index e13235c7ad..6927921a1e 100644 --- a/tests/unit/test_analytics_service.py +++ b/tests/unit/test_analytics_service.py @@ -312,6 +312,30 @@ def test_capture_always_includes_is_feature_env(self, saas_service): assert 'is_feature_env' in props assert props['is_feature_env'] is False + def test_capture_defaults_saas_deployment_kind_to_remote(self, saas_service): + """SaaS analytics events default to remote deployment_kind.""" + service, mock_client = saas_service + ctx = make_ctx(user_id='user123') + service.capture(ctx=ctx, event='test event') + _, kwargs = mock_client.capture.call_args + props = kwargs.get('properties', {}) + assert props['deployment_kind'] == 'remote' + + def test_capture_accepts_local_deployment_kind(self, mock_posthog): + """Self-hosted SaaS analytics events can be tagged local.""" + _, mock_client = mock_posthog + service = DirectService( + api_key='test-key', + host='https://posthog.example.com', + app_mode=AppMode.SAAS, + is_feature_env=False, + deployment_kind='local', + ) + service.capture(ctx=make_ctx(user_id='user123'), event='test event') + _, kwargs = mock_client.capture.call_args + props = kwargs.get('properties', {}) + assert props['deployment_kind'] == 'local' + def test_capture_includes_org_id_when_provided(self, saas_service): """capture() includes org_id when provided.""" service, mock_client = saas_service diff --git a/tests/unit/test_saas_lifespan.py b/tests/unit/test_saas_lifespan.py index 5adf3f262a..7a3e1f8aba 100644 --- a/tests/unit/test_saas_lifespan.py +++ b/tests/unit/test_saas_lifespan.py @@ -113,6 +113,7 @@ async def test_aenter_passes_env_vars_to_init(): call_kwargs = mock_init.call_args assert call_kwargs.kwargs['api_key'] == 'test-key' assert call_kwargs.kwargs['host'] == 'https://test.posthog.com' + assert call_kwargs.kwargs['deployment_kind'] == 'remote' @pytest.mark.asyncio @@ -134,6 +135,7 @@ async def test_aenter_disables_analytics_when_self_hosted(): await svc.__aenter__() assert mock_init.call_args.kwargs['api_key'] == '' + assert mock_init.call_args.kwargs['deployment_kind'] == 'local' @pytest.mark.asyncio