Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions frontend/__tests__/components/providers/posthog-wrapper.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(
<PostHogWrapper>
<div data-testid="child" />
</PostHogWrapper>,
);

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(
<PostHogWrapper>
Expand Down
35 changes: 35 additions & 0 deletions frontend/src/components/providers/posthog-wrapper.tsx
Original file line number Diff line number Diff line change
@@ -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<typeof OptionService.getConfig>
>;

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() {
Expand Down Expand Up @@ -43,6 +74,8 @@ export function PostHogWrapper({ children }: { children: React.ReactNode }) {
const [posthogClientKey, setPosthogClientKey] = React.useState<string | null>(
null,
);
const [deploymentKind, setDeploymentKind] =
React.useState<DeploymentKind>("local");
const [isLoading, setIsLoading] = React.useState(true);
const bootstrapIds = React.useMemo(() => getBootstrapIds(), []);

Expand All @@ -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,
);
Expand Down Expand Up @@ -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],
}}
>
Expand Down
5 changes: 4 additions & 1 deletion openhands/analytics/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.

Expand All @@ -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

Expand All @@ -57,6 +59,7 @@ def get_analytics_service() -> AnalyticsService | None:
__all__ = [
'AnalyticsContext',
'AnalyticsService',
'DeploymentKind',
'get_analytics_service',
'init_analytics_service',
'resolve_analytics_context',
Expand Down
17 changes: 13 additions & 4 deletions openhands/analytics/analytics_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -13,7 +14,7 @@
"""

from datetime import datetime, timezone
from typing import Any
from typing import Any, Literal

from posthog import Posthog

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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:
Expand Down Expand Up @@ -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,
}

Expand Down
1 change: 1 addition & 0 deletions server/app_lifespan/saas_app_lifespan_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
24 changes: 24 additions & 0 deletions tests/unit/test_analytics_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions tests/unit/test_saas_lifespan.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
Loading