Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix: keep PostHog identity stable for Cloud context (#1892)

Rohit Malhotraf3f75d994a62
diff --git a/AGENTS.md b/AGENTS.md
index 9756771def..abe576e294 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -32,15 +32,15 @@ by a human, report the exact validator error rather than editing them yourself.
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 identity through `setTelemetryIdentity()` and captures through the service; it never receives or resets the SDK client.
+- `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.
- 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`.
-- `canvas_install` fires once, pre-consent, with the client's anonymous distinct ID. After consent, Cloud `identify()` follows PostHog's normal anonymous-to-identified lifecycle, so install, Cloud-funnel, and app events remain queryable as one user journey. Account changes and logout reset identity inside `telemetry.ts`, which immediately restores the canonical consent state that the PostHog SDK reset clears.
+- `canvas_install` fires once, pre-consent, with the client's anonymous distinct ID. Consent does not identify PostHog as the Cloud user; Canvas keeps the browser/install distinct ID stable across local/Cloud backend switches, creates anonymous person profiles for analytics, and attaches Cloud account context as event properties (`cloud_user_id`, `cloud_user_email`) only while a Cloud backend is active. Legacy identified users are reset only when the PostHog client initializes without OAuth bootstrap IDs, and the reset immediately restores the canonical consent state that the PostHog SDK clears.
- `telemetry.ts` adds immutable `client_source`, `client_version`, `package_name`, and `package_version` properties in `before_send`, so reset cannot remove attribution and event producers cannot override it. Repeated business milestones use deterministic PostHog `$insert_id` values instead of process-local caches.
- `trackEvent` and `useTelemetry` remain the public library telemetry API for npm consumers (the `TelemetryConsentBanner` component was removed; hosts needing a consent UI build their own on `useTelemetry`). Non-React state machines use typed functions in `cloud-funnel-analytics.ts`; they do not call `trackEvent` directly.
-- React app events use typed functions in `src/hooks/use-tracking.ts`; components never call `posthog.capture()` raw. The hook attaches `current_url` and `user_email` automatically and captures through the telemetry service. It may read backend settings for event properties, but must never gate capture on a settings snapshot: `useSyncTelemetryConsent` has already mirrored the authoritative decision to the telemetry service, and settings can be stale during a backend transition.
+- React app events use typed functions in `src/hooks/use-tracking.ts`; components never call `posthog.capture()` raw. The hook attaches `current_url` automatically and captures through the telemetry service; Cloud account email is attached centrally as `cloud_user_email` while Cloud context is active. It may read backend settings for event properties, but must never gate capture on a settings snapshot: `useSyncTelemetryConsent` has already mirrored the authoritative decision to the telemetry service, and settings can be stale during a backend transition.
- A business milestone has one canonical event capture. Do not conditionally switch between telemetry and app clients or emit duplicate events.
### Cloud funnel observability
diff --git a/__tests__/hooks/use-telemetry-identity.test.ts b/__tests__/hooks/use-telemetry-identity.test.ts
index c2dac7095e..e19e08e791 100644
--- a/__tests__/hooks/use-telemetry-identity.test.ts
+++ b/__tests__/hooks/use-telemetry-identity.test.ts
@@ -16,10 +16,10 @@ vi.mock("#/hooks/query/use-cloud-current-user-id", () => ({
useCloudCurrentUserId: () => useCloudCurrentUserIdMock(),
}));
-const setTelemetryIdentityMock = vi.fn();
+const setTelemetryCloudContextMock = vi.fn();
vi.mock("#/services/telemetry", () => ({
- setTelemetryIdentity: (...args: unknown[]) =>
- setTelemetryIdentityMock(...args),
+ setTelemetryCloudContext: (...args: unknown[]) =>
+ setTelemetryCloudContextMock(...args),
}));
import { useTelemetryIdentity } from "#/hooks/use-telemetry-identity";
@@ -40,10 +40,11 @@ describe("useTelemetryIdentity", () => {
});
});
- it("declares the current Cloud identity", () => {
+ it("declares the current Cloud user context", () => {
renderHook(() => useTelemetryIdentity());
- expect(setTelemetryIdentityMock).toHaveBeenCalledWith("user-123", {
+ expect(setTelemetryCloudContextMock).toHaveBeenCalledWith({
+ userId: "user-123",
});
});
@@ -53,23 +54,27 @@ describe("useTelemetryIdentity", () => {
data: { email: "", git_user_email: "[email protected]" },
});
const { rerender } = renderHook(() => useTelemetryIdentity());
- expect(setTelemetryIdentityMock).toHaveBeenLastCalledWith("user-123", {
+ expect(setTelemetryCloudContextMock).toHaveBeenLastCalledWith({
+ userId: "user-123",
});
useSettingsMock.mockReturnValue({ data: {} });
rerender();
- expect(setTelemetryIdentityMock).toHaveBeenLastCalledWith("user-123", {});
+ expect(setTelemetryCloudContextMock).toHaveBeenLastCalledWith({
+ userId: "user-123",
+ email: undefined,
+ });
});
- it("waits until the Cloud identity query settles", () => {
+ it("preserves Cloud user context while the identity query loads", () => {
useCloudCurrentUserIdMock.mockReturnValue({
[BACKEND_ID]: { userId: null, isLoading: true },
});
renderHook(() => useTelemetryIdentity());
- expect(setTelemetryIdentityMock).not.toHaveBeenCalled();
+ expect(setTelemetryCloudContextMock).not.toHaveBeenCalled();
});
it("declares logout only after the Cloud identity query settles", () => {
@@ -79,15 +84,15 @@ describe("useTelemetryIdentity", () => {
renderHook(() => useTelemetryIdentity());
- expect(setTelemetryIdentityMock).toHaveBeenCalledWith(null);
+ expect(setTelemetryCloudContextMock).toHaveBeenCalledWith(null);
});
- it("preserves Cloud identity while a local backend is active", () => {
+ it("clears Cloud user context while a local backend is active", () => {
useActiveBackendMock.mockReturnValue({ backend: localBackend });
renderHook(() => useTelemetryIdentity());
- expect(setTelemetryIdentityMock).not.toHaveBeenCalled();
+ expect(setTelemetryCloudContextMock).toHaveBeenCalledWith(null);
});
it("declares a changed Cloud account", () => {
@@ -98,7 +103,8 @@ describe("useTelemetryIdentity", () => {
rerender();
- expect(setTelemetryIdentityMock).toHaveBeenLastCalledWith("user-456", {
+ expect(setTelemetryCloudContextMock).toHaveBeenLastCalledWith({
+ userId: "user-456",
});
});
diff --git a/__tests__/hooks/use-tracking.test.ts b/__tests__/hooks/use-tracking.test.ts
index a0f49b0a2f..cb9eb2aa9c 100644
--- a/__tests__/hooks/use-tracking.test.ts
+++ b/__tests__/hooks/use-tracking.test.ts
@@ -23,7 +23,6 @@ vi.mock("#/api/automation-service/automation-service.api", () => ({
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: Record<string, unknown>;
@@ -44,11 +43,10 @@ describe("useTracking", () => {
compatibilityMocks.getCachedAgentServerVersion.mockReturnValue(null);
useSettingsMock.mockReturnValue({
- data: { email: TEST_EMAIL, user_consents_to_analytics: true },
+ data: { email: "[email protected]", user_consents_to_analytics: true },
});
COMMON = {
current_url: window.location.href,
- user_email: TEST_EMAIL,
};
});
@@ -423,7 +421,7 @@ describe("useTracking", () => {
describe("shared telemetry boundary", () => {
it("delegates consent enforcement when backend settings report false", () => {
useSettingsMock.mockReturnValue({
- data: { email: TEST_EMAIL, user_consents_to_analytics: false },
+ data: { email: "[email protected]", user_consents_to_analytics: false },
});
getTracking().trackPushButtonClick();
@@ -436,7 +434,7 @@ describe("useTracking", () => {
it("delegates consent enforcement when backend settings report null", () => {
useSettingsMock.mockReturnValue({
- data: { email: TEST_EMAIL, user_consents_to_analytics: null },
+ data: { email: "[email protected]", user_consents_to_analytics: null },
});
getTracking().trackPushButtonClick();
@@ -463,45 +461,8 @@ describe("useTracking", () => {
backend_kind: "cloud",
connection_method: "cloud_login",
source: "onboarding",
- user_email: null,
}),
);
});
});
-
- describe("commonProperties", () => {
- it("uses git_user_email as fallback when email is absent", () => {
- useSettingsMock.mockReturnValue({
- data: {
- email: null,
- git_user_email: "[email protected]",
- user_consents_to_analytics: true,
- },
- });
-
- getTracking().trackPushButtonClick();
-
- expect(captureMock).toHaveBeenCalledWith(
- "push_button_clicked",
- expect.objectContaining({ user_email: "[email protected]" }),
- );
- });
-
- it("sends null user_email when no email fields are present", () => {
- useSettingsMock.mockReturnValue({
- data: {
- email: null,
- git_user_email: null,
- user_consents_to_analytics: true,
- },
- });
-
- getTracking().trackPushButtonClick();
-
- expect(captureMock).toHaveBeenCalledWith(
- "push_button_clicked",
- expect.objectContaining({ user_email: null }),
- );
- });
- });
});
diff --git a/__tests__/services/telemetry-bootstrap.test.ts b/__tests__/services/telemetry-bootstrap.test.ts
new file mode 100644
index 0000000000..8b9be45fcd
--- /dev/null
+++ b/__tests__/services/telemetry-bootstrap.test.ts
@@ -0,0 +1,87 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+type MockPostHog = {
+ init: ReturnType<typeof vi.fn>;
+ capture: ReturnType<typeof vi.fn>;
+ captureException: ReturnType<typeof vi.fn>;
+ opt_in_capturing: ReturnType<typeof vi.fn>;
+ opt_out_capturing: ReturnType<typeof vi.fn>;
+ has_opted_out_capturing: ReturnType<typeof vi.fn>;
+ identify: ReturnType<typeof vi.fn>;
+ get_property: ReturnType<typeof vi.fn>;
+ reset: ReturnType<typeof vi.fn>;
+};
+
+async function loadTelemetryWithLegacyUser() {
+ let identifiedUserId: string | undefined = "legacy-cloud-user";
+ const mockPosthog: MockPostHog = {
+ init: vi.fn(),
+ capture: vi.fn(),
+ captureException: vi.fn(),
+ opt_in_capturing: vi.fn(),
+ opt_out_capturing: vi.fn(),
+ has_opted_out_capturing: vi.fn(() => false),
+ identify: vi.fn((userId: string) => {
+ identifiedUserId = userId;
+ }),
+ get_property: vi.fn((property: string) =>
+ property === "$user_id" ? identifiedUserId : undefined,
+ ),
+ reset: vi.fn(() => {
+ identifiedUserId = undefined;
+ }),
+ };
+ mockPosthog.init.mockReturnValue(mockPosthog);
+
+ vi.doMock("posthog-js", () => ({
+ default: mockPosthog,
+ }));
+
+ const telemetry = await import("#/services/telemetry");
+ return { telemetry, mockPosthog };
+}
+
+describe("Telemetry bootstrap identity migration", () => {
+ beforeEach(() => {
+ vi.resetModules();
+ vi.clearAllMocks();
+ localStorage.clear();
+ sessionStorage.clear();
+ delete (window as unknown as Record<string, unknown>)
+ .__AGENT_CANVAS_LOCK_TO_CLOUD__;
+ });
+
+ it("clears a legacy identified user when no OAuth bootstrap is present", async () => {
+ const { telemetry, mockPosthog } = await loadTelemetryWithLegacyUser();
+
+ await telemetry.setTelemetryConsent("granted");
+
+ expect(mockPosthog.reset).toHaveBeenCalledWith(false);
+ expect(mockPosthog.opt_in_capturing).toHaveBeenCalled();
+ expect(mockPosthog.identify).not.toHaveBeenCalled();
+ });
+
+ it("preserves OAuth bootstrap identity instead of resetting legacy users", async () => {
+ const { telemetry, mockPosthog } = await loadTelemetryWithLegacyUser();
+
+ telemetry.configurePostHogBootstrap({
+ distinctID: "bootstrapped-browser-id",
+ sessionID: "bootstrapped-session-id",
+ });
+ await telemetry.setTelemetryConsent("granted");
+
+ expect(mockPosthog.reset).not.toHaveBeenCalled();
+ expect(mockPosthog.init).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ bootstrap: {
+ distinctID: "bootstrapped-browser-id",
+ sessionID: "bootstrapped-session-id",
+ },
+ person_profiles: "always",
+ }),
+ "agent-canvas",
+ );
+ expect(mockPosthog.identify).not.toHaveBeenCalled();
+ });
+});
diff --git a/__tests__/services/telemetry.test.ts b/__tests__/services/telemetry.test.ts
index be658081bf..f930db5e4d 100644
--- a/__tests__/services/telemetry.test.ts
+++ b/__tests__/services/telemetry.test.ts
@@ -2,6 +2,9 @@ import { describe, it, expect, beforeEach, vi, afterEach } from "vitest";
// Mock posthog-js before importing telemetry service
let identifiedUserId: string | undefined;
+let latestPostHogConfig:
+ | { before_send: (event: unknown) => unknown }
+ | undefined;
const mockPosthog = {
init: vi.fn(),
capture: vi.fn(),
@@ -19,7 +22,10 @@ const mockPosthog = {
identifiedUserId = undefined;
}),
};
-mockPosthog.init.mockReturnValue(mockPosthog);
+mockPosthog.init.mockImplementation((_, config) => {
+ latestPostHogConfig = config;
+ return mockPosthog;
+});
vi.mock("posthog-js", () => ({
default: mockPosthog,
@@ -32,7 +38,7 @@ import {
getPendingCloudTelemetryConsent,
initializePostHogClient,
setTelemetryConsent,
- setTelemetryIdentity,
+ setTelemetryCloudContext,
setTelemetryBackendContext,
subscribeTelemetryConsent,
isTelemetryEnabled,
@@ -85,7 +91,7 @@ describe("Telemetry Service", () => {
apiHost: undefined,
uiHost: undefined,
});
- mockPosthog.init.mockReturnValueOnce(null).mockReturnValue(mockPosthog);
+ mockPosthog.init.mockImplementationOnce(() => null);
await setTelemetryConsent("granted");
await expect(initializePostHogClient()).resolves.toBe(mockPosthog);
@@ -97,6 +103,7 @@ describe("Telemetry Service", () => {
ui_host: "https://posthog.example.com",
persistence_name: "agent-canvas",
consent_persistence_name: "agent-canvas-consent",
+ person_profiles: "always",
}),
"agent-canvas",
);
@@ -145,55 +152,50 @@ describe("Telemetry Service", () => {
});
});
- describe("identity", () => {
- it("identifies a consented Cloud user", async () => {
+ describe("Cloud context", () => {
+ it("adds Cloud user context without identifying PostHog as the Cloud user", async () => {
await setTelemetryConsent("granted");
- await setTelemetryIdentity("user-a", { email: "[email protected]" });
-
- expect(mockPosthog.identify).toHaveBeenCalledWith("user-a", {
+ setTelemetryCloudContext({
+ userId: "user-a",
});
- });
-
- it("resets before switching Cloud accounts and restores consent", async () => {
- await setTelemetryConsent("granted");
- await setTelemetryIdentity("user-a");
- vi.clearAllMocks();
-
- await setTelemetryIdentity("user-b");
-
- expect(mockPosthog.reset).toHaveBeenCalledWith(false);
- expect(mockPosthog.opt_in_capturing).toHaveBeenCalledOnce();
- expect(mockPosthog.identify).toHaveBeenCalledWith("user-b", {});
- });
-
- it("clears identity on logout without changing the device", async () => {
- await setTelemetryConsent("granted");
- await setTelemetryIdentity("user-a");
- vi.clearAllMocks();
- await setTelemetryIdentity(null);
-
- expect(mockPosthog.reset).toHaveBeenCalledWith(false);
- expect(mockPosthog.opt_in_capturing).toHaveBeenCalledOnce();
expect(mockPosthog.identify).not.toHaveBeenCalled();
+ expect(latestPostHogConfig).toBeDefined();
+ expect(
+ latestPostHogConfig!.before_send({
+ event: "cloud_event",
+ properties: {},
+ }),
+ ).toEqual({
+ event: "cloud_event",
+ properties: expect.objectContaining({
+ cloud_user_id: "user-a",
+ cloud_user_email: "[email protected]",
+ }),
+ });
});
- it("removes identity on denial and reapplies it after consent returns", async () => {
+ it("clears Cloud user context for local events", async () => {
await setTelemetryConsent("granted");
- await setTelemetryIdentity("user-a");
- vi.clearAllMocks();
-
- await setTelemetryConsent("denied");
-
- expect(mockPosthog.reset).toHaveBeenCalledWith(false);
- expect(mockPosthog.opt_out_capturing).toHaveBeenCalled();
- vi.clearAllMocks();
- await setTelemetryConsent("granted");
+ setTelemetryCloudContext({ userId: "user-a", email: "[email protected]" });
+ setTelemetryCloudContext(null);
- expect(mockPosthog.identify).toHaveBeenCalledWith("user-a", {});
+ expect(latestPostHogConfig).toBeDefined();
+ expect(
+ latestPostHogConfig!.before_send({
+ event: "local_event",
+ properties: {},
+ }),
+ ).toEqual({
+ event: "local_event",
+ properties: expect.objectContaining({
+ cloud_user_id: null,
+ cloud_user_email: null,
+ }),
+ });
});
});
diff --git a/src/hooks/use-telemetry-identity.ts b/src/hooks/use-telemetry-identity.ts
index e71ec7c4e7..76af880621 100644
--- a/src/hooks/use-telemetry-identity.ts
+++ b/src/hooks/use-telemetry-identity.ts
@@ -2,9 +2,9 @@ import React from "react";
import { useActiveBackend } from "#/contexts/active-backend-context";
import { useCloudCurrentUserId } from "#/hooks/query/use-cloud-current-user-id";
import { useSettings } from "#/hooks/query/use-settings";
-import { setTelemetryIdentity } from "#/services/telemetry";
+import { setTelemetryCloudContext } from "#/services/telemetry";
-/** Keep the telemetry service aligned with the resolved Cloud account. */
+/** Keep Cloud user event context aligned with the active backend. */
export const useTelemetryIdentity = () => {
const { backend } = useActiveBackend();
const { data: settings } = useSettings();
@@ -15,15 +15,18 @@ export const useTelemetryIdentity = () => {
const email = settings?.email || settings?.git_user_email || undefined;
React.useEffect(() => {
- // A local backend says nothing about Cloud login state. Preserve the last
- // Cloud identity until a Cloud query explicitly resolves it.
- if (backend.kind !== "cloud" || isIdentityLoading) return;
+ if (backend.kind !== "cloud") {
+ setTelemetryCloudContext(null);
+ return;
+ }
+
+ if (isIdentityLoading) return;
if (!userId) {
- void setTelemetryIdentity(null);
+ setTelemetryCloudContext(null);
return;
}
- void setTelemetryIdentity(userId, email ? { email } : {});
+ setTelemetryCloudContext({ userId, email });
}, [backend.kind, email, isIdentityLoading, userId]);
};
diff --git a/src/hooks/use-tracking.ts b/src/hooks/use-tracking.ts
index e12c14fcc2..cffbbf54ea 100644
--- a/src/hooks/use-tracking.ts
+++ b/src/hooks/use-tracking.ts
@@ -1,5 +1,4 @@
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";
@@ -19,7 +18,6 @@ import { setTelemetryBackendContext, trackEvent } from "#/services/telemetry";
* backend settings because they can be stale while a backend changes.
*/
export const useTracking = () => {
- const { data: settings } = useSettings();
const activeBackend = useActiveBackend();
const { backend } = activeBackend;
const [automationSdkVersion, setAutomationSdkVersion] = React.useState<
@@ -69,7 +67,6 @@ export const useTracking = () => {
// Common properties included in all tracking events
const commonProperties = {
current_url: window.location.href,
- user_email: settings?.email || settings?.git_user_email || null,
};
/**
diff --git a/src/services/telemetry-context.ts b/src/services/telemetry-context.ts
index 1f4acf7af8..8228cbe13c 100644
--- a/src/services/telemetry-context.ts
+++ b/src/services/telemetry-context.ts
@@ -4,6 +4,11 @@ export const UNKNOWN_TELEMETRY_VERSION = "unknown";
export type BackendConnectionMethod = "manual" | "cloud_login";
+export interface CloudTelemetryContextInput {
+ userId?: string | null;
+ email?: string | null;
+}
+
export interface BackendTelemetryContextInput {
backendKind?: BackendKind | null;
agentServerVersion?: string | null;
@@ -17,6 +22,13 @@ function normalizeTelemetryVersion(version: string | null | undefined): string {
return trimmed || UNKNOWN_TELEMETRY_VERSION;
}
+function normalizeOptionalProperty(
+ value: string | null | undefined,
+): string | null {
+ const trimmed = value?.trim();
+ return trimmed || null;
+}
+
export function getBackendTelemetryProperties({
backendKind,
agentServerVersion,
@@ -41,3 +53,12 @@ export function getBackendTelemetryProperties({
...(connectionMethod ? { connection_method: connectionMethod } : {}),
};
}
+
+export function getCloudTelemetryProperties(
+ context: CloudTelemetryContextInput | null = null,
+): Record<string, unknown> {
+ return {
+ cloud_user_id: normalizeOptionalProperty(context?.userId),
+ cloud_user_email: normalizeOptionalProperty(context?.email),
+ };
+}
diff --git a/src/services/telemetry.ts b/src/services/telemetry.ts
index eab6c80ceb..265fd4d658 100644
--- a/src/services/telemetry.ts
+++ b/src/services/telemetry.ts
@@ -35,7 +35,9 @@ import {
} from "#/api/client-source";
import {
getBackendTelemetryProperties,
+ getCloudTelemetryProperties,
type BackendTelemetryContextInput,
+ type CloudTelemetryContextInput,
} from "#/services/telemetry-context";
const TELEMETRY_CONSENT_KEY = "openhands-telemetry-consent";
@@ -89,18 +91,6 @@ let pendingBootstrap: BootstrapConfig | undefined;
let telemetryConfig: TelemetryConfig = {};
let telemetryDisabled = false;
-interface TelemetryIdentity {
- distinctId: string;
- properties: Record<string, unknown>;
-}
-
-// undefined means that Cloud identity has not resolved yet; null means that it
-// resolved without a user. This distinction prevents startup from resetting a
-// persisted identity while the current account is still loading.
-let desiredTelemetryIdentity: TelemetryIdentity | null | undefined;
-let desiredIdentityRevision = 0;
-let appliedIdentityRevision = -1;
-
const CANVAS_EVENT_PROPERTIES = Object.freeze({
client_source: AGENT_CANVAS_CLIENT_SOURCE,
client_version: AGENT_CANVAS_CLIENT_VERSION,
@@ -109,6 +99,7 @@ const CANVAS_EVENT_PROPERTIES = Object.freeze({
});
let telemetryBackendContext = getBackendTelemetryProperties({});
+let telemetryCloudContext = getCloudTelemetryProperties();
export function setTelemetryBackendContext(
context: BackendTelemetryContextInput,
@@ -116,6 +107,12 @@ export function setTelemetryBackendContext(
telemetryBackendContext = getBackendTelemetryProperties(context);
}
+export function setTelemetryCloudContext(
+ context: CloudTelemetryContextInput | null,
+): void {
+ telemetryCloudContext = getCloudTelemetryProperties(context);
+}
+
function addCanvasEventProperties(
event: CaptureResult | null,
): CaptureResult | null {
@@ -125,6 +122,7 @@ function addCanvasEventProperties(
...event,
properties: {
...telemetryBackendContext,
+ ...telemetryCloudContext,
...event.properties,
...CANVAS_EVENT_PROPERTIES,
},
@@ -141,47 +139,15 @@ function restorePostHogConsent(posthog: PostHog): void {
function resetPostHogIdentity(posthog: PostHog, resetDeviceId = false): void {
posthog.reset(resetDeviceId);
- appliedIdentityRevision = -1;
// PostHog reset clears its own consent persistence, so immediately restore
// the canonical Canvas decision kept in localStorage.
restorePostHogConsent(posthog);
}
-function applyDesiredTelemetryIdentity(posthog: PostHog): void {
- if (desiredTelemetryIdentity === undefined || !isTelemetryEnabled()) return;
-
- const desiredId = desiredTelemetryIdentity?.distinctId;
- const currentId = posthog.get_property("$user_id");
- if (currentId != null && currentId !== desiredId) {
+function clearLegacyIdentifiedUser(posthog: PostHog): void {
+ if (posthog.get_property?.("$user_id") != null) {
resetPostHogIdentity(posthog);
}
-
- if (desiredTelemetryIdentity === null) {
- appliedIdentityRevision = desiredIdentityRevision;
- return;
- }
-
- if (
- posthog.get_property("$user_id") !== desiredTelemetryIdentity.distinctId ||
- appliedIdentityRevision !== desiredIdentityRevision
- ) {
- posthog.identify(
- desiredTelemetryIdentity.distinctId,
- desiredTelemetryIdentity.properties,
- );
- appliedIdentityRevision = desiredIdentityRevision;
- }
-}
-
-function propertiesEqual(
- left: Record<string, unknown>,
- right: Record<string, unknown>,
-): boolean {
- const keys = Object.keys(left);
- return (
- keys.length === Object.keys(right).length &&
- keys.every((key) => left[key] === right[key])
- );
}
/**
@@ -210,7 +176,6 @@ export function configureTelemetry(config: TelemetryConfiguration): void {
if (wasDisabled) {
if (posthogInstance) {
restorePostHogConsent(posthogInstance);
- applyDesiredTelemetryIdentity(posthogInstance);
}
notifyTelemetryConsentListeners();
}
@@ -328,6 +293,7 @@ export async function initializePostHogClient(
// A named instance isolates Canvas configuration, consent, identity, and
// persistence from a host application's default PostHog singleton.
+ const bootstrap = pendingBootstrap;
const initializedPostHog = posthog.init(
config.apiKey,
{
@@ -339,9 +305,9 @@ export async function initializePostHogClient(
persistence: "localStorage",
persistence_name: POSTHOG_INSTANCE_NAME,
consent_persistence_name: `${POSTHOG_INSTANCE_NAME}-consent`,
- person_profiles: "identified_only",
+ person_profiles: "always",
disable_session_recording: true,
- bootstrap: pendingBootstrap,
+ bootstrap,
before_send: addCanvasEventProperties,
},
POSTHOG_INSTANCE_NAME,
@@ -350,12 +316,14 @@ export async function initializePostHogClient(
posthogInstance = initializedPostHog;
pendingBootstrap = undefined;
+ if (!bootstrap) {
+ clearLegacyIdentifiedUser(posthogInstance);
+ }
if (telemetryDisabled) {
posthogInstance.opt_out_capturing();
} else if (getTelemetryConsent() === "granted") {
posthogInstance.opt_in_capturing();
- applyDesiredTelemetryIdentity(posthogInstance);
} else if (!enableCapturing) {
posthogInstance.opt_out_capturing();
}
@@ -502,9 +470,8 @@ export async function setTelemetryConsent(
if (consent === "granted") {
posthog.opt_in_capturing();
- applyDesiredTelemetryIdentity(posthog);
} else {
- if (posthog.get_property("$user_id") != null) {
+ if (posthog.get_property?.("$user_id") != null) {
resetPostHogIdentity(posthog);
} else {
posthog.opt_out_capturing();
@@ -523,37 +490,6 @@ export async function setTelemetryConsent(
}
}
-/**
- * Declare the current Cloud identity. The telemetry service applies it only
- * after consent and owns all reset/account-switch semantics.
- */
-export async function setTelemetryIdentity(
- distinctId: string | null,
- properties: Record<string, unknown> = {},
-): Promise<void> {
- const nextIdentity = distinctId === null ? null : { distinctId, properties };
- const unchanged =
- desiredTelemetryIdentity === nextIdentity ||
- (desiredTelemetryIdentity !== undefined &&
- desiredTelemetryIdentity !== null &&
- nextIdentity !== null &&
- desiredTelemetryIdentity.distinctId === nextIdentity.distinctId &&
- propertiesEqual(desiredTelemetryIdentity.properties, properties));
- if (unchanged) return;
-
- desiredTelemetryIdentity = nextIdentity;
- desiredIdentityRevision += 1;
- appliedIdentityRevision = -1;
-
- if (!isTelemetryEnabled()) return;
- const posthog = posthogInstance ?? (await initializePostHogClient());
- if (posthog && isTelemetryEnabled()) {
- // Read the desired identity after the await so a newer account always wins
- // if identity changes while the SDK is loading.
- applyDesiredTelemetryIdentity(posthog);
- }
-}
-
/**
* Check if telemetry is enabled (user has granted consent)
*/
@@ -696,8 +632,6 @@ async function getPostHogForConsentedCapture(): Promise<PostHog | null> {
posthog.opt_in_capturing();
}
- applyDesiredTelemetryIdentity(posthog);
-
return posthog;
}
@@ -768,10 +702,8 @@ export async function clearTelemetryData(): Promise<void> {
// Continue clearing the in-memory and SDK identity if storage is blocked.
}
- desiredTelemetryIdentity = null;
- desiredIdentityRevision += 1;
- appliedIdentityRevision = -1;
telemetryBackendContext = getBackendTelemetryProperties({});
+ telemetryCloudContext = getCloudTelemetryProperties();
try {
if (posthogInstance) {