π OpenHands: AI-Driven Development
fix(frontend): restore cross-domain PostHog tracking by aligning client/server distinct_id (WIP) (#15100)
Lila Garciaf17e8e50b716
diff --git a/frontend/__tests__/hooks/mutation/use-add-git-providers.test.tsx b/frontend/__tests__/hooks/mutation/use-add-git-providers.test.tsxindex 0862dce1ff..037ce430c4 100644--- a/frontend/__tests__/hooks/mutation/use-add-git-providers.test.tsx+++ b/frontend/__tests__/hooks/mutation/use-add-git-providers.test.tsx@@ -6,14 +6,6 @@ import { SecretsService } from "#/api/secrets-service";import { useAddGitProviders } from "#/hooks/mutation/use-add-git-providers";import { Provider, ProviderToken } from "#/types/settings";-const mockTrackGitProviderConnected = vi.fn();--vi.mock("#/hooks/use-tracking", () => ({- useTracking: () => ({- trackGitProviderConnected: mockTrackGitProviderConnected,- }),-}));-vi.mock("#/context/use-selected-organization", () => ({useSelectedOrganizationId: () => ({ organizationId: "org-1" }),}));@@ -36,7 +28,6 @@ describe("useAddGitProviders", () => {beforeEach(() => {vi.restoreAllMocks();- mockTrackGitProviderConnected.mockReset();queryClient = new QueryClient({defaultOptions: {queries: { retry: false },diff --git a/frontend/__tests__/hooks/use-git-user.test.tsx b/frontend/__tests__/hooks/use-git-user.test.tsxindex b1427a8fba..aeac647167 100644--- a/frontend/__tests__/hooks/use-git-user.test.tsx+++ b/frontend/__tests__/hooks/use-git-user.test.tsx@@ -13,11 +13,6 @@ vi.mock("#/hooks/use-should-show-git-features");vi.mock("#/hooks/query/use-config");vi.mock("#/hooks/mutation/use-logout");vi.mock("#/api/user-service/user-service.api");-vi.mock("posthog-js/react", () => ({- usePostHog: vi.fn(() => ({- identify: vi.fn(),- })),-}));describe("useGitUser", () => {let mockLogout: ReturnType<typeof useLogout>;diff --git a/frontend/__tests__/hooks/use-posthog-identify.test.tsx b/frontend/__tests__/hooks/use-posthog-identify.test.tsxnew file mode 100644index 0000000000..9595adb5d4--- /dev/null+++ b/frontend/__tests__/hooks/use-posthog-identify.test.tsx@@ -0,0 +1,232 @@+import { describe, expect, it, vi, beforeEach } from "vitest";+import { renderHook, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import React from "react";+import { usePostHogIdentify } from "#/hooks/use-posthog-identify";+import * as useConfigModule from "#/hooks/query/use-config";+import * as useMeModule from "#/hooks/query/use-me";+import * as useGitUserModule from "#/hooks/query/use-git-user";+import * as useSettingsModule from "#/hooks/query/use-settings";++const mockIdentify = vi.fn();+const mockReset = vi.fn();+vi.mock("posthog-js/react", () => ({+ usePostHog: vi.fn(() => ({+ identify: mockIdentify,+ reset: mockReset,+ })),+}));+vi.mock("#/hooks/query/use-config");+vi.mock("#/hooks/query/use-me");+vi.mock("#/hooks/query/use-git-user");+vi.mock("#/hooks/query/use-settings");++describe("usePostHogIdentify", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(useMeModule.useMe).mockReturnValue({+ data: undefined,+ } as any);+ vi.mocked(useGitUserModule.useGitUser).mockReturnValue({+ data: undefined,+ } as any);+ // Default to consent granted so existing identify tests exercise the+ // happy path; individual tests override as needed.+ vi.mocked(useSettingsModule.useSettings).mockReturnValue({+ data: { user_consents_to_analytics: true },+ } as any);+ });++ const createWrapper = () => {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return ({ children }: { children: React.ReactNode }) => (+ <QueryClientProvider client={queryClient}>+ {children}+ </QueryClientProvider>+ );+ };++ it("should identify with keycloak user_id in SaaS mode", async () => {+ vi.mocked(useConfigModule.useConfig).mockReturnValue({+ data: { app_mode: "saas" },+ } as any);+ vi.mocked(useMeModule.useMe).mockReturnValue({+ data: { user_id: "keycloak-123", email: "[email protected]" },+ } as any);++ renderHook(() => usePostHogIdentify(), { wrapper: createWrapper() });++ await waitFor(() => {+ expect(mockIdentify).toHaveBeenCalledWith("keycloak-123", {+ email: "[email protected]",+ });+ });+ });++ it("should identify with git login in OSS mode", async () => {+ vi.mocked(useConfigModule.useConfig).mockReturnValue({+ data: { app_mode: "oss" },+ } as any);+ vi.mocked(useGitUserModule.useGitUser).mockReturnValue({+ data: {+ login: "devuser",+ name: "Dev User",+ email: "[email protected]",+ company: "Acme",+ },+ } as any);++ renderHook(() => usePostHogIdentify(), { wrapper: createWrapper() });++ await waitFor(() => {+ expect(mockIdentify).toHaveBeenCalledWith("devuser", {+ company: "Acme",+ name: "Dev User",+ email: "[email protected]",+ user: "devuser",+ mode: "oss",+ });+ });+ });++ it("should not identify when config is not loaded", () => {+ vi.mocked(useConfigModule.useConfig).mockReturnValue({+ data: undefined,+ } as any);++ renderHook(() => usePostHogIdentify(), { wrapper: createWrapper() });++ expect(mockIdentify).not.toHaveBeenCalled();+ });++ it("should not identify in SaaS mode until me data is available", () => {+ vi.mocked(useConfigModule.useConfig).mockReturnValue({+ data: { app_mode: "saas" },+ } as any);+ vi.mocked(useMeModule.useMe).mockReturnValue({+ data: undefined,+ } as any);++ renderHook(() => usePostHogIdentify(), { wrapper: createWrapper() });++ expect(mockIdentify).not.toHaveBeenCalled();+ });++ it("should only identify once even when data changes", async () => {+ vi.mocked(useConfigModule.useConfig).mockReturnValue({+ data: { app_mode: "saas" },+ } as any);+ vi.mocked(useMeModule.useMe).mockReturnValue({+ data: { user_id: "keycloak-123", email: "[email protected]" },+ } as any);++ const { rerender } = renderHook(() => usePostHogIdentify(), {+ wrapper: createWrapper(),+ });++ await waitFor(() => {+ expect(mockIdentify).toHaveBeenCalledTimes(1);+ });++ // Rerender to simulate data changes+ rerender();++ expect(mockIdentify).toHaveBeenCalledTimes(1);+ });++ it("should not identify when analytics consent has not been given", () => {+ vi.mocked(useConfigModule.useConfig).mockReturnValue({+ data: { app_mode: "saas" },+ } as any);+ vi.mocked(useMeModule.useMe).mockReturnValue({+ data: { user_id: "keycloak-123", email: "[email protected]" },+ } as any);+ vi.mocked(useSettingsModule.useSettings).mockReturnValue({+ data: { user_consents_to_analytics: false },+ } as any);++ renderHook(() => usePostHogIdentify(), { wrapper: createWrapper() });++ expect(mockIdentify).not.toHaveBeenCalled();+ });++ it("should not identify while consent decision is pending (null)", () => {+ vi.mocked(useConfigModule.useConfig).mockReturnValue({+ data: { app_mode: "saas" },+ } as any);+ vi.mocked(useMeModule.useMe).mockReturnValue({+ data: { user_id: "keycloak-123", email: "[email protected]" },+ } as any);+ vi.mocked(useSettingsModule.useSettings).mockReturnValue({+ data: { user_consents_to_analytics: null },+ } as any);++ renderHook(() => usePostHogIdentify(), { wrapper: createWrapper() });++ expect(mockIdentify).not.toHaveBeenCalled();+ });++ it("should not identify until settings are loaded", () => {+ vi.mocked(useConfigModule.useConfig).mockReturnValue({+ data: { app_mode: "saas" },+ } as any);+ vi.mocked(useMeModule.useMe).mockReturnValue({+ data: { user_id: "keycloak-123", email: "[email protected]" },+ } as any);+ vi.mocked(useSettingsModule.useSettings).mockReturnValue({+ data: undefined,+ } as any);++ renderHook(() => usePostHogIdentify(), { wrapper: createWrapper() });++ expect(mockIdentify).not.toHaveBeenCalled();+ });++ it("should reset when consent is revoked after a prior identify", async () => {+ vi.mocked(useConfigModule.useConfig).mockReturnValue({+ data: { app_mode: "saas" },+ } as any);+ vi.mocked(useMeModule.useMe).mockReturnValue({+ data: { user_id: "keycloak-123", email: "[email protected]" },+ } as any);+ vi.mocked(useSettingsModule.useSettings).mockReturnValue({+ data: { user_consents_to_analytics: true },+ } as any);++ const { rerender } = renderHook(() => usePostHogIdentify(), {+ wrapper: createWrapper(),+ });++ await waitFor(() => {+ expect(mockIdentify).toHaveBeenCalledTimes(1);+ });++ // Revoke consent+ vi.mocked(useSettingsModule.useSettings).mockReturnValue({+ data: { user_consents_to_analytics: false },+ } as any);+ rerender();++ await waitFor(() => {+ expect(mockReset).toHaveBeenCalledTimes(1);+ });+ });++ it("should not reset when consent is false and no prior identify happened", () => {+ vi.mocked(useConfigModule.useConfig).mockReturnValue({+ data: { app_mode: "saas" },+ } as any);+ vi.mocked(useMeModule.useMe).mockReturnValue({+ data: { user_id: "keycloak-123", email: "[email protected]" },+ } as any);+ vi.mocked(useSettingsModule.useSettings).mockReturnValue({+ data: { user_consents_to_analytics: false },+ } as any);++ renderHook(() => usePostHogIdentify(), { wrapper: createWrapper() });++ expect(mockReset).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/hooks/query/use-git-user.ts b/frontend/src/hooks/query/use-git-user.tsindex 6be1b2c272..df6ba2c4e5 100644--- a/frontend/src/hooks/query/use-git-user.ts+++ b/frontend/src/hooks/query/use-git-user.ts@@ -1,13 +1,11 @@import { useQuery } from "@tanstack/react-query";import React from "react";-import { usePostHog } from "posthog-js/react";import { useConfig } from "./use-config";import UserService from "#/api/user-service/user-service.api";import { useShouldShowGitFeatures } from "#/hooks/use-should-show-git-features";import { useLogout } from "../mutation/use-logout";export const useGitUser = () => {- const posthog = usePostHog();const { data: config } = useConfig();const logout = useLogout();@@ -24,18 +22,6 @@ export const useGitUser = () => {gcTime: 1000 * 60 * 15, // 15 minutes});- React.useEffect(() => {- if (user.data) {- posthog.identify(user.data.login, {- company: user.data.company,- name: user.data.name,- email: user.data.email,- user: user.data.login,- mode: config?.app_mode || "oss",- });- }- }, [user.data]);-// In saas mode, a 401 means that the integration tokens need to be// refreshed. Since this happens at login, we log out.// In oss mode, skip auto-logout since there's no token refresh mechanismdiff --git a/frontend/src/hooks/use-posthog-identify.ts b/frontend/src/hooks/use-posthog-identify.tsnew file mode 100644index 0000000000..992cadae53--- /dev/null+++ b/frontend/src/hooks/use-posthog-identify.ts@@ -0,0 +1,64 @@+import React from "react";+import { usePostHog } from "posthog-js/react";+import { useConfig } from "./query/use-config";+import { useMe } from "./query/use-me";+import { useGitUser } from "./query/use-git-user";+import { useSettings } from "./query/use-settings";++/**+ * Identifies the current user to PostHog using the same distinct_id+ * that the server-side AnalyticsService uses (keycloak user_id in SaaS+ * mode). This ensures cross-domain tracking works: the anonymous+ * distinct_id bootstrapped from the marketing site gets merged with+ * the keycloak user_id that every server-side event uses.+ *+ * In OSS mode, falls back to the Git user login.+ *+ * Identification is gated on analytics consent, matching the agent canvas+ * UI:+ * - consent === true β posthog.identify(...)+ * - consent === false β posthog.reset() (undo a prior identify)+ * - consent === null / settings loading β no-op (wait for a decision)+ */+export const usePostHogIdentify = () => {+ const posthog = usePostHog();+ const { data: config } = useConfig();+ const { data: me } = useMe();+ const { data: gitUser } = useGitUser();+ const { data: settings } = useSettings();+ const hasIdentifiedRef = React.useRef(false);++ const consent = settings?.user_consents_to_analytics;++ React.useEffect(() => {+ if (!posthog || settings === undefined) return;++ // Reset on explicit denial to undo any prior identify.+ if (consent === false) {+ if (hasIdentifiedRef.current) {+ posthog.reset();+ hasIdentifiedRef.current = false;+ }+ return;+ }++ // Wait for an explicit consent decision before identifying.+ if (consent !== true || hasIdentifiedRef.current) return;++ if (config?.app_mode === "saas" && me?.user_id) {+ posthog.identify(me.user_id, {+ email: me.email,+ });+ hasIdentifiedRef.current = true;+ } else if (config?.app_mode === "oss" && gitUser) {+ posthog.identify(gitUser.login, {+ company: gitUser.company,+ name: gitUser.name,+ email: gitUser.email,+ user: gitUser.login,+ mode: "oss",+ });+ hasIdentifiedRef.current = true;+ }+ }, [posthog, config?.app_mode, me, gitUser, consent, settings]);+};diff --git a/frontend/src/routes/root-layout.tsx b/frontend/src/routes/root-layout.tsxindex dc365ffb70..70fe34b6bf 100644--- a/frontend/src/routes/root-layout.tsx+++ b/frontend/src/routes/root-layout.tsx@@ -32,6 +32,7 @@ import { cn } from "#/utils/utils";import { LoadingSpinner } from "#/components/shared/loading-spinner";import { useAppTitle } from "#/hooks/use-app-title";import { useAutoAcceptInvitation } from "#/hooks/use-auto-accept-invitation";+import { usePostHogIdentify } from "#/hooks/use-posthog-identify";export function ErrorBoundary() {const error = useRouteError();@@ -101,6 +102,9 @@ export default function MainApp() {// Sync PostHog opt-in/out state with backend setting on mountuseSyncPostHogConsent();+ // Identify the user to PostHog using the same distinct_id as the server+ usePostHogIdentify();+// Auto-select the first organization when none is selecteduseAutoSelectOrganization();