π OpenHands: AI-Driven Development
feat: instrument the Canvas Cloud funnel (#1828)
Graham Neubige9d54fb29f9b
diff --git a/AGENTS.md b/AGENTS.mdindex 73d8bbfc27..80a948acc2 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -32,13 +32,14 @@ by a human, report the exact validator error rather than editing them yourself.Two distinct PostHog systems exist. **Never mix them at a call site.**-### System 1 β `telemetry.ts` (library-level, anonymous)-- **Purpose**: anonymous npm-consumer telemetry (`canvas_install`, `canvas_new_session`)+### System 1 β `telemetry.ts` (Canvas-level, anonymous)+- **Purpose**: anonymous npm-consumer telemetry and the consented OSS Cloud funnel- **Keys**: hardcoded staging/prod keys in `telemetry.ts`; routed through `https://z.openhands.dev`+- **Isolation**: the named `agent-canvas` PostHog instance has its own persistence and consent namespaces; never replace it with the default singleton- **Consent**: `localStorage["openhands-telemetry-consent"]` via `useTelemetry` / `TelemetryConsentBanner`- **`canvas_install`** fires once, pre-consent, per installation- **Exports**: `trackEvent`, `useTelemetry`, `TelemetryConsentBanner`, etc. from `src/lib/index.ts` β these are the **public library API for npm consumers**-- **Rule**: Do NOT import `trackEvent` from `#/services/telemetry` in app routes or components+- **Rule**: app routes/components use the typed functions in `cloud-funnel-analytics.ts`; do not call `trackEvent` directly### System 2 β `useTracking` hook (app-level, identified)- **Purpose**: product analytics for app behaviour events@@ -48,6 +49,11 @@ Two distinct PostHog systems exist. **Never mix them at a call site.**- **`commonProperties`** (`current_url`, `user_email`) are attached automatically by the hook- **Rule**: Do NOT use raw `usePostHog()` + `posthog.capture()` in components β always go through `useTracking`+### Cloud funnel observability+- OAuth device authorization and Cloud conversation-start requests include the coarse `X-OpenHands-Client: agent_canvas` and `X-OpenHands-Client-Version` headers from `src/api/client-source.ts`. Never put device codes, API keys, conversation content, raw hosts, or other user data in these headers.+- Production ingress must retain those two headers as structured Datadog facets before source-specific operational queries will work.+- The consented OSS funnel uses typed `cloud_device_authorization_started`, `cloud_device_authorization_succeeded`, `backend_added`, and `cloud_conversation_ready` events from `cloud-funnel-analytics.ts`.+### Adding a new event1. Add a typed function to `useTracking` in `src/hooks/use-tracking.ts`2. Add the function to the hook's `return` objectdiff --git a/__tests__/api/cloud-conversation-service.test.ts b/__tests__/api/cloud-conversation-service.test.tsindex 5341534d40..4248b23e0d 100644--- a/__tests__/api/cloud-conversation-service.test.ts+++ b/__tests__/api/cloud-conversation-service.test.ts@@ -8,8 +8,10 @@ import type { Backend } from "#/api/backend-registry/types";import { setStoredConversationMetadata } from "#/api/conversation-metadata-store";import {batchGetCloudConversations,+ createCloudAppConversation,searchCloudConversations,} from "#/api/cloud/conversation-service.api";+import { AGENT_CANVAS_CLIENT_HEADERS } from "#/api/client-source";const { mockCallCloudProxy } = vi.hoisted(() => ({mockCallCloudProxy: vi.fn(),@@ -42,6 +44,26 @@ describe("cloud conversation-service overlay", () => {mockCallCloudProxy.mockReset();});+ it("marks Cloud conversation starts as originating from Agent Canvas", async () => {+ mockCallCloudProxy.mockResolvedValueOnce({ id: "start-task" });++ await createCloudAppConversation({+ initial_message: null,+ selected_repository: null,+ selected_branch: null,+ git_provider: null,+ plugins: null,+ parent_conversation_id: null,+ });++ expect(mockCallCloudProxy).toHaveBeenCalledWith(+ expect.objectContaining({+ path: "/api/v1/app-conversations",+ headers: AGENT_CANVAS_CLIENT_HEADERS,+ }),+ );+ });+it("overlays locally-stored repo selection onto batchGetCloudConversations results when the server returns nulls", async () => {setStoredConversationMetadata("conv-1", {selected_repository: "octocat/hello-world",diff --git a/__tests__/api/device-flow-client.test.ts b/__tests__/api/device-flow-client.test.tsindex e01b9d0d3c..079582394a 100644--- a/__tests__/api/device-flow-client.test.ts+++ b/__tests__/api/device-flow-client.test.ts@@ -5,6 +5,7 @@ import {isOpenHandsCloudHost,DeviceFlowError,} from "../../src/api/device-flow-client";+import { AGENT_CANVAS_CLIENT_HEADERS } from "../../src/api/client-source";const TEST_HOST_URL = "https://app.all-hands.dev";@@ -80,15 +81,15 @@ describe("device-flow-client", () => {expect(result).toEqual(mockResponse);// Should call the cloud endpoint directly.- expect(fetch).toHaveBeenCalledWith(- `${TEST_HOST_URL}/oauth/device/authorize`,- expect.objectContaining({- method: "POST",- headers: expect.objectContaining({- "Content-Type": "application/json",- }),- }),- );+ const fetchCall = (fetch as ReturnType<typeof vi.fn>).mock.calls[0];+ expect(fetchCall[0]).toBe(`${TEST_HOST_URL}/oauth/device/authorize`);+ expect(fetchCall[1]).toEqual(expect.objectContaining({ method: "POST" }));++ const headers = new Headers(fetchCall[1].headers);+ expect(headers.get("Content-Type")).toBe("application/json");+ for (const [name, value] of Object.entries(AGENT_CANVAS_CLIENT_HEADERS)) {+ expect(headers.get(name)).toBe(value);+ }});it("normalizes host URL by removing trailing slashes", async () => {@@ -176,15 +177,17 @@ describe("device-flow-client", () => {expect(result).toEqual(mockTokenResponse);// Should call the cloud endpoint directly.- expect(fetch).toHaveBeenCalledWith(- `${TEST_HOST_URL}/oauth/device/token`,- expect.objectContaining({- method: "POST",- headers: expect.objectContaining({- "Content-Type": "application/x-www-form-urlencoded",- }),- }),+ const fetchCall = (fetch as ReturnType<typeof vi.fn>).mock.calls[0];+ expect(fetchCall[0]).toBe(`${TEST_HOST_URL}/oauth/device/token`);+ expect(fetchCall[1]).toEqual(expect.objectContaining({ method: "POST" }));++ const headers = new Headers(fetchCall[1].headers);+ expect(headers.get("Content-Type")).toBe(+ "application/x-www-form-urlencoded",);+ for (const [name, value] of Object.entries(AGENT_CANVAS_CLIENT_HEADERS)) {+ expect(headers.get(name)).toBe(value);+ }});it("polls until authorization is complete", async () => {@@ -296,6 +299,18 @@ describe("device-flow-client", () => {).rejects.toThrow(/denied/i);});+ it("reports a non-JSON error response instead of retrying it as a network error", async () => {+ global.fetch = vi.fn().mockResolvedValue({+ ok: false,+ status: 502,+ json: () => Promise.reject(new SyntaxError("invalid JSON")),+ });++ await expect(+ pollForToken(TEST_HOST_URL, "device123", { interval: 1 }),+ ).rejects.toThrow(/Unexpected response from server: 502/);+ });+it("respects abort signal", async () => {vi.useRealTimers(); // Use real timers for this testconst controller = new AbortController();@@ -321,6 +336,28 @@ describe("device-flow-client", () => {).rejects.toThrow(/cancelled/i);});+ it("reports cancellation when aborted between polling attempts", async () => {+ const controller = new AbortController();+ global.fetch = vi.fn().mockResolvedValue({+ ok: false,+ status: 400,+ json: () => Promise.resolve({ error: "authorization_pending" }),+ });++ const pollPromise = pollForToken(TEST_HOST_URL, "device123", {+ interval: 5,+ signal: controller.signal,+ });+ const rejection = expect(pollPromise).rejects.toMatchObject({+ code: "cancelled",+ });++ await vi.advanceTimersByTimeAsync(0);+ controller.abort();++ await rejection;+ });+it("times out after specified duration", async () => {vi.useRealTimers(); // Use real timers for this testglobal.fetch = vi.fn().mockResolvedValue({diff --git a/__tests__/hooks/use-device-flow.test.ts b/__tests__/hooks/use-device-flow.test.tsindex 3ad1dec09e..3eb11154e1 100644--- a/__tests__/hooks/use-device-flow.test.ts+++ b/__tests__/hooks/use-device-flow.test.ts@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";import { renderHook, act, waitFor } from "@testing-library/react";import { useDeviceFlow } from "../../src/hooks/use-device-flow";import * as deviceFlowClient from "../../src/api/device-flow-client";+import * as cloudFunnelAnalytics from "../../src/services/cloud-funnel-analytics";vi.mock("../../src/api/device-flow-client", () => ({startDeviceFlow: vi.fn(),@@ -16,6 +17,11 @@ vi.mock("../../src/api/device-flow-client", () => ({},}));+vi.mock("../../src/services/cloud-funnel-analytics", () => ({+ trackCloudDeviceAuthorizationStarted: vi.fn(),+ trackCloudDeviceAuthorizationSucceeded: vi.fn(),+}));+describe("useDeviceFlow", () => {beforeEach(() => {vi.clearAllMocks();@@ -69,7 +75,7 @@ describe("useDeviceFlow", () => {// Start the flowact(() => {- result.current.start("https://app.all-hands.dev");+ result.current.start("https://app.all-hands.dev", "onboarding");});// Should be starting@@ -87,6 +93,9 @@ describe("useDeviceFlow", () => {"https://app.all-hands.dev/device?user_code=USER-1234",);expect(result.current.userCode).toBe("USER-1234");+ expect(+ cloudFunnelAnalytics.trackCloudDeviceAuthorizationStarted,+ ).toHaveBeenCalledWith("https://app.all-hands.dev", "onboarding");// Resolve pollForTokenawait act(async () => {@@ -97,6 +106,9 @@ describe("useDeviceFlow", () => {// Now should be successexpect(result.current.status).toBe("success");expect(result.current.apiKey).toBe("api-key-123");+ expect(+ cloudFunnelAnalytics.trackCloudDeviceAuthorizationSucceeded,+ ).toHaveBeenCalledWith("https://app.all-hands.dev", "onboarding");});it("handles startDeviceFlow error", async () => {@@ -115,6 +127,9 @@ describe("useDeviceFlow", () => {});expect(result.current.error).toBe("Failed to start");+ expect(+ cloudFunnelAnalytics.trackCloudDeviceAuthorizationStarted,+ ).not.toHaveBeenCalled();});it("handles pollForToken error", async () => {@@ -147,6 +162,9 @@ describe("useDeviceFlow", () => {expect(result.current.error).toBe("Access denied");expect(result.current.errorCode).toBe("access_denied");+ expect(+ cloudFunnelAnalytics.trackCloudDeviceAuthorizationSucceeded,+ ).not.toHaveBeenCalled();});it("cancels flow and resets to idle", async () => {@@ -270,7 +288,8 @@ describe("useDeviceFlow", () => {device_code: "device123",user_code: "USER-1234",verification_uri: "https://app.all-hands.dev/device",- verification_uri_complete: "https://app.all-hands.dev/device?user_code=USER-1234",+ verification_uri_complete:+ "https://app.all-hands.dev/device?user_code=USER-1234",expires_in: 600,interval: 5,};diff --git a/__tests__/hooks/use-telemetry.test.tsx b/__tests__/hooks/use-telemetry.test.tsxindex 276d496803..662c9de43a 100644--- a/__tests__/hooks/use-telemetry.test.tsx+++ b/__tests__/hooks/use-telemetry.test.tsx@@ -1,20 +1,23 @@import { describe, it, expect, beforeEach, vi, afterEach } from "vitest";import { renderHook, act, waitFor } from "@testing-library/react";-// Mock posthog-js before importing hook+const canvasPosthog = vi.hoisted(() => ({+ capture: vi.fn(),+ opt_in_capturing: vi.fn(),+ opt_out_capturing: vi.fn(),+ has_opted_out_capturing: vi.fn(() => false),+ reset: vi.fn(),+ register: vi.fn(),+}));++// Mock posthog-js before importing hook. Canvas telemetry uses the instance+// returned by named initialization rather than PostHog's default singleton.vi.mock("posthog-js", () => ({default: {- init: vi.fn(),- capture: vi.fn(),- opt_in_capturing: vi.fn(),- opt_out_capturing: vi.fn(),- has_opted_out_capturing: vi.fn(() => false),- reset: vi.fn(),- register: vi.fn(),+ init: vi.fn(() => canvasPosthog),},}));-import posthog from "posthog-js";import { useTelemetry } from "#/hooks/use-telemetry";describe("useTelemetry", () => {@@ -62,7 +65,7 @@ describe("useTelemetry", () => {// trackInstall is called on mount - wait for the async effectawait waitFor(() => {- expect(posthog.capture).toHaveBeenCalledWith(+ expect(canvasPosthog.capture).toHaveBeenCalledWith("canvas_install",expect.any(Object),);@@ -74,7 +77,7 @@ describe("useTelemetry", () => {// Wait for initial trackInstallawait waitFor(() => {- expect(posthog.capture).toHaveBeenCalledTimes(1);+ expect(canvasPosthog.capture).toHaveBeenCalledTimes(1);});// Rerender multiple times@@ -83,7 +86,7 @@ describe("useTelemetry", () => {rerender();// Should still only have been called once- expect(posthog.capture).toHaveBeenCalledTimes(1);+ expect(canvasPosthog.capture).toHaveBeenCalledTimes(1);});it("grants consent and enables telemetry", async () => {@@ -123,7 +126,7 @@ describe("useTelemetry", () => {});// capture should not be called for custom events without consent- expect(posthog.capture).not.toHaveBeenCalledWith("test_event", {+ expect(canvasPosthog.capture).not.toHaveBeenCalledWith("test_event", {foo: "bar",});});diff --git a/__tests__/services/cloud-funnel-analytics.test.ts b/__tests__/services/cloud-funnel-analytics.test.tsnew file mode 100644index 0000000000..7df4aad916--- /dev/null+++ b/__tests__/services/cloud-funnel-analytics.test.ts@@ -0,0 +1,91 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ enabled: true,+ trackEvent: vi.fn(),+}));++vi.mock("#/services/telemetry", () => ({+ isTelemetryEnabled: () => mocks.enabled,+ trackEvent: mocks.trackEvent,+}));++import {+ trackCanvasBackendAdded,+ trackCloudConversationReady,+ trackCloudDeviceAuthorizationStarted,+ trackCloudDeviceAuthorizationSucceeded,+} from "#/services/cloud-funnel-analytics";++describe("cloud funnel analytics", () => {+ beforeEach(() => {+ mocks.enabled = true;+ mocks.trackEvent.mockReset();+ });++ it("emits the device authorization milestones with coarse attribution", () => {+ trackCloudDeviceAuthorizationStarted(+ "https://app.all-hands.dev",+ "onboarding",+ );+ trackCloudDeviceAuthorizationSucceeded(+ "https://app.all-hands.dev",+ "onboarding",+ );++ expect(mocks.trackEvent).toHaveBeenNthCalledWith(+ 1,+ "cloud_device_authorization_started",+ expect.objectContaining({+ is_openhands_cloud: true,+ is_custom_host: false,+ source: "onboarding",+ client_source: "agent_canvas",+ }),+ );+ expect(mocks.trackEvent).toHaveBeenNthCalledWith(+ 2,+ "cloud_device_authorization_succeeded",+ expect.objectContaining({ client_source: "agent_canvas" }),+ );+ });++ it("emits backend and ready milestones without raw host or credentials", () => {+ trackCanvasBackendAdded({+ backendKind: "cloud",+ connectionMethod: "cloud_login",+ host: "https://app.all-hands.dev",+ hasApiKey: true,+ source: "add_backend_modal",+ });+ trackCloudConversationReady("task-id", "conversation-id");++ expect(mocks.trackEvent).toHaveBeenNthCalledWith(+ 1,+ "backend_added",+ expect.objectContaining({+ backend_kind: "cloud",+ connection_method: "cloud_login",+ has_api_key: true,+ }),+ );+ expect(mocks.trackEvent.mock.calls[0][1]).not.toHaveProperty("host");+ expect(mocks.trackEvent).toHaveBeenNthCalledWith(+ 2,+ "cloud_conversation_ready",+ expect.objectContaining({+ task_id: "task-id",+ conversation_id: "conversation-id",+ }),+ );+ });++ it("does not enqueue funnel events without Canvas consent", () => {+ mocks.enabled = false;++ expect(+ trackCloudDeviceAuthorizationStarted("https://app.all-hands.dev"),+ ).toBe(false);+ expect(mocks.trackEvent).not.toHaveBeenCalled();+ });+});diff --git a/__tests__/services/telemetry-delivery.test.ts b/__tests__/services/telemetry-delivery.test.tsnew file mode 100644index 0000000000..41fa5b275b--- /dev/null+++ b/__tests__/services/telemetry-delivery.test.ts@@ -0,0 +1,63 @@+import { waitFor } from "@testing-library/react";+import { http, HttpResponse } from "msw";+import { gunzipSync } from "node:zlib";+import { afterEach, describe, expect, it } from "vitest";+import { server } from "#/mocks/node";+import {+ clearTelemetryData,+ getPostHogInstance,+ setTelemetryConsent,+ trackEvent,+} from "#/services/telemetry";++describe("Canvas telemetry delivery", () => {+ afterEach(async () => {+ await clearTelemetryData();+ });++ it("delivers a consented event through the real named PostHog client", async () => {+ const requestBodies: string[] = [];+ server.use(+ http.post("https://z.openhands.dev/*", async ({ request }) => {+ const body = Buffer.from(await request.arrayBuffer());+ const compression = new URL(request.url).searchParams.get(+ "compression",+ );+ requestBodies.push(+ compression === "gzip-js"+ ? gunzipSync(body).toString("utf8")+ : body.toString("utf8"),+ );+ return HttpResponse.json(null, { status: 200 });+ }),+ );++ await setTelemetryConsent("granted");+ const client = await getPostHogInstance();+ expect(client).not.toBeNull();++ // Reproduce the host-app lifecycle that previously broke Canvas events:+ // its default client is initialized and opted out after Canvas opts in.+ const { default: hostPosthog } = await import("posthog-js");+ hostPosthog.init(client!.config.token, {+ api_host: "https://z.openhands.dev",+ advanced_disable_flags: true,+ autocapture: false,+ capture_pageview: false,+ });+ hostPosthog.opt_out_capturing();+ expect(hostPosthog.has_opted_out_capturing()).toBe(true);+ expect(client!.has_opted_out_capturing()).toBe(false);++ // Send this assertion event immediately and without compression so the+ // test validates the SDK's actual HTTP delivery rather than a capture mock.+ client!.set_config({ request_batching: false, disable_compression: true });+ await trackEvent("canvas_delivery_test", { source: "vitest" });++ await waitFor(() =>+ expect(+ requestBodies.some((body) => body.includes("canvas_delivery_test")),+ ).toBe(true),+ );+ });+});diff --git a/__tests__/services/telemetry.test.ts b/__tests__/services/telemetry.test.tsindex f0b6698c38..a679de5cc2 100644--- a/__tests__/services/telemetry.test.ts+++ b/__tests__/services/telemetry.test.ts@@ -10,6 +10,7 @@ const mockPosthog = {reset: vi.fn(),register: vi.fn(),};+mockPosthog.init.mockReturnValue(mockPosthog);vi.mock("posthog-js", () => ({default: mockPosthog,@@ -46,6 +47,24 @@ describe("Telemetry Service", () => {sessionStorage.clear();});+ describe("PostHog ownership", () => {+ it("uses an isolated named client for Canvas consent and events", async () => {+ await setTelemetryConsent("granted");++ expect(mockPosthog.init).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({+ api_host: expect.any(String),+ ui_host: expect.any(String),+ persistence_name: "agent-canvas",+ consent_persistence_name: "agent-canvas-consent",+ }),+ "agent-canvas",+ );+ expect(mockPosthog.opt_in_capturing).toHaveBeenCalled();+ });+ });+describe("getTelemetryConsent", () => {it("returns 'pending' when no consent has been set", () => {expect(getTelemetryConsent()).toBe("pending");@@ -191,23 +210,5 @@ describe("Telemetry Service", () => {await setTelemetryConsent("denied");expect(mockPosthog.opt_out_capturing).toHaveBeenCalled();});-- it("initializes PostHog with ui_host for proxy support", async () => {- // Note: PostHog init may have been called in previous tests due to module caching- // We test that the configuration includes ui_host by checking any init call- // The actual initialization happens once per module load with the correct config- await trackInstall();-- // Check that init was called at some point with the expected config- // This verifies our telemetry service passes ui_host to PostHog- const initCalls = mockPosthog.init.mock.calls;- if (initCalls.length > 0) {- const [, config] = initCalls[0];- expect(config).toHaveProperty("api_host");- expect(config).toHaveProperty("ui_host");- }- // If init wasn't called in this test, it was already called in a previous test- // with the correct config, which is fine- });});});diff --git a/package-lock.json b/package-lock.jsonindex c01e6be307..d74e058bf5 100644--- a/package-lock.json+++ b/package-lock.json@@ -13,7 +13,7 @@"@microlink/react-json-view": "1.31.20","@monaco-editor/react": "4.7.0","@openhands/extensions": "0.9.0",- "@openhands/typescript-client": "1.33.0",+ "@openhands/typescript-client": "1.34.0","@react-router/node": "7.17.0","@react-router/serve": "7.17.0","@tailwindcss/vite": "4.2.4",@@ -3483,9 +3483,9 @@}},"node_modules/@openhands/typescript-client": {- "version": "1.33.0",- "resolved": "https://registry.npmjs.org/@openhands/typescript-client/-/typescript-client-1.33.0.tgz",- "integrity": "sha512-O5RSsXjT47o8Bee2gnIg7o2KW7e/EgURkXnWoxSbgAFGRQAiaW+hCPH8oQk5eN6AVE75BEL99RxRt56zNu4T7g==",+ "version": "1.34.0",+ "resolved": "https://registry.npmjs.org/@openhands/typescript-client/-/typescript-client-1.34.0.tgz",+ "integrity": "sha512-29nuKB7m1aOBHJWPgAY8ahZlsnJGkgByuoAQzYjY/lHzUClhM9RCJ0vgghm9cblADiYf+mUAOEL9AaOkXH2ahQ==","license": "MIT","dependencies": {"@openrouter/sdk": "^0.13.24",diff --git a/package.json b/package.jsonindex 0a55174b69..b5faa22a71 100644--- a/package.json+++ b/package.json@@ -24,7 +24,7 @@"@microlink/react-json-view": "1.31.20","@monaco-editor/react": "4.7.0","@openhands/extensions": "0.9.0",- "@openhands/typescript-client": "1.33.0",+ "@openhands/typescript-client": "1.34.0","@react-router/node": "7.17.0","@react-router/serve": "7.17.0","@tailwindcss/vite": "4.2.4",diff --git a/src/api/client-source.ts b/src/api/client-source.tsnew file mode 100644index 0000000000..9a3d4e383b--- /dev/null+++ b/src/api/client-source.ts@@ -0,0 +1,15 @@+import packageJson from "../../package.json";++export const AGENT_CANVAS_CLIENT_SOURCE = "agent_canvas";+export const AGENT_CANVAS_CLIENT_VERSION = packageJson.version;++/**+ * Coarse, non-user-identifying request metadata for Cloud observability.+ *+ * Cloud ingress can retain these headers as facets without logging request+ * bodies, API keys, device codes, or conversation content.+ */+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,+};diff --git a/src/api/cloud/conversation-service.api.ts b/src/api/cloud/conversation-service.api.tsindex 894e54b5ca..f5e5f29d65 100644--- a/src/api/cloud/conversation-service.api.ts+++ b/src/api/cloud/conversation-service.api.ts@@ -7,6 +7,7 @@ import type {AppConversationStartRequest,AppConversationStartTask,} from "../conversation-service/agent-server-conversation-service.types";+import { AGENT_CANVAS_CLIENT_HEADERS } from "../client-source";import { callCloudProxy } from "./proxy";/**@@ -126,6 +127,7 @@ export async function createCloudAppConversation(method: "POST",path: "/api/v1/app-conversations",body: request as unknown as Record<string, unknown>,+ headers: AGENT_CANVAS_CLIENT_HEADERS,});return data;}diff --git a/src/api/device-flow-client.ts b/src/api/device-flow-client.tsindex 27a6a45067..63dbd5344c 100644--- a/src/api/device-flow-client.ts+++ b/src/api/device-flow-client.ts@@ -1,43 +1,38 @@+import {+ pollForToken as sdkPollForToken,+ startDeviceFlow as sdkStartDeviceFlow,+} from "@openhands/typescript-client/client/device-flow-client";+import type {+ DeviceAuthorizationResponse,+ DeviceTokenResponse,+ PollDeviceTokenOptions,+} from "@openhands/typescript-client/client/device-flow-client";+import { AGENT_CANVAS_CLIENT_HEADERS } from "./client-source";+export {DeviceFlowError,- pollForToken,- startDeviceFlow,-} from "@openhands/typescript-client/clients";-import { isOpenHandsCloudHost as sdkIsOpenHandsCloudHost } from "@openhands/typescript-client/clients";--const OPENHANDS_CLOUD_HOST_SUFFIXES = ["all-hands.dev", "openhands.dev"];+ isOpenHandsCloudHost,+} from "@openhands/typescript-client/client/device-flow-client";-function isAllowedCloudHostname(hostname: string): boolean {- return OPENHANDS_CLOUD_HOST_SUFFIXES.some(- (suffix) => hostname === suffix || hostname.endsWith(`.${suffix}`),- );+export function startDeviceFlow(+ host: string,+): Promise<DeviceAuthorizationResponse> {+ return sdkStartDeviceFlow(host, { headers: AGENT_CANVAS_CLIENT_HEADERS });}-function fallbackIsOpenHandsCloudHost(host: string): boolean {- if (!host.trim()) return false;-- try {- const normalizedHost = host.includes("://") ? host : `https://${host}`;- const { hostname } = new URL(normalizedHost);- return isAllowedCloudHostname(hostname.toLowerCase());- } catch {- return false;- }+export function pollForToken(+ host: string,+ deviceCode: string,+ options: PollDeviceTokenOptions,+): Promise<DeviceTokenResponse> {+ return sdkPollForToken(host, deviceCode, {+ ...options,+ headers: AGENT_CANVAS_CLIENT_HEADERS,+ });}-export function isOpenHandsCloudHost(host: string): boolean {- try {- if (typeof sdkIsOpenHandsCloudHost === "function") {- return sdkIsOpenHandsCloudHost(host);- }- } catch {- return fallbackIsOpenHandsCloudHost(host);- }-- return fallbackIsOpenHandsCloudHost(host);-}export type {DeviceAuthorizationResponse,DeviceTokenResponse,PollDeviceTokenOptions as PollOptions,-} from "@openhands/typescript-client/clients";+} from "@openhands/typescript-client/client/device-flow-client";diff --git a/src/components/features/backends/backend-form-modal.tsx b/src/components/features/backends/backend-form-modal.tsxindex 5c85c42561..390f21982d 100644--- a/src/components/features/backends/backend-form-modal.tsx+++ b/src/components/features/backends/backend-form-modal.tsx@@ -16,6 +16,10 @@ import { useActiveBackendContext } from "#/contexts/active-backend-context";import { useNavigation } from "#/context/navigation-context";import { useBackendsHealth } from "#/hooks/query/use-backends-health";import { useTracking } from "#/hooks/use-tracking";+import {+ trackCanvasBackendAdded,+ type CloudConnectionSource,+} from "#/services/cloud-funnel-analytics";import { getAgentServerClientOptions } from "#/api/agent-server-client-options";import { getLockedCloudHost } from "#/api/agent-server-config";import { isOpenHandsCloudHost } from "#/api/device-flow-client";@@ -140,7 +144,7 @@ const DEFAULT_OPENHANDS_CLOUD_HOST = "https://app.all-hands.dev";export type BackendConnectionMethod = "manual" | "cloud_login";-export type BackendAddedSource = "add_backend_modal" | "manage_backends_modal";+export type BackendAddedSource = CloudConnectionSource;function getConnectionTestFailedTitle(t: ReturnType<typeof useTranslation>["t"],@@ -700,6 +704,7 @@ interface BackendConnectionOptionsProps {manualSubmitLabel?: React.ReactNode;manualSubmittingLabel?: React.ReactNode;manualSubmitTestId?: string;+ analyticsSource?: CloudConnectionSource;}/**@@ -715,6 +720,7 @@ export function BackendConnectionOptions({manualSubmitLabel,manualSubmittingLabel,manualSubmitTestId,+ analyticsSource,}: BackendConnectionOptionsProps) {const { t } = useTranslation("openhands");const lockedCloudHost = getLockedCloudHost();@@ -730,6 +736,7 @@ export function BackendConnectionOptions({onConnected={onConnected}testIdRoot={testIdRoot}lockedHost={lockedCloudHost}+ analyticsSource={analyticsSource}/></div></div>@@ -757,7 +764,11 @@ export function BackendConnectionOptions({</div><div className="flex-1 min-w-0">- <CloudLoginColumn onConnected={onConnected} testIdRoot={testIdRoot} />+ <CloudLoginColumn+ onConnected={onConnected}+ testIdRoot={testIdRoot}+ analyticsSource={analyticsSource}+ /></div></div>);@@ -934,6 +945,7 @@ interface CloudLoginColumnProps {) => void;testIdRoot: string;lockedHost?: string;+ analyticsSource?: CloudConnectionSource;}/**@@ -945,6 +957,7 @@ function CloudLoginColumn({onConnected,testIdRoot,lockedHost,+ analyticsSource,}: CloudLoginColumnProps) {const { t } = useTranslation("openhands");@@ -987,6 +1000,7 @@ function CloudLoginColumn({host={effectiveHost}onSuccess={handleLoginSuccess}testIdRoot={testIdRoot}+ analyticsSource={analyticsSource}/>{lockedHost ? null : (@@ -1052,22 +1066,36 @@ function AddBackendConnectionOptions({) => {addBackend(payload);// Coarse, non-sensitive host classification β never emit the raw host.- const isOpenHandsCloud = payload.host === DEFAULT_OPENHANDS_CLOUD_HOST;- trackBackendAdded({+ const isOpenHandsCloud = isOpenHandsCloudHost(payload.host);+ const trackedByCanvas = trackCanvasBackendAdded({backendKind: payload.kind,connectionMethod,- isOpenhandsCloud: isOpenHandsCloud,- isCustomHost: !isOpenHandsCloud,+ host: payload.host,hasApiKey: Boolean(payload.apiKey),source,});+ if (!trackedByCanvas) {+ trackBackendAdded({+ backendKind: payload.kind,+ connectionMethod,+ isOpenhandsCloud: isOpenHandsCloud,+ isCustomHost: !isOpenHandsCloud,+ hasApiKey: Boolean(payload.apiKey),+ source,+ });+ }redirectAfterAdd();onClose();},[addBackend, redirectAfterAdd, onClose, trackBackendAdded, source],);- return <BackendConnectionOptions onConnected={handleConnected} />;+ return (+ <BackendConnectionOptions+ onConnected={handleConnected}+ analyticsSource={source}+ />+ );}// ββ Modal wrappers ββββββββββββββββββββββββββββββββββββββββββββββββββdiff --git a/src/components/features/backends/backend-row.tsx b/src/components/features/backends/backend-row.tsxindex c2157361f5..53b57d5805 100644--- a/src/components/features/backends/backend-row.tsx+++ b/src/components/features/backends/backend-row.tsx@@ -131,6 +131,7 @@ export function BackendRow({buttonVariant="unstyled"buttonClassName={ROW_ACTION_BUTTON_CLASS}statusDisplay="modal"+ analyticsSource="manage_backends_modal"/>) : null}{!lockedCloudHost && (diff --git a/src/components/features/backends/device-flow-auth.tsx b/src/components/features/backends/device-flow-auth.tsxindex 17ccacc93e..6398a942fd 100644--- a/src/components/features/backends/device-flow-auth.tsx+++ b/src/components/features/backends/device-flow-auth.tsx@@ -4,6 +4,7 @@ import { BrandButton } from "#/components/features/settings/brand-button";import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";import { ModalBody } from "#/components/shared/modals/modal-body";import { useDeviceFlow, type DeviceFlowStatus } from "#/hooks/use-device-flow";+import type { CloudConnectionSource } from "#/services/cloud-funnel-analytics";import { I18nKey } from "#/i18n/declaration";import { cn } from "#/utils/utils";@@ -35,6 +36,8 @@ interface DeviceFlowAuthProps {buttonVariant?: DeviceFlowButtonVariant;/** Whether in-progress auth content should render inline or in a modal. */statusDisplay?: DeviceFlowStatusDisplay;+ /** Product surface that initiated this authorization attempt. */+ analyticsSource?: CloudConnectionSource;}/**@@ -68,6 +71,7 @@ export function DeviceFlowAuth({buttonClassName,buttonVariant = "primary",statusDisplay = "inline",+ analyticsSource,}: DeviceFlowAuthProps) {const { t } = useTranslation("openhands");const deviceFlow = useDeviceFlow();@@ -149,7 +153,7 @@ export function DeviceFlowAuth({console.warn("Popup blocked - user will need to use manual link");}- deviceFlow.start(fullHost);+ deviceFlow.start(fullHost, analyticsSource);};const handleCancel = () => {diff --git a/src/components/features/onboarding/steps/check-backend-step.tsx b/src/components/features/onboarding/steps/check-backend-step.tsxindex 0d3ea8f7aa..121752e027 100644--- a/src/components/features/onboarding/steps/check-backend-step.tsx+++ b/src/components/features/onboarding/steps/check-backend-step.tsx@@ -12,11 +12,13 @@ import {import { DEFAULT_LOCAL_BACKEND_NAME } from "#/api/backend-registry/default-backend";import {BackendConnectionOptions,+ type BackendConnectionMethod,type BackendFormSubmitPayload,} from "#/components/features/backends/backend-form-modal";import { BrandButton } from "#/components/features/settings/brand-button";import { useActiveBackendContext } from "#/contexts/active-backend-context";import { useBackendsHealth } from "#/hooks/query/use-backends-health";+import { trackCanvasBackendAdded } from "#/services/cloud-funnel-analytics";import { I18nKey } from "#/i18n/declaration";import ChevronDownSmallIcon from "#/icons/chevron-down-small.svg?react";import { cn } from "#/utils/utils";@@ -168,7 +170,10 @@ export function CheckBackendStep({const hideConfigurationFields = isConnected === true && !configurationOpen;const handleConnected = React.useCallback(- (payload: BackendFormSubmitPayload) => {+ (+ payload: BackendFormSubmitPayload,+ connectionMethod: BackendConnectionMethod,+ ) => {if (noBackendSelected) {addBackend(payload);} else {@@ -185,6 +190,13 @@ export function CheckBackendStep({setActive(backend.id, null);}}+ trackCanvasBackendAdded({+ backendKind: payload.kind,+ connectionMethod,+ host: payload.host,+ hasApiKey: Boolean(payload.apiKey),+ source: "onboarding",+ });// In locked-to-Cloud mode, Cloud login IS the onboarding// completion: dismiss the modal immediately so the user never// sees the next slide (Choose Agent) flash before the root gate@@ -278,6 +290,7 @@ export function CheckBackendStep({manualSubmitLabel={t(I18nKey.ONBOARDING$NEXT)}manualSubmittingLabel={t(I18nKey.SETTINGS$SAVING)}manualSubmitTestId="onboarding-backend-next"+ analyticsSource="onboarding"/>) : null}</div>diff --git a/src/hooks/query/use-task-polling.ts b/src/hooks/query/use-task-polling.tsindex 8d0e92e14f..49be95a609 100644--- a/src/hooks/query/use-task-polling.ts+++ b/src/hooks/query/use-task-polling.ts@@ -14,6 +14,7 @@ import {setConversationState,} from "#/utils/conversation-local-storage";import { useOptimisticUserMessageStore } from "#/stores/optimistic-user-message-store";+import { trackCloudConversationReady } from "#/services/cloud-funnel-analytics";import { flushPendingTaskAttachments } from "#/utils/flush-pending-task-attachments";import {clearPendingTaskMessageLink,@@ -128,6 +129,7 @@ export const useTaskPolling = () => {}handledReadyTaskIdRef.current = taskId;+ trackCloudConversationReady(taskId, appConversationId);storeTaskPlugins(task, appConversationId);void (async () => {diff --git a/src/hooks/use-device-flow.ts b/src/hooks/use-device-flow.tsindex 255c032eed..2f346329cf 100644--- a/src/hooks/use-device-flow.ts+++ b/src/hooks/use-device-flow.ts@@ -5,6 +5,11 @@ import {DeviceFlowError,type DeviceAuthorizationResponse,} from "#/api/device-flow-client";+import {+ trackCloudDeviceAuthorizationStarted,+ trackCloudDeviceAuthorizationSucceeded,+ type CloudConnectionSource,+} from "#/services/cloud-funnel-analytics";export type DeviceFlowStatus =| "idle"@@ -29,13 +34,18 @@ export interface DeviceFlowState {export interface UseDeviceFlowReturn extends DeviceFlowState {/** Start the device flow authentication */- start: (host: string) => void;+ start: StartDeviceFlow;/** Cancel an in-progress flow */cancel: () => void;/** Reset state back to idle */reset: () => void;}+type StartDeviceFlow = (+ host: string,+ analyticsSource?: CloudConnectionSource,+) => void;+const initialState: DeviceFlowState = {status: "idle",verificationUrl: null,@@ -70,7 +80,7 @@ export function useDeviceFlow(): UseDeviceFlowReturn {const [state, setState] = React.useState<DeviceFlowState>(initialState);const abortControllerRef = React.useRef<AbortController | null>(null);- const start = React.useCallback((host: string) => {+ const start: StartDeviceFlow = React.useCallback((host, analyticsSource) => {// Cancel any existing flowabortControllerRef.current?.abort();const abortController = new AbortController();@@ -106,6 +116,8 @@ export function useDeviceFlow(): UseDeviceFlowReturn {if (abortController.signal.aborted) return;+ trackCloudDeviceAuthorizationStarted(host, analyticsSource);+setState({...initialState,status: "awaiting_authorization",@@ -125,6 +137,8 @@ export function useDeviceFlow(): UseDeviceFlowReturn {if (abortController.signal.aborted) return;+ trackCloudDeviceAuthorizationSucceeded(host, analyticsSource);+setState({...initialState,status: "success",diff --git a/src/hooks/use-tracking.ts b/src/hooks/use-tracking.tsindex 3453de58b0..d5e07ab41e 100644--- a/src/hooks/use-tracking.ts+++ b/src/hooks/use-tracking.ts@@ -3,6 +3,7 @@ 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";/*** Hook that provides tracking functions with automatic data collection@@ -251,7 +252,7 @@ export const useTracking = () => {isOpenhandsCloud: boolean;isCustomHost: boolean;hasApiKey: boolean;- source?: "add_backend_modal" | "manage_backends_modal";+ source?: CloudConnectionSource;}) => {track("backend_added", {backend_kind: backendKind,diff --git a/src/routes/app-settings.tsx b/src/routes/app-settings.tsxindex 8937cbd884..429b9f7f91 100644--- a/src/routes/app-settings.tsx+++ b/src/routes/app-settings.tsx@@ -5,6 +5,7 @@ import { useSaveSettings } from "#/hooks/mutation/use-save-settings";import { useSettings } from "#/hooks/query/use-settings";import { AvailableLanguages } from "#/i18n";import { DEFAULT_SETTINGS } from "#/services/settings";+import { setTelemetryConsent } from "#/services/telemetry";import { BrandButton } from "#/components/features/settings/brand-button";import { SettingsSwitch } from "#/components/features/settings/settings-switch";import { SettingsInput } from "#/components/features/settings/settings-input";@@ -69,6 +70,7 @@ export function AppSettingsScreen() {{onSuccess: () => {handleCaptureConsent(posthog, enableAnalytics);+ void setTelemetryConsent(enableAnalytics ? "granted" : "denied");displaySuccessToast(t(I18nKey.SETTINGS$SAVED));},onError: (error) => {diff --git a/src/services/cloud-funnel-analytics.ts b/src/services/cloud-funnel-analytics.tsnew file mode 100644index 0000000000..af330994e2--- /dev/null+++ b/src/services/cloud-funnel-analytics.ts@@ -0,0 +1,86 @@+import type { BackendKind } from "#/api/backend-registry/types";+import {+ AGENT_CANVAS_CLIENT_SOURCE,+ AGENT_CANVAS_CLIENT_VERSION,+} from "#/api/client-source";+import { isOpenHandsCloudHost } from "#/api/device-flow-client";+import { isTelemetryEnabled, trackEvent } from "#/services/telemetry";++export type CloudConnectionSource =+ | "onboarding"+ | "add_backend_modal"+ | "manage_backends_modal";++const commonProperties = {+ client_source: AGENT_CANVAS_CLIENT_SOURCE,+ client_version: AGENT_CANVAS_CLIENT_VERSION,+};++function trackCloudFunnelEvent(+ event: string,+ properties: Record<string, unknown>,+): boolean {+ if (!isTelemetryEnabled()) return false;+ void trackEvent(event, { ...properties, ...commonProperties });+ return true;+}++function hostClassification(host: string) {+ const isOpenhandsCloud = isOpenHandsCloudHost(host);+ return {+ is_openhands_cloud: isOpenhandsCloud,+ is_custom_host: !isOpenhandsCloud,+ };+}++export function trackCloudDeviceAuthorizationStarted(+ host: string,+ source?: CloudConnectionSource,+): boolean {+ return trackCloudFunnelEvent("cloud_device_authorization_started", {+ ...hostClassification(host),+ source,+ });+}++export function trackCloudDeviceAuthorizationSucceeded(+ host: string,+ source?: CloudConnectionSource,+): boolean {+ return trackCloudFunnelEvent("cloud_device_authorization_succeeded", {+ ...hostClassification(host),+ source,+ });+}++export function trackCanvasBackendAdded({+ backendKind,+ connectionMethod,+ host,+ hasApiKey,+ source,+}: {+ backendKind: BackendKind;+ connectionMethod: "manual" | "cloud_login";+ host: string;+ hasApiKey: boolean;+ source?: CloudConnectionSource;+}): boolean {+ return trackCloudFunnelEvent("backend_added", {+ backend_kind: backendKind,+ connection_method: connectionMethod,+ ...hostClassification(host),+ has_api_key: hasApiKey,+ source,+ });+}++export function trackCloudConversationReady(+ taskId: string,+ conversationId: string,+): boolean {+ return trackCloudFunnelEvent("cloud_conversation_ready", {+ task_id: taskId,+ conversation_id: conversationId,+ });+}diff --git a/src/services/telemetry.ts b/src/services/telemetry.tsindex 3194ae6326..45ec978cfb 100644--- a/src/services/telemetry.ts+++ b/src/services/telemetry.ts@@ -31,6 +31,7 @@ import packageJson from "../../package.json";const TELEMETRY_CONSENT_KEY = "openhands-telemetry-consent";const TELEMETRY_FIRST_USE_KEY = "openhands-telemetry-first-use";const TELEMETRY_SESSION_KEY = "openhands-telemetry-session";+const POSTHOG_INSTANCE_NAME = "agent-canvas";// PostHog project keys β one per deployment environment, hardcoded so they// are baked into the static bundle at build time and cannot drift at runtime.@@ -85,7 +86,6 @@ async function getPostHog(): Promise<PostHog | null> {try {const { default: posthog } = await import("posthog-js");- posthogInstance = posthog;return posthog;} catch {// Failed to load PostHog - telemetry will be disabled@@ -142,31 +142,40 @@ async function initializePostHog(return null;}- posthog.init(POSTHOG_API_KEY, {- api_host: POSTHOG_HOST,- // UI host is required when using a reverse proxy so PostHog features work correctly- ui_host: POSTHOG_UI_HOST,- // Start with capturing disabled by default - we enable it explicitly when needed- opt_out_capturing_by_default: !enableCapturing,- // Don't auto-capture page views - we control when to track- capture_pageview: false,- // Don't auto-capture clicks etc.- autocapture: false,- // Use localStorage for persistence- persistence: "localStorage",- // Disable session recording- disable_session_recording: true,- // Set default properties for all events- loaded: (ph) => {- ph.register({- package_name: packageJson.name,- package_version: packageJson.version,- });+ // Canvas telemetry must not share PostHog's default singleton with host-app+ // analytics. A named instance gives it independent configuration, consent,+ // persistence, and delivery state.+ posthogInstance = posthog.init(+ POSTHOG_API_KEY,+ {+ api_host: POSTHOG_HOST,+ // UI host is required when using a reverse proxy so PostHog features work correctly+ ui_host: POSTHOG_UI_HOST,+ // Start with capturing disabled by default - we enable it explicitly when needed+ opt_out_capturing_by_default: !enableCapturing,+ // Don't auto-capture page views - we control when to track+ capture_pageview: false,+ // Don't auto-capture clicks etc.+ autocapture: false,+ // Use localStorage for persistence+ persistence: "localStorage",+ persistence_name: POSTHOG_INSTANCE_NAME,+ consent_persistence_name: `${POSTHOG_INSTANCE_NAME}-consent`,+ // Disable session recording+ disable_session_recording: true,+ // Set default properties for all events+ loaded: (ph) => {+ ph.register({+ package_name: packageJson.name,+ package_version: packageJson.version,+ });+ },},- });+ POSTHOG_INSTANCE_NAME,+ );isInitialized = true;- return posthog;+ return posthogInstance;}/**diff --git a/vite.config.ts b/vite.config.tsindex b9d37d69fa..94704f0c3d 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -282,6 +282,7 @@ export default defineConfig(({ mode }) => {// OpenHands typescript client"@openhands/typescript-client","@openhands/typescript-client/client/http-client",+ "@openhands/typescript-client/client/device-flow-client","@openhands/typescript-client/clients","@openhands/typescript-client/events/remote-events-list","@openhands/typescript-client/workspace/remote-workspace",