The platform for continuously improving AI agents.
Include user email in PostHog person properties (#284)
Pritam Soni7d5a158c6ae1
diff --git a/frontend/src/analytics.ts b/frontend/src/analytics.tsindex 0f4d739e..98bce5f0 100644--- a/frontend/src/analytics.ts+++ b/frontend/src/analytics.ts@@ -38,8 +38,17 @@ export const trackEvent = (event: string, properties?: Record<string, any>) => {export const identifyUser = ({userId,clerkUserId,-}: Partial<{ userId: string; clerkUserId: string }>) => {+ email,+ name,+}: Partial<{ userId: string; clerkUserId: string; email: string; name: string }>) => {if (userId && clerkUserId) {- void client?.then((posthog) => posthog?.identify(userId, { clerkUserId: clerkUserId }));+ const properties: Record<string, string> = { clerkUserId };+ if (email) properties.email = email;+ if (name) properties.name = name;+ void client?.then((posthog) => posthog?.identify(userId, properties));}};++export const resetUser = () => {+ void client?.then((posthog) => posthog?.reset());+};diff --git a/frontend/src/components/app-sidebar.tsx b/frontend/src/components/app-sidebar.tsxindex 09e853aa..6d7ccf1a 100644--- a/frontend/src/components/app-sidebar.tsx+++ b/frontend/src/components/app-sidebar.tsx@@ -345,10 +345,19 @@ export function AppSidebar({ collapsible = "icon", onSearchOpen }: AppSidebarProconst showPlan = me?.billingEnabled === true;const [feedbackOpen, setFeedbackOpen] = useState(false);const clerkUserId = user?.id ?? "";+ const userEmail = user?.email ?? "";+ const userName = user?.name ?? "";useEffect(() => {trackEvent("login_changed", { isSignedIn });- identifyUser({ clerkUserId, userId: clerkUserId });- }, [isSignedIn, clerkUserId]);+ }, [isSignedIn]);+ useEffect(() => {+ identifyUser({+ clerkUserId,+ email: userEmail || undefined,+ name: userName || undefined,+ userId: clerkUserId,+ });+ }, [clerkUserId, userEmail, userName]);useEffect(() => {const kinds = kindsForPathname(location.pathname);if (kinds) clearUnseenCompletionsForKinds(kinds);diff --git a/frontend/src/contexts/auth-context.tsx b/frontend/src/contexts/auth-context.tsxindex dd1b88af..dcd4ad80 100644--- a/frontend/src/contexts/auth-context.tsx+++ b/frontend/src/contexts/auth-context.tsx@@ -2,7 +2,7 @@ import { createContext, useCallback, useContext, useEffect, useRef, useState } fimport { useAuth, useUser } from "@clerk/clerk-react";-import { trackEvent } from "@/analytics";+import { resetUser, trackEvent } from "@/analytics";import apiClient, {clearTokens,getAccessToken,@@ -113,6 +113,7 @@ function ClerkAuthProvider({ children }: { children: React.ReactNode }) {const handleSignOut = useCallback(async () => {clearTokens();setGuestActive(false);+ resetUser();await signOut();}, [signOut]);@@ -189,6 +190,7 @@ function SelfHostedAuthProvider({ children }: { children: React.ReactNode }) {setIsSignedIn(false);setIsGuest(false);setUser(null);+ resetUser();}, []);const beginGuestSession = useCallback((access: string, refresh: string, projectId: string) => {diff --git a/frontend/src/self-hosted-analytics.test.ts b/frontend/src/self-hosted-analytics.test.tsindex 170337a2..ed0fa6bc 100644--- a/frontend/src/self-hosted-analytics.test.ts+++ b/frontend/src/self-hosted-analytics.test.ts@@ -4,6 +4,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";const posthogInit = vi.fn();const posthogCapture = vi.fn();const posthogIdentify = vi.fn();+const posthogReset = vi.fn();const posthogCaptureException = vi.fn();vi.mock("posthog-js", () => ({@@ -12,6 +13,7 @@ vi.mock("posthog-js", () => ({captureException: posthogCaptureException,identify: posthogIdentify,init: posthogInit,+ reset: posthogReset,},}));@@ -21,6 +23,8 @@ describe("self-hosted PostHog strip", () => {vi.resetModules();posthogInit.mockClear();posthogCapture.mockClear();+ posthogIdentify.mockClear();+ posthogReset.mockClear();});it("skips analytics.ts init when VITE_SELF_HOSTED is true", async () => {@@ -35,8 +39,15 @@ describe("self-hosted PostHog strip", () => {vi.stubEnv("VITE_PUBLIC_POSTHOG_KEY", "phc_test");vi.stubEnv("VITE_PUBLIC_POSTHOG_HOST", "https://analytics.example");vi.stubEnv("MODE", "production");- const { trackEvent } = await import("./analytics");+ const { identifyUser, resetUser, trackEvent } = await import("./analytics");trackEvent("setup_prompt_copied", { project_id: "project-1" });+ identifyUser({+ clerkUserId: "user_123",+ email: "[email protected]",+ name: "Ada Lovelace",+ userId: "user_123",+ });+ resetUser();await vi.dynamicImportSettled();expect(posthogInit).toHaveBeenCalledOnce();expect(posthogInit).toHaveBeenCalledWith(@@ -46,5 +57,11 @@ describe("self-hosted PostHog strip", () => {}));expect(posthogCapture).toHaveBeenCalledWith("setup_prompt_copied", { project_id: "project-1" });+ expect(posthogIdentify).toHaveBeenCalledWith("user_123", {+ clerkUserId: "user_123",+ email: "[email protected]",+ name: "Ada Lovelace",+ });+ expect(posthogReset).toHaveBeenCalledOnce();});});diff --git a/overbae/management/commands/sync_posthog_users.py b/overbae/management/commands/sync_posthog_users.pynew file mode 100644index 00000000..5f9329ef--- /dev/null+++ b/overbae/management/commands/sync_posthog_users.py@@ -0,0 +1,56 @@+"""Backfill PostHog person properties (email, name) for existing registered users."""++from __future__ import annotations++from django.conf import settings+from django.core.management.base import BaseCommand, CommandError+from posthog import Posthog++from overbae.models import User+++class Command(BaseCommand):+ help = "Backfill email and name onto existing PostHog person profiles."++ def add_arguments(self, parser):+ parser.add_argument(+ "--dry-run",+ action="store_true",+ help="Count eligible users without sending events to PostHog.",+ )++ def handle(self, *args, **options):+ dry_run = bool(options["dry_run"])+ if not dry_run and not settings.POSTHOG_PROJECT_TOKEN:+ raise CommandError("POSTHOG_PROJECT_TOKEN is not configured.")++ users = list(+ User.objects.filter(is_guest=False, is_active=True)+ .exclude(clerk_user_id="")+ .exclude(email="")+ .order_by("id")+ )+ if dry_run:+ self.stdout.write(self.style.SUCCESS(f"dry_run=True users={len(users)}"))+ return++ client = Posthog(+ settings.POSTHOG_PROJECT_TOKEN,+ host=settings.POSTHOG_HOST,+ enable_local_evaluation=False,+ )+ try:+ for user in users:+ traits: dict[str, str] = {+ "clerkUserId": user.clerk_user_id,+ "email": user.email,+ "overmind_user_id": str(user.pk),+ }+ name = user.get_full_name().strip()+ if name:+ traits["name"] = name+ client.set(distinct_id=user.clerk_user_id, properties=traits)+ finally:+ client.shutdown()++ self.stdout.write(self.style.SUCCESS(f"synced={len(users)}"))diff --git a/overbae/services/mcp/server.py b/overbae/services/mcp/server.pyindex 1d60e030..7d624eb6 100644--- a/overbae/services/mcp/server.py+++ b/overbae/services/mcp/server.py@@ -140,8 +140,11 @@ async def _read_resource(uri):def _identify(_request, _extra) -> UserIdentity | None:- clerk_user_id = get_context().user.clerk_user_id- return UserIdentity(distinct_id=clerk_user_id) if clerk_user_id else None+ user = get_context().user+ if not user.clerk_user_id:+ return None+ properties = {"email": user.email} if user.email and not user.is_guest else None+ return UserIdentity(distinct_id=user.clerk_user_id, properties=properties)def _project_properties(request, _extra) -> dict[str, str]:diff --git a/overmind/overmind/__init__.py b/overmind/overmind/__init__.pyindex 2e6be629..885eb55b 100644--- a/overmind/overmind/__init__.py+++ b/overmind/overmind/__init__.py@@ -10,7 +10,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Any-__version__ = "0.1.116"+__version__ = "0.1.117"from .client import Client, ModelDeleted, OvermindInferenceErrordiff --git a/overmind/overmind/analytics.py b/overmind/overmind/analytics.pyindex e1ba43c6..1ef3a399 100644--- a/overmind/overmind/analytics.py+++ b/overmind/overmind/analytics.py@@ -216,7 +216,7 @@ def ensure_identified(*, api_key: str | None = None, base_url: str | None = None_identify_attempted = Truecached = _load_identity_cache()- if cached and cached.get("key_fp") == fingerprint and cached.get("distinct_id"):+ if cached and cached.get("key_fp") == fingerprint and cached.get("distinct_id") and "email" in cached:_identified_distinct_id = str(cached["distinct_id"])return True@@ -229,9 +229,11 @@ def ensure_identified(*, api_key: str | None = None, base_url: str | None = Noneif not distinct:return False+ email = str(me.get("email") or "").strip() if not me.get("is_guest") else ""traits = {"sdk_surface": "python","overmind_user_id": str(me.get("id") or ""),+ "email": email or None,"plan": me.get("plan"),"is_guest": me.get("is_guest"),"project_id": _project_id(),@@ -249,6 +251,7 @@ def ensure_identified(*, api_key: str | None = None, base_url: str | None = None"key_fp": fingerprint,"distinct_id": distinct,"overmind_user_id": str(me.get("id") or ""),+ "email": email,})return Trueexcept Exception:diff --git a/overmind/pyproject.toml b/overmind/pyproject.tomlindex ef91b325..acd4af2a 100644--- a/overmind/pyproject.toml+++ b/overmind/pyproject.toml@@ -46,7 +46,7 @@ license = { text = "MIT" }name = "overmind"readme = "README.md"requires-python = ">=3.10,<4" # todo; remove the upper bound-version = "0.1.116"+version = "0.1.117"[project.urls]"Agent setup" = "https://console.overmindlab.ai/setup.md"diff --git a/overmind/tests/test_analytics.py b/overmind/tests/test_analytics.pyindex d9a1c063..91ea9437 100644--- a/overmind/tests/test_analytics.py+++ b/overmind/tests/test_analytics.py@@ -194,7 +194,13 @@ def test_ensure_identified_caches_per_key(monkeypatch, tmp_path, posthog_client)def fake_me(api_key, base_url):me_calls["n"] += 1- return {"id": "user-1", "clerk_user_id": "user_clerk_1", "plan": "free", "is_guest": False}+ return {+ "id": "user-1",+ "clerk_user_id": "user_clerk_1",+ "email": "[email protected]",+ "plan": "free",+ "is_guest": False,+ }monkeypatch.setattr(analytics, "_fetch_me", fake_me)@@ -208,4 +214,5 @@ def test_ensure_identified_caches_per_key(monkeypatch, tmp_path, posthog_client)assert call.args == ("$identify",)assert call.kwargs["distinct_id"] == "user_clerk_1"assert call.kwargs["properties"]["$anon_distinct_id"]+ assert call.kwargs["properties"]["$set"]["email"] == "[email protected]"assert call.kwargs["properties"]["$set"]["plan"] == "free"diff --git a/overmind/uv.lock b/overmind/uv.lockindex ab6b2c1d..25f75d8f 100644--- a/overmind/uv.lock+++ b/overmind/uv.lock@@ -1,9 +1,9 @@version = 1-revision = 5+revision = 3requires-python = ">=3.10, <4"resolution-markers = ["python_full_version >= '3.12' and sys_platform == 'emscripten'",- "python_full_version == '3.11.*' or (python_full_version >= '3.12' and sys_platform != 'emscripten')",+ "(python_full_version >= '3.11' and sys_platform != 'emscripten') or (python_full_version == '3.11.*' and sys_platform == 'emscripten')","python_full_version < '3.11'",]@@ -300,7 +300,7 @@ name = "exceptiongroup"version = "1.3.1"source = { registry = "https://pypi.org/simple" }dependencies = [- { name = "typing-extensions" },+ { name = "typing-extensions", marker = "python_full_version < '3.11'" },]sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" }wheels = [@@ -351,8 +351,8 @@ name = "httpcore2"version = "2.13.1"source = { registry = "https://pypi.org/simple" }dependencies = [- { name = "h11" },- { name = "truststore" },+ { name = "h11", marker = "python_full_version < '3.12' or sys_platform != 'emscripten'" },+ { name = "truststore", marker = "python_full_version < '3.12' or sys_platform != 'emscripten'" },]sdist = { url = "https://files.pythonhosted.org/packages/cb/f3/1db7aa2bc2524062192bb0e0323969492d1883152a232fe36eea65f4e35c/httpcore2-2.13.1.tar.gz", hash = "sha256:e0aa977abe17e69a3b820a24542a6fa88702676d83880b8d194dcd18408e5103", size = 68071, upload-time = "2026-09-23T07:47:22.372Z" }wheels = [@@ -923,7 +923,7 @@ wheels = [[[package]]name = "overmind"-version = "0.1.116"+version = "0.1.117"source = { editable = "." }dependencies = [{ name = "packaging" },diff --git a/tests/test_mcp_analytics.py b/tests/test_mcp_analytics.pyindex d3165603..bcd62df3 100644--- a/tests/test_mcp_analytics.py+++ b/tests/test_mcp_analytics.py@@ -7,6 +7,7 @@ import uuidfrom http.server import BaseHTTPRequestHandler, HTTPServerimport pytest+from django.core.management import call_commandfrom mcp.server.lowlevel import Serverfrom mcp_fixtures import asgi_dbfrom posthog import Posthog@@ -144,6 +145,7 @@ def test_every_tool_call_reaches_posthog_as_metadata_only(instrumented):assert properties["$mcp_server_name"] == "overmind-platform"assert properties["$mcp_client_name"] == "analytics-e2e"assert event["distinct_id"] == user.clerk_user_id+ assert properties["$set"] == {"email": user.email}captured.setdefault(properties["$mcp_tool_name"], []).append((properties["$mcp_is_error"],@@ -185,3 +187,38 @@ def test_failed_ingest_does_not_fail_tool_calls(instrumented):assert result.get("isError") is not Trueassert result["structuredContent"]["total"] == 1+++def test_sync_posthog_users_backfills_non_guest_profiles(ingest, settings):+ settings.POSTHOG_PROJECT_TOKEN = "phc_test"+ settings.POSTHOG_HOST = f"http://127.0.0.1:{ingest.server_port}"++ active = User.objects.create_user(+ email="[email protected]",+ password="pw",+ clerk_user_id="user_ada",+ first_name="Ada",+ last_name="Lovelace",+ )+ User.objects.create_user(+ email="[email protected]",+ password=None,+ clerk_user_id="guest_123",+ is_guest=True,+ )++ call_command("sync_posthog_users")++ set_events = [+ event+ for event in ingest.events+ if event["event"] == "$set" and event["distinct_id"] == active.clerk_user_id+ ]+ assert len(set_events) == 1+ assert set_events[0]["$set"] == {+ "clerkUserId": "user_ada",+ "email": "[email protected]",+ "name": "Ada Lovelace",+ "overmind_user_id": str(active.pk),+ }+ assert all(event["distinct_id"] != "guest_123" for event in ingest.events)