π OpenHands: AI-Driven Development
fix: add version context to telemetry (#1872)
Rohit Malhotra4d0fc5c942c9
diff --git a/__tests__/components/backends/add-backend-modal.test.tsx b/__tests__/components/backends/add-backend-modal.test.tsxindex d747a5beb3..5f8f8b89fa 100644--- a/__tests__/components/backends/add-backend-modal.test.tsx+++ b/__tests__/components/backends/add-backend-modal.test.tsx@@ -350,8 +350,6 @@ describe("AddBackendModal β analytics", () => {expect.objectContaining({backend_kind: "local",connection_method: "manual",- is_openhands_cloud: false,- is_custom_host: true,has_api_key: true,source: "add_backend_modal",}),diff --git a/__tests__/hooks/use-tracking.test.ts b/__tests__/hooks/use-tracking.test.tsindex 0037feacb2..a0f49b0a2f 100644--- a/__tests__/hooks/use-tracking.test.ts+++ b/__tests__/hooks/use-tracking.test.ts@@ -1,4 +1,4 @@-import { renderHook } from "@testing-library/react";+import { renderHook, waitFor } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import * as telemetry from "#/services/telemetry";@@ -7,21 +7,42 @@ vi.mock("#/hooks/query/use-settings", () => ({useSettings: () => useSettingsMock(),}));+const compatibilityMocks = vi.hoisted(() => ({+ getCachedAgentServerVersion: vi.fn(),+}));+vi.mock("#/api/agent-server-compatibility", () => ({+ getCachedAgentServerVersion: compatibilityMocks.getCachedAgentServerVersion,+}));++const automationServiceMocks = vi.hoisted(() => ({+ getSdkVersion: vi.fn(),+}));+vi.mock("#/api/automation-service/automation-service.api", () => ({+ default: automationServiceMocks,+}));+import { useTracking } from "#/hooks/use-tracking";const TEST_EMAIL = "[email protected]";// Resolved at test-run time so it matches whatever URL jsdom is configured// with in the current environment (varies between local and CI).-let COMMON: { current_url: string; user_email: string };+let COMMON: Record<string, unknown>;describe("useTracking", () => {let captureMock: ReturnType<typeof vi.spyOn>;+ let setBackendContextMock: ReturnType<typeof vi.spyOn>;beforeEach(() => {captureMock = vi.spyOn(telemetry, "trackEvent").mockResolvedValue(undefined);+ setBackendContextMock = vi.spyOn(telemetry, "setTelemetryBackendContext");useSettingsMock.mockReset();+ automationServiceMocks.getSdkVersion.mockReset();+ automationServiceMocks.getSdkVersion.mockResolvedValue(null);+ compatibilityMocks.getCachedAgentServerVersion.mockReset();+ compatibilityMocks.getCachedAgentServerVersion.mockReturnValue(null);+useSettingsMock.mockReturnValue({data: { email: TEST_EMAIL, user_consents_to_analytics: true },});@@ -33,6 +54,7 @@ describe("useTracking", () => {afterEach(() => {captureMock.mockRestore();+ setBackendContextMock.mockRestore();});const getTracking = () => renderHook(() => useTracking()).result.current;@@ -127,6 +149,72 @@ describe("useTracking", () => {}),);});++ it("declares backend versions to the telemetry service when known", async () => {+ automationServiceMocks.getSdkVersion.mockResolvedValue("1.36.3");+ compatibilityMocks.getCachedAgentServerVersion.mockReturnValue("1.36.2");++ const { result } = renderHook(() => useTracking());+ await waitFor(() =>+ expect(setBackendContextMock).toHaveBeenCalledWith(+ expect.objectContaining({ automationSdkVersion: "1.36.3" }),+ ),+ );+ setBackendContextMock.mockClear();++ result.current.trackConversationCreated({+ conversationId: "conv-versioned",+ taskId: "conv-versioned",+ hasRepository: false,+ hasWorkspace: false,+ hasInitialQuery: true,+ hasParentConversation: false,+ entryPoint: "home",+ });++ expect(setBackendContextMock).toHaveBeenCalledWith(+ expect.objectContaining({+ backendKind: "local",+ agentServerVersion: "1.36.2",+ automationSdkVersion: "1.36.3",+ }),+ );+ expect(captureMock).toHaveBeenCalledWith(+ "conversation_created",+ expect.not.objectContaining({+ agent_server_version: "1.36.2",+ automation_sdk_version: "1.36.3",+ backend_version: "1.36.2",+ }),+ );+ expect(+ compatibilityMocks.getCachedAgentServerVersion,+ ).toHaveBeenCalledWith(expect.any(String));+ });++ it("uses the latest cached agent-server version when an event fires", () => {+ compatibilityMocks.getCachedAgentServerVersion.mockReturnValue(null);+ const tracking = getTracking();+ setBackendContextMock.mockClear();+ compatibilityMocks.getCachedAgentServerVersion.mockReturnValue("1.36.1");++ tracking.trackConversationCreated({+ conversationId: "conv-cache-late",+ taskId: "conv-cache-late",+ hasRepository: false,+ hasWorkspace: false,+ hasInitialQuery: true,+ hasParentConversation: false,+ entryPoint: "home",+ });++ expect(setBackendContextMock).toHaveBeenCalledWith(+ expect.objectContaining({+ backendKind: "local",+ agentServerVersion: "1.36.1",+ }),+ );+ });});describe("trackPushButtonClick", () => {@@ -314,20 +402,20 @@ describe("useTracking", () => {getTracking().trackBackendAdded({backendKind: "cloud",connectionMethod: "cloud_login",- isOpenhandsCloud: true,- isCustomHost: false,hasApiKey: true,source: "add_backend_modal",+ agentServerVersion: "1.36.1",});expect(captureMock).toHaveBeenCalledWith("backend_added", {+ ...COMMON,backend_kind: "cloud",connection_method: "cloud_login",- is_openhands_cloud: true,- is_custom_host: false,has_api_key: true,source: "add_backend_modal",- ...COMMON,+ agent_server_version: "1.36.1",+ automation_sdk_version: "unknown",+ backend_version: "1.36.1",});});});@@ -365,8 +453,6 @@ describe("useTracking", () => {getTracking().trackBackendAdded({backendKind: "cloud",connectionMethod: "cloud_login",- isOpenhandsCloud: true,- isCustomHost: false,hasApiKey: true,source: "onboarding",});@@ -376,7 +462,6 @@ describe("useTracking", () => {expect.objectContaining({backend_kind: "cloud",connection_method: "cloud_login",- is_openhands_cloud: true,source: "onboarding",user_email: null,}),diff --git a/__tests__/services/cloud-funnel-analytics.test.ts b/__tests__/services/cloud-funnel-analytics.test.tsindex 2020ec93d3..d6f4d52631 100644--- a/__tests__/services/cloud-funnel-analytics.test.ts+++ b/__tests__/services/cloud-funnel-analytics.test.ts@@ -33,8 +33,11 @@ describe("cloud funnel analytics", () => {1,"cloud_device_authorization_started",expect.objectContaining({- is_openhands_cloud: true,- is_custom_host: false,+ backend_kind: "cloud",+ connection_method: "cloud_login",+ agent_server_version: "unknown",+ automation_sdk_version: "unknown",+ backend_version: "unknown",source: "onboarding",}),);@@ -54,6 +57,10 @@ describe("cloud funnel analytics", () => {expect.objectContaining({task_id: "task-id",conversation_id: "conversation-id",+ backend_kind: "cloud",+ agent_server_version: "unknown",+ automation_sdk_version: "unknown",+ backend_version: "unknown",}),);});diff --git a/__tests__/services/telemetry-delivery.test.ts b/__tests__/services/telemetry-delivery.test.tsindex 95e25e2751..0c92458083 100644--- a/__tests__/services/telemetry-delivery.test.ts+++ b/__tests__/services/telemetry-delivery.test.ts@@ -34,8 +34,6 @@ describe("Canvas telemetry delivery", () => {result.current.trackBackendAdded({backendKind: "cloud",connectionMethod: "cloud_login",- isOpenhandsCloud: true,- isCustomHost: false,hasApiKey: true,source: "onboarding",});diff --git a/__tests__/services/telemetry.test.ts b/__tests__/services/telemetry.test.tsindex 62b276f577..be658081bf 100644--- a/__tests__/services/telemetry.test.ts+++ b/__tests__/services/telemetry.test.ts@@ -33,6 +33,7 @@ import {initializePostHogClient,setTelemetryConsent,setTelemetryIdentity,+ setTelemetryBackendContext,subscribeTelemetryConsent,isTelemetryEnabled,trackInstall,@@ -61,6 +62,7 @@ describe("Telemetry Service", () => {vi.clearAllMocks();identifiedUserId = undefined;mockPosthog.has_opted_out_capturing.mockReturnValue(false);+ setTelemetryBackendContext({});});afterEach(() => {@@ -112,6 +114,31 @@ describe("Telemetry Service", () => {client_version: expect.any(String),package_name: "@openhands/agent-canvas",package_version: expect.any(String),+ backend_kind: null,+ agent_server_version: "unknown",+ automation_sdk_version: "unknown",+ backend_version: "unknown",+ custom: "value",+ }),+ });++ setTelemetryBackendContext({+ backendKind: "local",+ agentServerVersion: "1.36.2",+ automationSdkVersion: "1.36.3",+ });+ expect(+ config.before_send({+ event: "backend_context_event",+ properties: { backend_kind: "cloud", custom: "value" },+ }),+ ).toEqual({+ event: "backend_context_event",+ properties: expect.objectContaining({+ backend_kind: "cloud",+ agent_server_version: "1.36.2",+ automation_sdk_version: "1.36.3",+ backend_version: "1.36.2",custom: "value",}),});@@ -249,6 +276,15 @@ describe("Telemetry Service", () => {expect(getPendingCloudTelemetryConsent()).toBeNull();});+ it("does not re-emit PostHog opt-in for unchanged granted consent", async () => {+ await setTelemetryConsent("granted");+ vi.clearAllMocks();++ await setTelemetryConsent("granted", { syncToCloud: false });++ expect(mockPosthog.opt_in_capturing).not.toHaveBeenCalled();+ });+it("only clears the pending decision it expects", async () => {await setTelemetryConsent("granted");@@ -350,6 +386,17 @@ describe("Telemetry Service", () => {});});+ it("does not repair SDK opt-out or capture when consent is denied", async () => {+ await setTelemetryConsent("denied");+ vi.clearAllMocks();+ mockPosthog.has_opted_out_capturing.mockReturnValue(true);++ await trackEvent("custom_action");++ expect(mockPosthog.opt_in_capturing).not.toHaveBeenCalled();+ expect(mockPosthog.capture).not.toHaveBeenCalled();+ });+it("repairs a stale SDK opt-out before a consented custom event", async () => {localStorage.setItem("openhands-telemetry-consent", "granted");mockPosthog.has_opted_out_capturing.mockReturnValue(true);diff --git a/src/api/agent-server-compatibility.test.ts b/src/api/agent-server-compatibility.test.tsindex 153593c35e..bde7fa0e6b 100644--- a/src/api/agent-server-compatibility.test.ts+++ b/src/api/agent-server-compatibility.test.ts@@ -3,12 +3,13 @@ import {AgentServerUnknownVersionError,AgentServerUnsupportedVersionError,assertAgentServerVersionIsSupported,+ getDisplayAgentServerSdkVersion,getDisplayAgentServerVersion,type AgentServerInfo,} from "./agent-server-compatibility";-const serverInfo = (version?: string): AgentServerInfo =>- ({ version }) as AgentServerInfo;+const serverInfo = (version?: string, sdkVersion?: string): AgentServerInfo =>+ ({ version, sdk_version: sdkVersion }) as AgentServerInfo;describe("agent-server version compatibility", () => {it("classifies missing and unknown versions separately from old versions", () => {@@ -36,4 +37,22 @@ describe("agent-server version compatibility", () => {expect(getDisplayAgentServerVersion(serverInfo("dev-build"))).toBeNull();expect(getDisplayAgentServerVersion(serverInfo("1.28.0"))).toBe("1.28.0");});++ it("uses sdk_version as the agent-server version fallback", () => {+ expect(getDisplayAgentServerVersion(serverInfo(undefined, "1.36.1"))).toBe(+ "1.36.1",+ );+ expect(() =>+ assertAgentServerVersionIsSupported(serverInfo(undefined, "1.36.1")),+ ).not.toThrow();+ });++ it("reports the dedicated agent-server SDK version when present", () => {+ expect(+ getDisplayAgentServerSdkVersion(serverInfo("1.36.0", "1.36.1")),+ ).toBe("1.36.1");+ expect(getDisplayAgentServerSdkVersion(serverInfo("1.36.0"))).toBe(+ "1.36.0",+ );+ });});diff --git a/src/api/agent-server-compatibility.ts b/src/api/agent-server-compatibility.tsindex 990aa7019e..0962d9bd63 100644--- a/src/api/agent-server-compatibility.ts+++ b/src/api/agent-server-compatibility.ts@@ -23,6 +23,7 @@ export const AGENT_SERVER_UNKNOWN_VERSION_ERROR_CODE ="AGENT_SERVER_UNKNOWN_VERSION";export interface AgentServerInfo extends BaseServerInfo {+ sdk_version?: string;usable_tools?: string[] | null;}@@ -158,12 +159,25 @@ export function isSdkHttpStatusError(error: unknown, status: number): boolean {);}-function getRawAgentServerVersion(serverInfo: AgentServerInfo): string | null {- if (typeof serverInfo.version !== "string") return null;- const trimmed = serverInfo.version.trim();+function normalizeAgentServerInfoVersion(version: unknown): string | null {+ if (typeof version !== "string") return null;+ const trimmed = version.trim();return trimmed || null;}+function getRawAgentServerSdkVersion(+ serverInfo: AgentServerInfo,+): string | null {+ return normalizeAgentServerInfoVersion(serverInfo.sdk_version);+}++function getRawAgentServerVersion(serverInfo: AgentServerInfo): string | null {+ return (+ normalizeAgentServerInfoVersion(serverInfo.version) ??+ getRawAgentServerSdkVersion(serverInfo)+ );+}+function getComparableAgentServerVersion(serverInfo: AgentServerInfo,): string | null {@@ -184,6 +198,34 @@ export function getDisplayAgentServerVersion(return version;}+export function getDisplayAgentServerSdkVersion(+ serverInfo: AgentServerInfo,+): string | null {+ const version =+ getRawAgentServerSdkVersion(serverInfo) ??+ getComparableAgentServerVersion(serverInfo);+ if (!version || version.toLowerCase() === UNKNOWN_AGENT_SERVER_VERSION) {+ return null;+ }+ return version;+}++export function getCachedAgentServerSdkVersion(+ host?: string | null,+): string | null {+ if (!cachedAgentServerInfo) return null;+ if (host && getEffectiveLocalBackend()?.host !== host) return null;+ return getDisplayAgentServerSdkVersion(cachedAgentServerInfo);+}++export function getCachedAgentServerVersion(+ host?: string | null,+): string | null {+ if (!cachedAgentServerInfo) return null;+ if (host && getEffectiveLocalBackend()?.host !== host) return null;+ return getDisplayAgentServerVersion(cachedAgentServerInfo);+}+function compareAgentServerVersions(actual: string, required: string) {const parsedActual = parseAgentServerVersion(actual);const parsedRequired = parseAgentServerVersion(required);diff --git a/src/api/automation-service/automation-service.api.test.ts b/src/api/automation-service/automation-service.api.test.tsindex ed7394704a..e85500aea7 100644--- a/src/api/automation-service/automation-service.api.test.ts+++ b/src/api/automation-service/automation-service.api.test.ts@@ -72,6 +72,53 @@ const createdAutomation: Automation = {updated_at: "2026-07-10T00:00:00Z",};+describe("AutomationService.getSdkVersion", () => {+ beforeEach(() => {+ setRegisteredBackends([localBackend]);+ setActiveSelection({ backendId: localBackend.id });+ });++ afterEach(() => {+ setActiveSelection(null);+ setRegisteredBackends([]);+ vi.clearAllMocks();+ });++ it("fetches the local automation SDK version from the automation sidecar", async () => {+ localAxios.get.mockResolvedValueOnce({ data: { sdk_version: "1.36.1" } });++ await expect(AutomationService.getSdkVersion()).resolves.toBe("1.36.1");++ expect(localAxios.get).toHaveBeenCalledWith("/api/automation/sdk-version", {+ timeout: 5000,+ });+ });++ it("fetches the cloud automation SDK version through the cloud proxy", async () => {+ setRegisteredBackends([cloudBackend]);+ setActiveSelection({ backendId: cloudBackend.id, orgId: "org-1" });+ callCloudProxy.mockResolvedValueOnce({ sdk_version: "1.36.2" });++ await expect(AutomationService.getSdkVersion()).resolves.toBe("1.36.2");++ expect(callCloudProxy).toHaveBeenCalledWith(+ expect.objectContaining({+ backend: cloudBackend,+ method: "GET",+ path: "/api/automation/sdk-version",+ headers: { "X-Org-Id": "org-1" },+ timeoutSeconds: 5,+ }),+ );+ });++ it("returns null when the SDK version endpoint is unavailable", async () => {+ localAxios.get.mockRejectedValueOnce(new Error("not running"));++ await expect(AutomationService.getSdkVersion()).resolves.toBeNull();+ });+});+describe("AutomationService.createAutomation", () => {beforeEach(() => {setRegisteredBackends([localBackend]);diff --git a/src/api/automation-service/automation-service.api.ts b/src/api/automation-service/automation-service.api.tsindex 52d1587dab..73e1d81c34 100644--- a/src/api/automation-service/automation-service.api.ts+++ b/src/api/automation-service/automation-service.api.ts@@ -22,6 +22,13 @@ export interface AutomationHealthResponse {message?: string;}+type AutomationSdkVersionResponse =+ | string+ | {+ sdk_version?: unknown;+ version?: unknown;+ };+// Local automation calls go to the automation sidecar that// `scripts/dev-with-automation.mjs` mounts behind the local agent-server.// Both backends use the same session API key and the same `X-Session-API-Key`@@ -53,6 +60,24 @@ localAutomationAxios.interceptors.request.use((config) => {return config;});+function normalizeAutomationSdkVersion(version: unknown): string | null {+ if (typeof version !== "string") return null;+ const trimmed = version.trim();+ return trimmed || null;+}++function getAutomationSdkVersionFromResponse(+ response: AutomationSdkVersionResponse,+): string | null {+ if (typeof response === "string") {+ return normalizeAutomationSdkVersion(response);+ }+ return (+ normalizeAutomationSdkVersion(response.sdk_version) ??+ normalizeAutomationSdkVersion(response.version)+ );+}+function buildPaginationQuery(limit: number, offset: number): string {const params = new URLSearchParams();params.set("limit", String(limit));@@ -139,6 +164,34 @@ function buildPinnedCloudHeaders(active: ResolvedActiveBackend) {}class AutomationService {+ static async getSdkVersion(): Promise<string | null> {+ const active = getActiveBackend();+ const path = `${AUTOMATION_BASE_PATH}/sdk-version`;++ try {+ let response: AutomationSdkVersionResponse;+ if (active.backend.kind === "cloud") {+ response = await callCloudProxy<AutomationSdkVersionResponse>({+ backend: active.backend,+ method: "GET",+ path,+ headers: buildPinnedCloudHeaders(active),+ timeoutSeconds: 5,+ });+ } else {+ const { data } =+ await localAutomationAxios.get<AutomationSdkVersionResponse>(path, {+ timeout: 5000,+ });+ response = data;+ }++ return getAutomationSdkVersionFromResponse(response);+ } catch {+ return null;+ }+ }+static async listAutomations(params: { limit?: number; offset?: number } = {},): Promise<AutomationsResponse> {diff --git a/src/components/features/backends/backend-form-modal.test.tsx b/src/components/features/backends/backend-form-modal.test.tsxindex ee991c888f..14493ef5e0 100644--- a/src/components/features/backends/backend-form-modal.test.tsx+++ b/src/components/features/backends/backend-form-modal.test.tsx@@ -74,6 +74,7 @@ describe("BackendConnectionOptions β manual backend type", () => {apiKey: "oh-cloud-key",}),"manual",+ { agentServerVersion: null },);});});diff --git a/src/components/features/backends/backend-form-modal.tsx b/src/components/features/backends/backend-form-modal.tsxindex 124fb61bc5..4591b30818 100644--- a/src/components/features/backends/backend-form-modal.tsx+++ b/src/components/features/backends/backend-form-modal.tsx@@ -39,6 +39,10 @@ import { DeviceFlowAuth } from "./device-flow-auth";export type BackendFormMode = "add" | "edit";+interface BackendConnectionTestMetadata {+ agentServerVersion: string | null;+}+interface BackendFormModalProps {mode: BackendFormMode;/** Required when `mode === "edit"`. */@@ -164,9 +168,9 @@ function getConnectionTestFailedMessage(title: string, error: unknown): string {async function testBackendConnection(backend: Pick<Backend, "host" | "apiKey" | "kind">,-): Promise<void> {+): Promise<BackendConnectionTestMetadata> {// Cloud backends authenticate via OAuth; preflight GET is not applicable.- if (backend.kind !== "local") return;+ if (backend.kind !== "local") return { agentServerVersion: null };const serverInfo = await new ServerClient(getAgentServerClientOptions({@@ -176,6 +180,7 @@ async function testBackendConnection(}),).getServerInfo();assertAgentServerVersionIsSupported(serverInfo);+ return { agentServerVersion: getDisplayAgentServerVersion(serverInfo) };}/**@@ -289,9 +294,11 @@ interface UseBackendFormOptions {* wrapped version (e.g. with extra logging or different timeout).* Should throw on failure.*/- onTestConnection: (payload: BackendFormSubmitPayload) => Promise<void>;+ onTestConnection: (+ payload: BackendFormSubmitPayload,+ ) => Promise<BackendConnectionTestMetadata>;/** Called after a successful connection test and persistence. */- onSuccess: () => void;+ onSuccess: (metadata: BackendConnectionTestMetadata) => void;/** Require a non-empty API key even when the host looks local. */requireApiKey?: boolean;/**@@ -363,8 +370,8 @@ function useBackendForm({if (onSubmitOverride) {await onSubmitOverride(payload);} else {- await onTestConnection(payload);- onSuccess();+ const metadata = await onTestConnection(payload);+ onSuccess(metadata);}} catch (error) {setConnectionError(@@ -692,6 +699,7 @@ interface BackendConnectionOptionsProps {onConnected: (payload: BackendFormSubmitPayload,connectionMethod: BackendConnectionMethod,+ metadata?: BackendConnectionTestMetadata,) => void;testIdRoot?: string;initialManualBackend?: Partial<@@ -775,6 +783,7 @@ interface ManualConnectionColumnProps {onConnected: (payload: BackendFormSubmitPayload,connectionMethod: BackendConnectionMethod,+ metadata?: BackendConnectionTestMetadata,) => void;testIdRoot: string;initialBackend?: Partial<@@ -820,7 +829,7 @@ function ManualConnectionColumn({initialHost: initialBackend?.host ?? "",initialApiKey: initialBackend?.apiKey ?? "",onTestConnection: testBackendConnection,- onSuccess: () => {+ onSuccess: (metadata) => {onConnected({name: name.trim(),@@ -829,6 +838,7 @@ function ManualConnectionColumn({kind,},"manual",+ metadata,);},requireApiKey,@@ -939,6 +949,7 @@ interface CloudLoginColumnProps {onConnected: (payload: BackendFormSubmitPayload,connectionMethod: BackendConnectionMethod,+ metadata?: BackendConnectionTestMetadata,) => void;testIdRoot: string;lockedHost?: string;@@ -1060,17 +1071,15 @@ function AddBackendConnectionOptions({(payload: BackendFormSubmitPayload,connectionMethod: BackendConnectionMethod,+ metadata?: BackendConnectionTestMetadata,) => {addBackend(payload);- // Coarse, non-sensitive host classification β never emit the raw host.- const isOpenHandsCloud = isOpenHandsCloudHost(payload.host);trackBackendAdded({backendKind: payload.kind,connectionMethod,- isOpenhandsCloud: isOpenHandsCloud,- isCustomHost: !isOpenHandsCloud,hasApiKey: Boolean(payload.apiKey),source,+ agentServerVersion: metadata?.agentServerVersion,});redirectAfterAdd();onClose();diff --git a/src/components/features/onboarding/steps/check-backend-step.tsx b/src/components/features/onboarding/steps/check-backend-step.tsxindex 7d82346818..eb7e55b48b 100644--- a/src/components/features/onboarding/steps/check-backend-step.tsx+++ b/src/components/features/onboarding/steps/check-backend-step.tsx@@ -19,7 +19,6 @@ import { BrandButton } from "#/components/features/settings/brand-button";import { useActiveBackendContext } from "#/contexts/active-backend-context";import { useBackendsHealth } from "#/hooks/query/use-backends-health";import { useTracking } from "#/hooks/use-tracking";-import { isOpenHandsCloudHost } from "#/api/device-flow-client";import { I18nKey } from "#/i18n/declaration";import ChevronDownSmallIcon from "#/icons/chevron-down-small.svg?react";import { cn } from "#/utils/utils";@@ -192,12 +191,9 @@ export function CheckBackendStep({setActive(backend.id, null);}}- const isOpenHandsCloud = isOpenHandsCloudHost(payload.host);trackBackendAdded({backendKind: payload.kind,connectionMethod,- isOpenhandsCloud: isOpenHandsCloud,- isCustomHost: !isOpenHandsCloud,hasApiKey: Boolean(payload.apiKey),source: "onboarding",});diff --git a/src/hooks/use-tracking.ts b/src/hooks/use-tracking.tsindex 3ff9be792a..e12c14fcc2 100644--- a/src/hooks/use-tracking.ts+++ b/src/hooks/use-tracking.ts@@ -1,9 +1,14 @@+import React from "react";import { useSettings } from "./query/use-settings";import { Provider } from "#/types/settings";import type { BackendKind } from "#/api/backend-registry/types";import type { WorkspaceMode } from "#/api/conversation-metadata-store";import type { CloudConnectionSource } from "#/services/cloud-funnel-analytics";-import { trackEvent } from "#/services/telemetry";+import { getCachedAgentServerVersion } from "#/api/agent-server-compatibility";+import { useActiveBackend } from "#/contexts/active-backend-context";+import AutomationService from "#/api/automation-service/automation-service.api";+import { getBackendTelemetryProperties } from "#/services/telemetry-context";+import { setTelemetryBackendContext, trackEvent } from "#/services/telemetry";/*** Hook that provides tracking functions with automatic data collection@@ -15,6 +20,51 @@ import { trackEvent } from "#/services/telemetry";*/export const useTracking = () => {const { data: settings } = useSettings();+ const activeBackend = useActiveBackend();+ const { backend } = activeBackend;+ const [automationSdkVersion, setAutomationSdkVersion] = React.useState<+ string | null+ >(null);++ React.useEffect(() => {+ if (typeof AutomationService.getSdkVersion !== "function") {+ setAutomationSdkVersion(null);+ return undefined;+ }++ let isMounted = true;+ setAutomationSdkVersion(null);+ void AutomationService.getSdkVersion().then((version) => {+ if (isMounted) {+ setAutomationSdkVersion(version);+ }+ });+ return () => {+ isMounted = false;+ };+ }, [+ activeBackend.orgId,+ backend.apiKey,+ backend.host,+ backend.id,+ backend.kind,+ ]);++ const getBackendTelemetryContext = React.useCallback(+ () => ({+ backendKind: backend.kind,+ agentServerVersion:+ backend.kind === "local"+ ? getCachedAgentServerVersion(backend.host)+ : null,+ automationSdkVersion: automationSdkVersion ?? null,+ }),+ [automationSdkVersion, backend.host, backend.kind],+ );++ React.useEffect(() => {+ setTelemetryBackendContext(getBackendTelemetryContext());+ }, [getBackendTelemetryContext]);// Common properties included in all tracking eventsconst commonProperties = {@@ -28,7 +78,8 @@ export const useTracking = () => {* backend is being added or switched.*/const track = (event: string, properties: Record<string, unknown> = {}) => {- void trackEvent(event, { ...properties, ...commonProperties });+ setTelemetryBackendContext(getBackendTelemetryContext());+ void trackEvent(event, { ...commonProperties, ...properties });};const trackLoginButtonClick = ({ provider }: { provider: Provider }) => {@@ -240,23 +291,25 @@ export const useTracking = () => {const trackBackendAdded = ({backendKind,connectionMethod,- isOpenhandsCloud,- isCustomHost,hasApiKey,source,+ agentServerVersion,+ backendVersion,}: {backendKind: BackendKind;connectionMethod: "manual" | "cloud_login";- isOpenhandsCloud: boolean;- isCustomHost: boolean;hasApiKey: boolean;source?: CloudConnectionSource;+ agentServerVersion?: string | null;+ backendVersion?: string | null;}) => {track("backend_added", {- backend_kind: backendKind,- connection_method: connectionMethod,- is_openhands_cloud: isOpenhandsCloud,- is_custom_host: isCustomHost,+ ...getBackendTelemetryProperties({+ backendKind,+ agentServerVersion,+ backendVersion,+ connectionMethod,+ }),has_api_key: hasApiKey,source,});diff --git a/src/services/cloud-funnel-analytics.ts b/src/services/cloud-funnel-analytics.tsindex 122b1ba2d3..0df7142d67 100644--- a/src/services/cloud-funnel-analytics.ts+++ b/src/services/cloud-funnel-analytics.ts@@ -1,5 +1,5 @@import { AGENT_CANVAS_CLIENT_SOURCE } from "#/api/client-source";-import { isOpenHandsCloudHost } from "#/api/device-flow-client";+import { getBackendTelemetryProperties } from "#/services/telemetry-context";import { trackEvent } from "#/services/telemetry";export type CloudConnectionSource =@@ -16,30 +16,35 @@ function trackCloudFunnelEvent(void trackEvent(event, properties);}-function hostClassification(host: string) {- const isOpenhandsCloud = isOpenHandsCloudHost(host);- return {- is_openhands_cloud: isOpenhandsCloud,- is_custom_host: !isOpenhandsCloud,- };+function cloudLoginBackendContext() {+ return getBackendTelemetryProperties({+ backendKind: "cloud",+ connectionMethod: "cloud_login",+ });+}++function cloudConversationBackendContext() {+ return getBackendTelemetryProperties({+ backendKind: "cloud",+ });}export function trackCloudDeviceAuthorizationStarted(- host: string,+ _host: string,source?: CloudConnectionSource,): void {trackCloudFunnelEvent("cloud_device_authorization_started", {- ...hostClassification(host),+ ...cloudLoginBackendContext(),source,});}export function trackCloudDeviceAuthorizationSucceeded(- host: string,+ _host: string,source?: CloudConnectionSource,): void {trackCloudFunnelEvent("cloud_device_authorization_succeeded", {- ...hostClassification(host),+ ...cloudLoginBackendContext(),source,});}@@ -49,6 +54,7 @@ export function trackCloudConversationReady(conversationId: string,): void {trackCloudFunnelEvent("cloud_conversation_ready", {+ ...cloudConversationBackendContext(),$insert_id: `${CLOUD_CONVERSATION_READY_INSERT_ID_PREFIX}:${taskId}`,task_id: taskId,conversation_id: conversationId,diff --git a/src/services/telemetry-context.ts b/src/services/telemetry-context.tsnew file mode 100644index 0000000000..1f4acf7af8--- /dev/null+++ b/src/services/telemetry-context.ts@@ -0,0 +1,43 @@+import type { BackendKind } from "#/api/backend-registry/types";++export const UNKNOWN_TELEMETRY_VERSION = "unknown";++export type BackendConnectionMethod = "manual" | "cloud_login";++export interface BackendTelemetryContextInput {+ backendKind?: BackendKind | null;+ agentServerVersion?: string | null;+ automationSdkVersion?: string | null;+ backendVersion?: string | null;+ connectionMethod?: BackendConnectionMethod;+}++function normalizeTelemetryVersion(version: string | null | undefined): string {+ const trimmed = version?.trim();+ return trimmed || UNKNOWN_TELEMETRY_VERSION;+}++export function getBackendTelemetryProperties({+ backendKind,+ agentServerVersion,+ automationSdkVersion,+ backendVersion,+ connectionMethod,+}: BackendTelemetryContextInput): Record<string, unknown> {+ const resolvedAgentServerVersion = normalizeTelemetryVersion(+ agentServerVersion ?? backendVersion,+ );+ const resolvedAutomationSdkVersion =+ normalizeTelemetryVersion(automationSdkVersion);+ const resolvedBackendVersion = normalizeTelemetryVersion(+ backendVersion ?? agentServerVersion,+ );++ return {+ backend_kind: backendKind ?? null,+ agent_server_version: resolvedAgentServerVersion,+ automation_sdk_version: resolvedAutomationSdkVersion,+ backend_version: resolvedBackendVersion,+ ...(connectionMethod ? { connection_method: connectionMethod } : {}),+ };+}diff --git a/src/services/telemetry.ts b/src/services/telemetry.tsindex 6b6a4b74ca..eab6c80ceb 100644--- a/src/services/telemetry.ts+++ b/src/services/telemetry.ts@@ -33,6 +33,10 @@ import {AGENT_CANVAS_CLIENT_SOURCE,AGENT_CANVAS_CLIENT_VERSION,} from "#/api/client-source";+import {+ getBackendTelemetryProperties,+ type BackendTelemetryContextInput,+} from "#/services/telemetry-context";const TELEMETRY_CONSENT_KEY = "openhands-telemetry-consent";const TELEMETRY_CONSENT_PENDING_CLOUD_SYNC_KEY =@@ -104,6 +108,14 @@ const CANVAS_EVENT_PROPERTIES = Object.freeze({package_version: packageJson.version,});+let telemetryBackendContext = getBackendTelemetryProperties({});++export function setTelemetryBackendContext(+ context: BackendTelemetryContextInput,+): void {+ telemetryBackendContext = getBackendTelemetryProperties(context);+}+function addCanvasEventProperties(event: CaptureResult | null,): CaptureResult | null {@@ -112,6 +124,7 @@ function addCanvasEventProperties(return {...event,properties: {+ ...telemetryBackendContext,...event.properties,...CANVAS_EVENT_PROPERTIES,},@@ -474,8 +487,11 @@ export async function setTelemetryConsent(}try {+ const previousConsent = getTelemetryConsent();+ const unchanged = previousConsent === consent;localStorage.setItem(TELEMETRY_CONSENT_KEY, consent);if (telemetryDisabled) return;+ if (unchanged) return;// Reuse an initialized client synchronously so a same-flush identify()// cannot run before consent is applied. Only the cold path awaits import.@@ -666,7 +682,7 @@ function markSessionSent(): void {/** Return the shared client only when a consented capture is safe to emit. */async function getPostHogForConsentedCapture(): Promise<PostHog | null> {- if (!isTelemetryEnabled()) return null;+ if (!isTelemetryEnabled() || getTelemetryConsent() !== "granted") return null;const posthog = await initializePostHogClient();if (!posthog || !isTelemetryEnabled()) return null;@@ -755,6 +771,7 @@ export async function clearTelemetryData(): Promise<void> {desiredTelemetryIdentity = null;desiredIdentityRevision += 1;appliedIdentityRevision = -1;+ telemetryBackendContext = getBackendTelemetryProperties({});try {if (posthogInstance) {