π OpenHands: AI-Driven Development
feat: forward automation telemetry context (#1917)
Rohit Malhotra22fe594133c0
diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.ymlindex 2a88367ec1..3f37c06a6b 100644--- a/.github/workflows/npm-publish.yml+++ b/.github/workflows/npm-publish.yml@@ -72,6 +72,21 @@ jobs:VITE_POSTHOG_API_KEY: ${{ vars.POSTHOG_PROD_KEY }}run: npm run build:lib+ - name: Bake package telemetry defaults+ env:+ # The CLI launcher runs after install, so it cannot read the build-time+ # Vite env baked into the browser bundle. Store the public production+ # key in the packaged defaults used by bin/agent-canvas.mjs.+ POSTHOG_API_KEY: ${{ vars.POSTHOG_PROD_KEY }}+ run: |+ node -e '+ const fs = require("fs");+ const path = "config/defaults.json";+ const defaults = JSON.parse(fs.readFileSync(path, "utf8"));+ defaults.telemetry.posthogApiKey = process.env.POSTHOG_API_KEY;+ fs.writeFileSync(path, `${JSON.stringify(defaults, null, 2)}\n`);+ '+- name: Verify package contentsrun: npm pack --dry-rundiff --git a/AGENTS.md b/AGENTS.mdindex abe576e294..342c63556c 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -34,6 +34,7 @@ One Canvas-owned PostHog client owns telemetry and app analytics.- `src/services/telemetry.ts` is the only module that accesses the named `agent-canvas` PostHog client. The name isolates Canvas identity, persistence, configuration, and consent from an embedding host's default singleton. React code declares Cloud user event context through `setTelemetryCloudContext()` and captures through the service; it never receives, identifies, or resets the SDK client.- `TelemetryProvider` configures bootstrap/runtime options and eagerly initializes the service. It does not expose PostHog context or maintain a second client lifecycle.+- The default PostHog key and direct ingestion host live in `config/defaults.json` under `telemetry`. Local launchers (`dev-with-automation`, `dev-static`, published binary path) and Docker default `AUTOMATION_POSTHOG_API_KEY` from explicit automation env, then `VITE_POSTHOG_API_KEY`, then that shared default key, so the automation backend can emit local consent-gated telemetry without extra user config. Keep `VITE_DO_NOT_TRACK=1` disabling the zero-config default.- Unconfigured source builds use the staging key and route through `https://z.openhands.dev`. Release workflows pass the public production key through `VITE_POSTHOG_API_KEY`. Precompiled npm consumers override `apiKey`, `apiHost`, and `uiHost` at runtime through `AgentServerUIProviders.analytics` or `configureTelemetry()`.- `setTelemetryConsent` is the only user-consent controller; `configureTelemetry(false)` is the embedding host's hard disable. An explicit first-run browser decision remains pending across local backends until `useSyncTelemetryConsent` persists it to Cloud; a stale/default backend value must not overwrite that newer choice during login or navigation. Once Cloud confirms the choice, backend `user_consents_to_analytics` changes are authoritative and mirrored to the client. No other hook or component should call `opt_in_capturing` / `opt_out_capturing` directly.- `subscribeTelemetryConsent` is the sole React-facing consent store. Hooks that render consent state must use `useSyncExternalStore`; do not mirror consent in component state or gate events outside `telemetry.ts`.diff --git a/__tests__/api/automation-service.test.ts b/__tests__/api/automation-service.test.tsindex ece78fedbe..aec847e6f0 100644--- a/__tests__/api/automation-service.test.ts+++ b/__tests__/api/automation-service.test.ts@@ -18,9 +18,14 @@ const {mockCallCloudProxy,mockGetActive,mockGetEffectiveLocal,+ mockGetTelemetryDistinctId,capturedInterceptors,} = vi.hoisted(() => {- const interceptors: Array<(config: InternalAxiosRequestConfig) => InternalAxiosRequestConfig> = [];+ const interceptors: Array<+ (+ config: InternalAxiosRequestConfig,+ ) => InternalAxiosRequestConfig | Promise<InternalAxiosRequestConfig>+ > = [];return {mockGet: vi.fn(),mockPatch: vi.fn(),@@ -29,6 +34,7 @@ const {mockCallCloudProxy: vi.fn(),mockGetActive: vi.fn(),mockGetEffectiveLocal: vi.fn(),+ mockGetTelemetryDistinctId: vi.fn(),capturedInterceptors: interceptors,};});@@ -43,7 +49,13 @@ vi.mock("axios", () => ({delete: mockDelete,interceptors: {request: {- use: (fn: (config: InternalAxiosRequestConfig) => InternalAxiosRequestConfig) => {+ use: (+ fn: (+ config: InternalAxiosRequestConfig,+ ) =>+ | InternalAxiosRequestConfig+ | Promise<InternalAxiosRequestConfig>,+ ) => {capturedInterceptors.push(fn);},},@@ -61,6 +73,10 @@ vi.mock("#/api/backend-registry/active-store", () => ({getEffectiveLocalBackend: mockGetEffectiveLocal,}));+vi.mock("#/services/telemetry", () => ({+ getTelemetryDistinctId: mockGetTelemetryDistinctId,+}));+// Import after mockingimport AutomationService from "#/api/automation-service/automation-service.api";@@ -72,6 +88,12 @@ const localBackend: Backend = {kind: "local",};+const expectedAutomationTelemetryHeaders = {+ "X-OpenHands-Client": "agent_canvas",+ "X-OpenHands-Client-Version": expect.any(String),+ "X-OpenHands-Telemetry-Distinct-Id": "ph-test-distinct-id",+};+const cloudBackend: Backend = {id: "cloud-1",name: "Production",@@ -133,6 +155,8 @@ describe("AutomationService", () => {mockGetActive.mockReturnValue({ backend: localBackend, orgId: null });mockGetEffectiveLocal.mockReset();mockGetEffectiveLocal.mockReturnValue(localBackend);+ mockGetTelemetryDistinctId.mockReset();+ mockGetTelemetryDistinctId.mockResolvedValue("ph-test-distinct-id");});describe("listAutomations", () => {@@ -358,7 +382,9 @@ describe("AutomationService", () => {expect(mockCallCloudProxy).toHaveBeenCalledWith({backend: cloudBackend,method: "GET",- path: "/api/automation/v1?limit=10&offset=5", });+ path: "/api/automation/v1?limit=10&offset=5",+ headers: expectedAutomationTelemetryHeaders,+ });expect(mockGet).not.toHaveBeenCalled();expect(result).toEqual(response);});@@ -371,7 +397,9 @@ describe("AutomationService", () => {expect(mockCallCloudProxy).toHaveBeenCalledWith({backend: cloudBackend,method: "GET",- path: "/api/automation/v1/abc", });+ path: "/api/automation/v1/abc",+ headers: expectedAutomationTelemetryHeaders,+ });expect(result).toEqual(mockAutomation);});@@ -383,7 +411,9 @@ describe("AutomationService", () => {expect(mockCallCloudProxy).toHaveBeenCalledWith({backend: cloudBackend,method: "POST",- path: "/api/automation/v1/abc/dispatch", });+ path: "/api/automation/v1/abc/dispatch",+ headers: expectedAutomationTelemetryHeaders,+ });expect(mockPost).not.toHaveBeenCalled();expect(result).toEqual(mockRun);});@@ -400,7 +430,9 @@ describe("AutomationService", () => {backend: cloudBackend,method: "PATCH",path: "/api/automation/v1/abc",- body: { enabled: false }, });+ body: { enabled: false },+ headers: expectedAutomationTelemetryHeaders,+ });expect(mockPatch).not.toHaveBeenCalled();expect(result).toEqual(updated);});@@ -413,7 +445,9 @@ describe("AutomationService", () => {expect(mockCallCloudProxy).toHaveBeenCalledWith({backend: cloudBackend,method: "DELETE",- path: "/api/automation/v1/abc", });+ path: "/api/automation/v1/abc",+ headers: expectedAutomationTelemetryHeaders,+ });expect(mockDelete).not.toHaveBeenCalled();});@@ -434,7 +468,9 @@ describe("AutomationService", () => {expect(mockCallCloudProxy).toHaveBeenCalledWith({backend: cloudBackend,method: "POST",- path: "/api/automation/v1/abc/dispatch", });+ path: "/api/automation/v1/abc/dispatch",+ headers: expectedAutomationTelemetryHeaders,+ });expect(mockPost).not.toHaveBeenCalled();expect(result).toEqual(run);});@@ -467,7 +503,7 @@ describe("AutomationService", () => {// registry rather than the build-time VITE_SESSION_API_KEY env var so that// the published npm package picks up the runtime-injected key (issue #829).describe("localAutomationAxios interceptor", () => {- it("sets X-Session-API-Key from the effective local backend apiKey", () => {+ it("sets telemetry headers and X-Session-API-Key from the effective local backend apiKey", async () => {const interceptor = capturedInterceptors[0];expect(interceptor).toBeDefined();@@ -478,15 +514,23 @@ describe("AutomationService", () => {mockGetEffectiveLocal.mockReturnValue(backendWithKey);const config = makeAxiosConfig();- interceptor(config);+ await interceptor(config);+ expect(config.headers.set).toHaveBeenCalledWith(+ "X-OpenHands-Client",+ "agent_canvas",+ );+ expect(config.headers.set).toHaveBeenCalledWith(+ "X-OpenHands-Telemetry-Distinct-Id",+ "ph-test-distinct-id",+ );expect(config.headers.set).toHaveBeenCalledWith("X-Session-API-Key","runtime-injected-key",);});- it("does not set X-Session-API-Key when backend apiKey is empty", () => {+ it("does not set X-Session-API-Key when backend apiKey is empty", async () => {const interceptor = capturedInterceptors[0];expect(interceptor).toBeDefined();@@ -496,12 +540,15 @@ describe("AutomationService", () => {});const config = makeAxiosConfig();- interceptor(config);+ await interceptor(config);- expect(config.headers.set).not.toHaveBeenCalled();+ expect(config.headers.set).not.toHaveBeenCalledWith(+ "X-Session-API-Key",+ expect.anything(),+ );});- it("sets baseURL from effective local backend host when not already set", () => {+ it("sets baseURL from effective local backend host when not already set", async () => {const interceptor = capturedInterceptors[0];expect(interceptor).toBeDefined();@@ -512,12 +559,12 @@ describe("AutomationService", () => {});const config = makeAxiosConfig();- interceptor(config);+ await interceptor(config);expect(config.baseURL).toBe("http://custom-host:9000");});- it("does not overwrite an already-set baseURL", () => {+ it("does not overwrite an already-set baseURL", async () => {const interceptor = capturedInterceptors[0];expect(interceptor).toBeDefined();@@ -528,7 +575,7 @@ describe("AutomationService", () => {});const config = makeAxiosConfig({ baseURL: "http://already-set:8000" });- interceptor(config);+ await interceptor(config);expect(config.baseURL).toBe("http://already-set:8000");});diff --git a/__tests__/hooks/use-sync-automation-telemetry-consent.test.ts b/__tests__/hooks/use-sync-automation-telemetry-consent.test.tsnew file mode 100644index 0000000000..e98e4c4896--- /dev/null+++ b/__tests__/hooks/use-sync-automation-telemetry-consent.test.ts@@ -0,0 +1,115 @@+import { act, renderHook } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";++const syncTelemetryConsentMock = vi.fn();+const state = {+ backendId: "local-1",+ backendKind: "local" as "local" | "cloud",+ backendHost: "http://localhost:8000",+ backendApiKey: "key-1",+ consent: "pending" as "pending" | "granted" | "denied",+};+const listeners = new Set<() => void>();++vi.mock("#/api/automation-service/automation-service.api", () => ({+ default: {+ syncTelemetryConsent: (...args: unknown[]) =>+ syncTelemetryConsentMock(...args),+ },+}));++vi.mock("#/contexts/active-backend-context", () => ({+ useActiveBackend: () => ({+ backend: {+ id: state.backendId,+ kind: state.backendKind,+ host: state.backendHost,+ apiKey: state.backendApiKey,+ },+ }),+}));++vi.mock("#/services/telemetry", () => ({+ getTelemetryConsent: () => state.consent,+ subscribeTelemetryConsent: (listener: () => void) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+}));++// Import after mocks so the module sees the stubbed dependencies.+import { useSyncAutomationTelemetryConsent } from "#/hooks/use-sync-automation-telemetry-consent";++describe("useSyncAutomationTelemetryConsent", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ syncTelemetryConsentMock.mockResolvedValue(undefined);+ listeners.clear();+ state.backendId = "local-1";+ state.backendHost = "http://localhost:8000";+ state.backendApiKey = "key-1";++ state.backendKind = "local";+ state.consent = "pending";+ });++ it("does not call the local automation consent API while consent is pending", () => {+ renderHook(() => useSyncAutomationTelemetryConsent());++ expect(syncTelemetryConsentMock).not.toHaveBeenCalled();+ });++ it("does not call the local automation consent API for cloud backends", () => {+ state.backendKind = "cloud";+ state.consent = "granted";++ renderHook(() => useSyncAutomationTelemetryConsent());++ expect(syncTelemetryConsentMock).not.toHaveBeenCalled();+ });++ it("syncs resolved consent for a local backend once", () => {+ state.consent = "granted";+ const { rerender } = renderHook(() => useSyncAutomationTelemetryConsent());+ rerender();++ expect(syncTelemetryConsentMock).toHaveBeenCalledTimes(1);+ expect(syncTelemetryConsentMock).toHaveBeenCalledWith("granted");+ });++ it("syncs when consent resolves after mount", () => {+ renderHook(() => useSyncAutomationTelemetryConsent());++ act(() => {+ state.consent = "denied";+ listeners.forEach((listener) => listener());+ });++ expect(syncTelemetryConsentMock).toHaveBeenCalledTimes(1);+ expect(syncTelemetryConsentMock).toHaveBeenCalledWith("denied");+ });++ it("syncs the current consent when switching between local backends", () => {+ state.consent = "granted";+ const { rerender } = renderHook(() => useSyncAutomationTelemetryConsent());++ state.backendId = "local-2";+ rerender();++ expect(syncTelemetryConsentMock).toHaveBeenCalledTimes(2);+ expect(syncTelemetryConsentMock).toHaveBeenNthCalledWith(1, "granted");+ expect(syncTelemetryConsentMock).toHaveBeenNthCalledWith(2, "granted");+ });++ it("resyncs when the active local backend connection changes", () => {+ state.consent = "granted";+ const { rerender } = renderHook(() => useSyncAutomationTelemetryConsent());++ state.backendApiKey = "key-2";+ rerender();++ expect(syncTelemetryConsentMock).toHaveBeenCalledTimes(2);+ expect(syncTelemetryConsentMock).toHaveBeenNthCalledWith(1, "granted");+ expect(syncTelemetryConsentMock).toHaveBeenNthCalledWith(2, "granted");+ });+});diff --git a/__tests__/scripts/dev-static.test.ts b/__tests__/scripts/dev-static.test.tsindex be3164e0a7..04f2784e1b 100644--- a/__tests__/scripts/dev-static.test.ts+++ b/__tests__/scripts/dev-static.test.ts@@ -4,18 +4,24 @@ import { buildAutomationBackendEnv } from "../../scripts/dev-static.mjs";describe("dev-static", () => {it("uses the same session key for both agent-server and automation backend auth", () => {- const env = buildAutomationBackendEnv({- agentServerPort: 18000,- ingressPort: 8000,- sessionApiKey: "shared-session-key",- stateDir: "/tmp/agent-canvas-state",- });+ const env = buildAutomationBackendEnv(+ {+ agentServerPort: 18000,+ ingressPort: 8000,+ sessionApiKey: "shared-session-key",+ stateDir: "/tmp/agent-canvas-state",+ },+ {},+ );// Both backends receive the same key valueexpect(env).toMatchObject({AUTOMATION_AGENT_SERVER_URL: "http://localhost:18000",AUTOMATION_AGENT_SERVER_API_KEY: "shared-session-key",AUTOMATION_LOCAL_API_KEY: "shared-session-key",+ AUTOMATION_POSTHOG_API_KEY:+ "phc_kBtz5nKmxVRRQ7HtPwr2QX9eMC5j65zE86QKocVNwb4U",+ AUTOMATION_POSTHOG_HOST: "https://us.i.posthog.com",});});});diff --git a/__tests__/scripts/dev-with-automation.test.ts b/__tests__/scripts/dev-with-automation.test.tsindex bfddad4628..0921ce9e8b 100644--- a/__tests__/scripts/dev-with-automation.test.ts+++ b/__tests__/scripts/dev-with-automation.test.ts@@ -17,6 +17,7 @@ import { describe, expect, it, afterEach } from "vitest";import {buildAgentServerAutomationEnv,buildAutomationCommand,+ buildAutomationTelemetryEnv,buildConfig,buildRouteArgs,buildViteBackendEnv,@@ -132,6 +133,46 @@ describe("buildAgentServerAutomationEnv", () => {});});+describe("buildAutomationTelemetryEnv", () => {+ it("provides the shared frontend PostHog key to automation by default", () => {+ expect(buildAutomationTelemetryEnv({})).toEqual({+ AUTOMATION_POSTHOG_API_KEY:+ "phc_kBtz5nKmxVRRQ7HtPwr2QX9eMC5j65zE86QKocVNwb4U",+ AUTOMATION_POSTHOG_HOST: "https://us.i.posthog.com",+ });+ });++ it("prefers explicit automation telemetry settings", () => {+ expect(+ buildAutomationTelemetryEnv({+ AUTOMATION_POSTHOG_API_KEY: "phc_auto",+ AUTOMATION_POSTHOG_HOST: "https://auto.example",+ VITE_POSTHOG_API_KEY: "phc_frontend",+ VITE_POSTHOG_HOST: "https://frontend.example",+ }),+ ).toEqual({+ AUTOMATION_POSTHOG_API_KEY: "phc_auto",+ AUTOMATION_POSTHOG_HOST: "https://auto.example",+ });+ });++ it("uses explicit frontend telemetry settings when automation settings are absent", () => {+ expect(+ buildAutomationTelemetryEnv({+ VITE_POSTHOG_API_KEY: "phc_frontend",+ VITE_POSTHOG_HOST: "https://frontend.example",+ }),+ ).toEqual({+ AUTOMATION_POSTHOG_API_KEY: "phc_frontend",+ AUTOMATION_POSTHOG_HOST: "https://frontend.example",+ });+ });++ it("does not default automation telemetry when do-not-track is enabled", () => {+ expect(buildAutomationTelemetryEnv({ VITE_DO_NOT_TRACK: "1" })).toEqual({});+ });+});+describe("buildConfig", () => {const servers: net.Server[] = [];const keyDirs: string[] = [];diff --git a/__tests__/services/telemetry.test.ts b/__tests__/services/telemetry.test.tsindex cd2493834b..11383c6bb1 100644--- a/__tests__/services/telemetry.test.ts+++ b/__tests__/services/telemetry.test.ts@@ -18,6 +18,7 @@ const mockPosthog = {get_property: vi.fn((property: string) =>property === "$user_id" ? identifiedUserId : undefined,),+ get_distinct_id: vi.fn(() => "ph-test-distinct-id"),reset: vi.fn(() => {identifiedUserId = undefined;}),@@ -35,6 +36,7 @@ import {clearPendingCloudTelemetryConsent,configureTelemetry,getTelemetryConsent,+ getTelemetryDistinctId,getPendingCloudTelemetryConsent,initializePostHogClient,setTelemetryConsent,@@ -68,6 +70,7 @@ describe("Telemetry Service", () => {vi.clearAllMocks();identifiedUserId = undefined;mockPosthog.has_opted_out_capturing.mockReturnValue(false);+ mockPosthog.get_distinct_id.mockReturnValue("ph-test-distinct-id");setTelemetryBackendContext({});});@@ -380,6 +383,20 @@ describe("Telemetry Service", () => {});});+ describe("getTelemetryDistinctId", () => {+ it("returns null when consent is not granted", async () => {+ await expect(getTelemetryDistinctId()).resolves.toBeNull();+ });++ it("returns the PostHog distinct ID when consent is granted", async () => {+ await setTelemetryConsent("granted");++ await expect(getTelemetryDistinctId()).resolves.toBe(+ "ph-test-distinct-id",+ );+ });+ });+describe("trackEvent", () => {it("does not send event when consent is not granted", async () => {await trackEvent("test_event", { foo: "bar" });diff --git a/config/defaults.json b/config/defaults.jsonindex 05562964f8..cdfa640411 100644--- a/config/defaults.json+++ b/config/defaults.json@@ -3,7 +3,7 @@"versions": {"agentServer": "1.37.0","agentCanvas": "1.5.2",- "automation": "1.2.0"+ "automation": "1.3.0"},"compatibility": {"minimumAgentServer": "1.28.0"@@ -33,5 +33,9 @@"automation": "openhands-automation","tools": "openhands-tools","workspace": "openhands-workspace"+ },+ "telemetry": {+ "posthogApiKey": "phc_kBtz5nKmxVRRQ7HtPwr2QX9eMC5j65zE86QKocVNwb4U",+ "posthogHost": "https://us.i.posthog.com"}}diff --git a/docker/Dockerfile b/docker/Dockerfileindex 8470d41c84..b66484be62 100644--- a/docker/Dockerfile+++ b/docker/Dockerfile@@ -61,6 +61,8 @@ RUN node -e " \'CONFIG_BASH_EVENTS=' + c.paths.bashEvents, \'CONFIG_AUTOMATION_DB=' + c.paths.automationDb, \'CONFIG_CANVAS_BASE_PATH=' + c.paths.canvasBasePath, \+ 'CONFIG_POSTHOG_API_KEY=' + c.telemetry.posthogApiKey, \+ 'CONFIG_POSTHOG_HOST=' + c.telemetry.posthogHost, \]; \require('fs').writeFileSync('/tmp/defaults.env', lines.join('\n') + '\n'); \"@@ -73,6 +75,7 @@ ARG AGENT_SERVER_SDK_GIT_REF=""ARG OPENHANDS_BUILD_GIT_SHA=unknownARG OPENHANDS_BUILD_GIT_REF=unknownARG VITE_BASE_PATH="/canvas"+ARG VITE_POSTHOG_API_KEY=""ARG AGENT_CANVAS_VERSION=devLABEL org.opencontainers.image.title="agent-canvas"@@ -84,6 +87,7 @@ LABEL org.opencontainers.image.revision="${OPENHANDS_BUILD_GIT_SHA}"ENV AGENT_CANVAS_BUILD_GIT_SHA=${OPENHANDS_BUILD_GIT_SHA}ENV AGENT_CANVAS_BUILD_GIT_REF=${OPENHANDS_BUILD_GIT_REF}ENV AGENT_CANVAS_BASE_PATH=${VITE_BASE_PATH}+ENV VITE_POSTHOG_API_KEY=${VITE_POSTHOG_API_KEY}USER rootdiff --git a/docker/entrypoint.sh b/docker/entrypoint.shindex d5e709fe71..3c74317e17 100644--- a/docker/entrypoint.sh+++ b/docker/entrypoint.sh@@ -114,6 +114,16 @@ export OPENHANDS_AUTOMATION_API_KEY="${OPENHANDS_AUTOMATION_API_KEY:-${EFFECTIVEexport AUTOMATION_LOCAL_API_KEY="${AUTOMATION_LOCAL_API_KEY:-${EFFECTIVE_SESSION_KEY}}"export AUTOMATION_AGENT_SERVER_API_KEY="${AUTOMATION_AGENT_SERVER_API_KEY:-${EFFECTIVE_SESSION_KEY}}"export OPENHANDS_REMOTE_WS_READY_REQUIRED="${OPENHANDS_REMOTE_WS_READY_REQUIRED:-false}"+if [ -z "${AUTOMATION_POSTHOG_API_KEY:-}" ]; then+ if [ -n "${VITE_POSTHOG_API_KEY:-}" ]; then+ export AUTOMATION_POSTHOG_API_KEY="$VITE_POSTHOG_API_KEY"+ elif [ "${VITE_DO_NOT_TRACK:-}" != "1" ]; then+ export AUTOMATION_POSTHOG_API_KEY="${CONFIG_POSTHOG_API_KEY:-}"+ fi+fi+if [ -n "${AUTOMATION_POSTHOG_API_KEY:-}" ]; then+ export AUTOMATION_POSTHOG_HOST="${AUTOMATION_POSTHOG_HOST:-${VITE_POSTHOG_HOST:-${CONFIG_POSTHOG_HOST:-}}}"+fi# AGENT_SERVER_URL β needed by automation sandbox callbacks.export AGENT_SERVER_URL="${AGENT_SERVER_URL:-http://127.0.0.1:${AGENT_SERVER_PORT}}"diff --git a/scripts/dev-static.mjs b/scripts/dev-static.mjsindex c274c3bfcb..18f0be291b 100644--- a/scripts/dev-static.mjs+++ b/scripts/dev-static.mjs@@ -60,6 +60,7 @@ import {import {buildAgentServerAutomationEnv,buildAutomationCommand,+ buildAutomationTelemetryEnv,buildConfig,} from "./dev-with-automation.mjs";@@ -323,7 +324,7 @@ function startAgentServer(config) {);}-function buildAutomationBackendEnv(config) {+function buildAutomationBackendEnv(config, env = process.env) {// Both backends share the same session API key value.return {AUTOMATION_AGENT_SERVER_URL: `http://localhost:${config.agentServerPort}`,@@ -332,6 +333,7 @@ function buildAutomationBackendEnv(config) {AUTOMATION_BASE_URL: `http://localhost:${config.ingressPort}`,AUTOMATION_WORKSPACE_BASE: join(config.stateDir, "workspaces"),AUTOMATION_LOCAL_API_KEY: config.sessionApiKey,+ ...buildAutomationTelemetryEnv(env),AUTOMATION_CORS_ORIGINS: `http://localhost:${config.ingressPort},http://127.0.0.1:${config.ingressPort},http://localhost:3001,http://127.0.0.1:3001`,FILE_STORE: "local",LOCAL_STORAGE_PATH: join(config.stateDir, "storage"),diff --git a/scripts/dev-with-automation.mjs b/scripts/dev-with-automation.mjsindex e64060c161..cc52a35320 100644--- a/scripts/dev-with-automation.mjs+++ b/scripts/dev-with-automation.mjs@@ -60,7 +60,6 @@ import {buildNpmScriptCommand,buildRuntimeServicesInfo,formatMissingUvxGuidance,- getOrCreatePersistedApiKey,validateFrontendDependencies,validateLocalAgentServerPath,} from "./dev-safe.mjs";@@ -87,6 +86,8 @@ const DEFAULT_AUTOMATION_VERSION = SHARED_DEFAULTS.versions.automation;const DEFAULT_AUTOMATION_SDK_VERSION = SHARED_DEFAULTS.versions.agentServer;const DEFAULT_BACKEND_PORT = SHARED_DEFAULTS.ports.agentServer;const DEFAULT_AUTOMATION_PORT = SHARED_DEFAULTS.ports.automation;+const DEFAULT_POSTHOG_API_KEY = SHARED_DEFAULTS.telemetry.posthogApiKey;+const DEFAULT_POSTHOG_HOST = SHARED_DEFAULTS.telemetry.posthogHost;// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ// Terminal Styling@@ -623,7 +624,7 @@ function spawnService(name, command, args, options = {}) {emitServiceLog(name, `failed to start: ${error.message}`, "error");});- proc.on("exit", (code, signal) => {+ proc.on("exit", (code, _signal) => {if (code !== 0 && code !== null && !shuttingDown) {logService(name, `Exited with code ${code}`, c.red);emitServiceLog(name, `exited with code ${code}`, "error");@@ -753,6 +754,24 @@ function buildAgentServerAutomationEnv(config) {};}+function buildAutomationTelemetryEnv(env = process.env) {+ const telemetryDisabled = env.VITE_DO_NOT_TRACK === "1";+ const apiKey =+ env.AUTOMATION_POSTHOG_API_KEY ||+ env.VITE_POSTHOG_API_KEY ||+ (telemetryDisabled ? "" : DEFAULT_POSTHOG_API_KEY);++ if (!apiKey) return {};++ return {+ AUTOMATION_POSTHOG_API_KEY: apiKey,+ AUTOMATION_POSTHOG_HOST:+ env.AUTOMATION_POSTHOG_HOST ||+ env.VITE_POSTHOG_HOST ||+ DEFAULT_POSTHOG_HOST,+ };+}+function startAgentServer(config) {logService("agent-server",@@ -884,6 +903,7 @@ function startAutomationBackend(config) {join(config.stateDir, "workspaces"),// Session API key for self-hosted auth β shared with agent-server via X-Session-API-Key headerAUTOMATION_LOCAL_API_KEY: config.sessionApiKey,+ ...buildAutomationTelemetryEnv(),// KV store secret β required for automations to use the built-in// key-value store for state persistence between runs. Used for JWT// signing and value encryption.@@ -1132,7 +1152,8 @@ function printBanner(config) {// padEnd counts invisible ANSI escape bytes as visible characters, so we// compute the visible length separately and pad with spaces accordingly.- const ansiRe = /\x1b\[[0-9;]*m/g;+ const ansiEscape = String.fromCharCode(27);+ const ansiRe = new RegExp(`${ansiEscape}\\[[0-9;]*m`, "g");const ansiPadEnd = (str, targetVisible) => {const visible = str.replace(ansiRe, "").length;return str + " ".repeat(Math.max(0, targetVisible - visible));@@ -1474,6 +1495,7 @@ function startStaticFrontend(config, staticDir) {export {buildAgentServerAutomationEnv,buildAutomationCommand,+ buildAutomationTelemetryEnv,buildConfig,buildRouteArgs,buildViteBackendEnv,diff --git a/src/api/automation-service/automation-service.api.test.ts b/src/api/automation-service/automation-service.api.test.tsindex e85500aea7..0911124a23 100644--- a/src/api/automation-service/automation-service.api.test.ts+++ b/src/api/automation-service/automation-service.api.test.ts@@ -7,7 +7,13 @@ import type { Backend } from "#/api/backend-registry/types";import type { Automation, AutomationSpec } from "#/types/automation";import AutomationService from "./automation-service.api";-const { localAxios, callCloudProxy } = vi.hoisted(() => ({+const {+ localAxios,+ callCloudProxy,+ getTelemetryConsent,+ getTelemetryDistinctId,+ getTelemetryDistinctIdForConsentSync,+} = vi.hoisted(() => ({localAxios: {interceptors: { request: { use: vi.fn() } },get: vi.fn(),@@ -16,6 +22,9 @@ const { localAxios, callCloudProxy } = vi.hoisted(() => ({delete: vi.fn(),},callCloudProxy: vi.fn(),+ getTelemetryConsent: vi.fn(),+ getTelemetryDistinctId: vi.fn(),+ getTelemetryDistinctIdForConsentSync: vi.fn(),}));vi.mock("axios", () => ({@@ -29,6 +38,12 @@ vi.mock("#/api/cloud/proxy", () => ({callCloudProxy,}));+vi.mock("#/services/telemetry", () => ({+ getTelemetryConsent,+ getTelemetryDistinctId,+ getTelemetryDistinctIdForConsentSync,+}));+const localBackend: Backend = {id: "local-test",name: "Local test backend",@@ -106,7 +121,7 @@ describe("AutomationService.getSdkVersion", () => {backend: cloudBackend,method: "GET",path: "/api/automation/sdk-version",- headers: { "X-Org-Id": "org-1" },+ headers: expect.objectContaining({ "X-Org-Id": "org-1" }),timeoutSeconds: 5,}),);@@ -119,6 +134,59 @@ describe("AutomationService.getSdkVersion", () => {});});+describe("AutomationService.syncTelemetryConsent", () => {+ beforeEach(() => {+ setRegisteredBackends([localBackend]);+ setActiveSelection({ backendId: localBackend.id });+ getTelemetryConsent.mockReturnValue("pending");+ getTelemetryDistinctIdForConsentSync.mockResolvedValue("ph-fe-sync");+ localAxios.post.mockResolvedValue({ data: { consent_granted: true } });+ });++ afterEach(() => {+ setActiveSelection(null);+ setRegisteredBackends([]);+ vi.clearAllMocks();+ });++ it("posts local telemetry consent with the frontend PostHog distinct ID", async () => {+ await AutomationService.syncTelemetryConsent("granted");++ expect(localAxios.post).toHaveBeenCalledWith(+ "/api/automation/v1/telemetry/consent",+ {+ consent_granted: true,+ frontend_distinct_id: "ph-fe-sync",+ },+ { timeout: 5000 },+ );+ });++ it("uses the current telemetry consent when no explicit value is supplied", async () => {+ getTelemetryConsent.mockReturnValue("denied");++ await AutomationService.syncTelemetryConsent();++ expect(localAxios.post).toHaveBeenCalledWith(+ "/api/automation/v1/telemetry/consent",+ {+ consent_granted: false,+ frontend_distinct_id: "ph-fe-sync",+ },+ { timeout: 5000 },+ );+ });++ it("skips cloud backends because cloud consent is handled by auth", async () => {+ setRegisteredBackends([cloudBackend]);+ setActiveSelection({ backendId: cloudBackend.id, orgId: "org-1" });++ await AutomationService.syncTelemetryConsent("granted");++ expect(localAxios.post).not.toHaveBeenCalled();+ });+});+describe("AutomationService.createAutomation", () => {beforeEach(() => {setRegisteredBackends([localBackend]);@@ -162,7 +230,9 @@ describe("AutomationService.createAutomation", () => {},{baseURL: localBackend.host,- headers: { "X-Session-API-Key": localBackend.apiKey },+ headers: expect.objectContaining({+ "X-Session-API-Key": localBackend.apiKey,+ }),},);expect(localAxios.patch).toHaveBeenCalledWith(@@ -177,7 +247,9 @@ describe("AutomationService.createAutomation", () => {},{baseURL: localBackend.host,- headers: { "X-Session-API-Key": localBackend.apiKey },+ headers: expect.objectContaining({+ "X-Session-API-Key": localBackend.apiKey,+ }),},);expect(created.enabled).toBe(false);@@ -232,7 +304,7 @@ describe("AutomationService.createAutomation", () => {method: "POST",path: "/api/automation/v1/preset/plugin",body: expect.objectContaining({ name: spec.name }),- headers: { "X-Org-Id": "org-1" },+ headers: expect.objectContaining({ "X-Org-Id": "org-1" }),}),);expect(callCloudProxy).toHaveBeenNthCalledWith(@@ -242,7 +314,7 @@ describe("AutomationService.createAutomation", () => {method: "PATCH",path: "/api/automation/v1/created-automation",body: expect.objectContaining({ enabled: false }),- headers: { "X-Org-Id": "org-1" },+ headers: expect.objectContaining({ "X-Org-Id": "org-1" }),}),);expect(created.enabled).toBe(false);@@ -260,7 +332,9 @@ describe("AutomationService.createAutomation", () => {"/api/automation/v1/created-automation",{baseURL: localBackend.host,- headers: { "X-Session-API-Key": localBackend.apiKey },+ headers: expect.objectContaining({+ "X-Session-API-Key": localBackend.apiKey,+ }),},);});diff --git a/src/api/automation-service/automation-service.api.ts b/src/api/automation-service/automation-service.api.tsindex 73e1d81c34..ec23fddc35 100644--- a/src/api/automation-service/automation-service.api.ts+++ b/src/api/automation-service/automation-service.api.ts@@ -1,4 +1,10 @@import axios from "axios";+import {+ getTelemetryConsent,+ getTelemetryDistinctId,+ getTelemetryDistinctIdForConsentSync,+ type TelemetryConsent,+} from "#/services/telemetry";import type {Automation,AutomationRun,@@ -14,6 +20,10 @@ import {} from "../backend-registry/active-store";import { NoBackendAvailableError } from "../agent-server-client-options";import { callCloudProxy } from "../cloud/proxy";+import {+ AGENT_CANVAS_CLIENT_HEADERS,+ OPENHANDS_TELEMETRY_DISTINCT_ID_HEADER,+} from "../client-source";const AUTOMATION_BASE_PATH = "/api/automation";@@ -35,7 +45,25 @@ type AutomationSdkVersionResponse =// header for consistency.const localAutomationAxios = axios.create();-localAutomationAxios.interceptors.request.use((config) => {+async function buildAutomationRequestHeaders(+ extraHeaders: Record<string, string> = {},+): Promise<Record<string, string>> {+ const telemetryDistinctId = await getTelemetryDistinctId();+ return {+ ...AGENT_CANVAS_CLIENT_HEADERS,+ ...(telemetryDistinctId+ ? { [OPENHANDS_TELEMETRY_DISTINCT_ID_HEADER]: telemetryDistinctId }+ : {}),+ ...extraHeaders,+ };+}++localAutomationAxios.interceptors.request.use(async (config) => {+ const requestHeaders = await buildAutomationRequestHeaders();+ Object.entries(requestHeaders).forEach(([name, value]) => {+ config.headers.set(name, value);+ });+// Import uses an explicit baseURL/header pair so its POST, PATCH, and// cleanup stay pinned to the backend selected when the mutation started.if (config.baseURL) return config;@@ -151,19 +179,40 @@ function buildCreateAutomationRequest(spec: AutomationSpec) {};}-function buildPinnedLocalConfig(backend: Backend) {+async function buildPinnedLocalConfig(backend: Backend) {const apiKey = backend.apiKey.trim();return {baseURL: backend.host,- ...(apiKey && { headers: { "X-Session-API-Key": apiKey } }),+ headers: await buildAutomationRequestHeaders(+ apiKey ? { "X-Session-API-Key": apiKey } : {},+ ),};}-function buildPinnedCloudHeaders(active: ResolvedActiveBackend) {- return active.orgId ? { "X-Org-Id": active.orgId } : undefined;+async function buildPinnedCloudHeaders(active: ResolvedActiveBackend) {+ return buildAutomationRequestHeaders(+ active.orgId ? { "X-Org-Id": active.orgId } : {},+ );}class AutomationService {+ static async syncTelemetryConsent(+ consent: TelemetryConsent = getTelemetryConsent(),+ ): Promise<void> {+ const active = getActiveBackend();+ if (active.backend.kind !== "local") return;++ const frontendDistinctId = await getTelemetryDistinctIdForConsentSync();+ await localAutomationAxios.post(+ `${AUTOMATION_BASE_PATH}/v1/telemetry/consent`,+ {+ consent_granted: consent === "granted",+ frontend_distinct_id: frontendDistinctId,+ },+ { timeout: 5000 },+ );+ }+static async getSdkVersion(): Promise<string | null> {const active = getActiveBackend();const path = `${AUTOMATION_BASE_PATH}/sdk-version`;@@ -175,7 +224,7 @@ class AutomationService {backend: active.backend,method: "GET",path,- headers: buildPinnedCloudHeaders(active),+ headers: await buildPinnedCloudHeaders(active),timeoutSeconds: 5,});} else {@@ -203,6 +252,7 @@ class AutomationService {backend: active,method: "GET",path: `${AUTOMATION_BASE_PATH}/v1?${buildPaginationQuery(limit, offset)}`,+ headers: await buildAutomationRequestHeaders(),});}@@ -229,6 +279,7 @@ class AutomationService {backend: active,method: "GET",path,+ headers: await buildAutomationRequestHeaders(),});}@@ -247,13 +298,13 @@ class AutomationService {method: "POST",path,body,- headers: buildPinnedCloudHeaders(active),+ headers: await buildPinnedCloudHeaders(active),});} else {const { data } = await localAutomationAxios.post<Automation>(path,body,- buildPinnedLocalConfig(active.backend),+ await buildPinnedLocalConfig(active.backend),);created = data;}@@ -271,14 +322,14 @@ class AutomationService {method: "PATCH",path: updatePath,body: updateBody,- headers: buildPinnedCloudHeaders(active),+ headers: await buildPinnedCloudHeaders(active),});}const { data } = await localAutomationAxios.patch<Automation>(updatePath,updateBody,- buildPinnedLocalConfig(active.backend),+ await buildPinnedLocalConfig(active.backend),);return data;} catch (updateError) {@@ -288,12 +339,12 @@ class AutomationService {backend: active.backend,method: "DELETE",path: updatePath,- headers: buildPinnedCloudHeaders(active),+ headers: await buildPinnedCloudHeaders(active),});} else {await localAutomationAxios.delete(updatePath,- buildPinnedLocalConfig(active.backend),+ await buildPinnedLocalConfig(active.backend),);}} catch (cleanupError) {@@ -319,6 +370,7 @@ class AutomationService {method: "PATCH",path,body: body as Record<string, unknown>,+ headers: await buildAutomationRequestHeaders(),});}@@ -335,6 +387,7 @@ class AutomationService {backend: active,method: "DELETE",path,+ headers: await buildAutomationRequestHeaders(),});return;}@@ -351,6 +404,7 @@ class AutomationService {backend: active,method: "POST",path,+ headers: await buildAutomationRequestHeaders(),});}@@ -371,6 +425,7 @@ class AutomationService {backend: active,method: "GET",path: `${basePath}?${buildPaginationQuery(limit, offset)}`,+ headers: await buildAutomationRequestHeaders(),});}@@ -407,6 +462,7 @@ class AutomationService {method: "GET",path,responseType: "blob",+ headers: await buildAutomationRequestHeaders(),});} else {const { data } = await localAutomationAxios.get<Blob>(path, {@@ -435,6 +491,7 @@ class AutomationService {path,// Fail fast, matching the local branch's 5s timeout below.timeoutSeconds: 5,+ headers: await buildAutomationRequestHeaders(),});return response;}diff --git a/src/api/client-source.ts b/src/api/client-source.tsindex 9a3d4e383b..48443ef8be 100644--- a/src/api/client-source.ts+++ b/src/api/client-source.ts@@ -9,7 +9,12 @@ export const AGENT_CANVAS_CLIENT_VERSION = packageJson.version;* Cloud ingress can retain these headers as facets without logging request* bodies, API keys, device codes, or conversation content.*/+export const OPENHANDS_CLIENT_HEADER = "X-OpenHands-Client";+export const OPENHANDS_CLIENT_VERSION_HEADER = "X-OpenHands-Client-Version";+export const OPENHANDS_TELEMETRY_DISTINCT_ID_HEADER =+ "X-OpenHands-Telemetry-Distinct-Id";+export const AGENT_CANVAS_CLIENT_HEADERS: Readonly<Record<string, string>> = {- "X-OpenHands-Client": AGENT_CANVAS_CLIENT_SOURCE,- "X-OpenHands-Client-Version": AGENT_CANVAS_CLIENT_VERSION,+ [OPENHANDS_CLIENT_HEADER]: AGENT_CANVAS_CLIENT_SOURCE,+ [OPENHANDS_CLIENT_VERSION_HEADER]: AGENT_CANVAS_CLIENT_VERSION,};diff --git a/src/hooks/use-sync-automation-telemetry-consent.ts b/src/hooks/use-sync-automation-telemetry-consent.tsnew file mode 100644index 0000000000..1b2ee294f0--- /dev/null+++ b/src/hooks/use-sync-automation-telemetry-consent.ts@@ -0,0 +1,27 @@+import React from "react";+import AutomationService from "#/api/automation-service/automation-service.api";+import { useActiveBackend } from "#/contexts/active-backend-context";+import {+ getTelemetryConsent,+ subscribeTelemetryConsent,+} from "#/services/telemetry";++export function useSyncAutomationTelemetryConsent() {+ const { backend } = useActiveBackend();+ const consent = React.useSyncExternalStore(+ subscribeTelemetryConsent,+ getTelemetryConsent,+ () => "pending" as const,+ );+ const lastSyncKeyRef = React.useRef<string | null>(null);++ React.useEffect(() => {+ if (backend.kind !== "local" || consent === "pending") return;++ const syncKey = `${backend.id}:${backend.host}:${backend.apiKey ?? ""}:${consent}`;+ if (lastSyncKeyRef.current === syncKey) return;+ lastSyncKeyRef.current = syncKey;++ void AutomationService.syncTelemetryConsent(consent).catch(() => {});+ }, [backend.apiKey, backend.host, backend.id, backend.kind, consent]);+}diff --git a/src/routes/root-layout.tsx b/src/routes/root-layout.tsxindex 35e5f2411e..f5121d245d 100644--- a/src/routes/root-layout.tsx+++ b/src/routes/root-layout.tsx@@ -15,6 +15,8 @@ import { SidebarMobileMenuBar } from "#/components/features/sidebar/sidebar-mobiimport { useSettings } from "#/hooks/query/use-settings";import { useEnsureActiveProfile } from "#/hooks/use-ensure-active-profile";import { useSyncTelemetryConsent } from "#/hooks/use-sync-telemetry-consent";+import { useSyncAutomationTelemetryConsent } from "#/hooks/use-sync-automation-telemetry-consent";+import { useTelemetryIdentity } from "#/hooks/use-telemetry-identity";import { LoadingSpinner } from "#/components/shared/loading-spinner";import { useAppTitle } from "#/hooks/use-app-title";@@ -75,6 +77,8 @@ export default function MainApp() {const { data: settings } = useSettings();const config = useConfig();+ useSyncAutomationTelemetryConsent();+useSyncTelemetryConsent();useTelemetryIdentity();// Local-mode policy: keep a profile active so a usable LLM is always selected.diff --git a/src/services/telemetry.ts b/src/services/telemetry.tsindex 265fd4d658..fba8c70366 100644--- a/src/services/telemetry.ts+++ b/src/services/telemetry.ts@@ -28,6 +28,8 @@import type { BootstrapConfig, CaptureResult, PostHog } from "posthog-js";import { getLockedCloudAuthMode } from "#/api/agent-server-config";+import defaults from "../../config/defaults.json";+import packageJson from "../../package.json";import {AGENT_CANVAS_CLIENT_SOURCE,@@ -50,10 +52,9 @@ const POSTHOG_INSTANCE_NAME = "agent-canvas";// Unconfigured source builds use staging. Production release workflows pass// VITE_POSTHOG_API_KEY explicitly for both the app and library artifacts.-const POSTHOG_STAGING_KEY = "phc_kBtz5nKmxVRRQ7HtPwr2QX9eMC5j65zE86QKocVNwb4U";const DEFAULT_POSTHOG_API_KEY: string =(import.meta.env.VITE_POSTHOG_API_KEY as string | undefined) ||- POSTHOG_STAGING_KEY;+ defaults.telemetry.posthogApiKey;// Default to OpenHands' reverse proxy to bypass ad blockers.// The proxy at z.openhands.dev routes to PostHog's US region.@@ -657,6 +658,22 @@ export async function trackSessionStart(): Promise<void> {markSessionSent();}+/** Return the active PostHog distinct ID when consent allows capture. */+export async function getTelemetryDistinctId(): Promise<string | null> {+ const posthog = await getPostHogForConsentedCapture();+ return posthog?.get_distinct_id?.() ?? null;+}++/** Return the PostHog distinct ID for local consent sync without emitting capture. */+export async function getTelemetryDistinctIdForConsentSync(): Promise<+ string | null+> {+ if (!isBrowser() || telemetryDisabled || isDoNotTrackEnabled()) return null;++ const posthog = await initializePostHogClient();+ return posthog?.get_distinct_id?.() ?? null;+}+/*** Track a custom event (respects consent).*/