Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

chore(analytics): retire redundant PostHog tracking (MUL-4127) (#4996)

Bohan Jiang3cb5dc3ad683
diff --git a/apps/desktop/src/renderer/src/App.tsx b/apps/desktop/src/renderer/src/App.tsx
index 369cdf095c..9e53238683 100644
--- a/apps/desktop/src/renderer/src/App.tsx
+++ b/apps/desktop/src/renderer/src/App.tsx
@@ -13,7 +13,6 @@ import { MulticaIcon } from "@multica/ui/components/common/multica-icon";
import { Toaster } from "@multica/ui/components/ui/sonner";
import { DesktopLoginPage } from "./pages/login";
import { DesktopShell } from "./components/desktop-layout";
-import { PageviewTracker } from "./components/pageview-tracker";
import { UpdateNotification } from "./components/update-notification";
import { useTabStore } from "./stores/tab-store";
import { useWindowOverlayStore } from "./stores/window-overlay-store";
@@ -277,15 +276,7 @@ function AppContent() {
);
}
- // Pageview tracker sits at the app root so it covers every visible
- // surface (login, overlays, tab paths) — mounting it inside DesktopShell
- // would miss the logged-out and overlay states.
- return (
- <>
- <PageviewTracker />
- {user ? <DesktopShell /> : <DesktopLoginPage />}
- </>
- );
+ return user ? <DesktopShell /> : <DesktopLoginPage />;
}
function BlockingRuntimeConfigError({ message }: { message: string }) {
diff --git a/apps/desktop/src/renderer/src/components/pageview-tracker.test.tsx b/apps/desktop/src/renderer/src/components/pageview-tracker.test.tsx
deleted file mode 100644
index 9a0e6e185c..0000000000
--- a/apps/desktop/src/renderer/src/components/pageview-tracker.test.tsx
+++ /dev/null
@@ -1,247 +0,0 @@
-import { describe, expect, it, vi, beforeEach } from "vitest";
-import { render } from "@testing-library/react";
-
-// vi.hoisted shared state — every store mock reads the same object so each
-// test can mutate it then re-render to drive the tracker.
-const state = vi.hoisted(() => ({
- user: null as { id: string } | null,
- overlay: null as { type: string; invitationId?: string } | null,
- activeWorkspaceSlug: null as string | null,
- byWorkspace: {} as Record<
- string,
- { activeTabId: string; tabs: { id: string; path: string }[] }
- >,
- capturePageview: vi.fn<(path?: string) => void>(),
-}));
-
-vi.mock("@multica/core/analytics", () => ({
- capturePageview: state.capturePageview,
-}));
-
-// Auth store — single selector pattern (`s => s.user`).
-vi.mock("@multica/core/auth", () => {
- const useAuthStore = (selector: (s: typeof state) => unknown) =>
- selector(state);
- return { useAuthStore };
-});
-
-// Window overlay store — same shape.
-vi.mock("@/stores/window-overlay-store", () => {
- const useWindowOverlayStore = (selector: (s: typeof state) => unknown) =>
- selector(state);
- return { useWindowOverlayStore };
-});
-
-// Tab store — selectors read activeWorkspaceSlug + byWorkspace. Also expose
-// getState() for the seed pass and the helpers the tracker imports
-// (useActiveTabIdentity, getActiveTab) so we don't have to re-import them
-// from the real store inside a mocked module.
-vi.mock("@/stores/tab-store", () => {
- const useTabStore = Object.assign(
- (selector: (s: typeof state) => unknown) => selector(state),
- { getState: () => state },
- );
- const getActiveTab = (s: typeof state) => {
- const slug = s.activeWorkspaceSlug;
- if (!slug) return null;
- const group = s.byWorkspace[slug];
- if (!group) return null;
- return group.tabs.find((t) => t.id === group.activeTabId) ?? null;
- };
- const useActiveTabIdentity = () => ({
- slug: state.activeWorkspaceSlug,
- tabId: state.activeWorkspaceSlug
- ? (state.byWorkspace[state.activeWorkspaceSlug]?.activeTabId ?? null)
- : null,
- });
- return { useTabStore, getActiveTab, useActiveTabIdentity };
-});
-
-import { PageviewTracker } from "./pageview-tracker";
-
-function reset() {
- state.user = { id: "u1" };
- state.overlay = null;
- state.activeWorkspaceSlug = null;
- state.byWorkspace = {};
- state.capturePageview.mockClear();
-}
-
-beforeEach(() => {
- reset();
-});
-
-describe("PageviewTracker", () => {
- it("suppresses pageview when switching to a previously-visible tab on its existing path", () => {
- state.byWorkspace = {
- acme: {
- activeTabId: "tA",
- tabs: [
- { id: "tA", path: "/acme/issues" },
- { id: "tB", path: "/acme/inbox" },
- ],
- },
- };
- state.activeWorkspaceSlug = "acme";
-
- const { rerender } = render(<PageviewTracker />);
- // Initial mount on tA — seeded as observed, no pageview because both
- // tabs were already in the persisted store before the tracker mounted.
- expect(state.capturePageview).not.toHaveBeenCalled();
-
- // Switch to tB (already-known tab on its already-known path).
- state.byWorkspace = {
- acme: {
- activeTabId: "tB",
- tabs: [
- { id: "tA", path: "/acme/issues" },
- { id: "tB", path: "/acme/inbox" },
- ],
- },
- };
- rerender(<PageviewTracker />);
- expect(state.capturePageview).not.toHaveBeenCalled();
-
- // Switch back to tA — still no pageview.
- state.byWorkspace = {
- acme: {
- activeTabId: "tA",
- tabs: [
- { id: "tA", path: "/acme/issues" },
- { id: "tB", path: "/acme/inbox" },
- ],
- },
- };
- rerender(<PageviewTracker />);
- expect(state.capturePageview).not.toHaveBeenCalled();
- });
-
- it("fires pageview when a foreground tab is added (addTab path)", () => {
- state.byWorkspace = {
- acme: {
- activeTabId: "tA",
- tabs: [{ id: "tA", path: "/acme/issues" }],
- },
- };
- state.activeWorkspaceSlug = "acme";
-
- const { rerender } = render(<PageviewTracker />);
- state.capturePageview.mockClear();
-
- // Simulate a foreground new-tab action (e.g. an explicit "Open in new
- // tab" toolbar button that passes `{ activate: true }`) — tC is
- // appended AND becomes active. `openInNewTab` defaults to background
- // (no `setActiveTab`); only the `activate: true` branch produces the
- // state change this test exercises.
- state.byWorkspace = {
- acme: {
- activeTabId: "tC",
- tabs: [
- { id: "tA", path: "/acme/issues" },
- { id: "tC", path: "/acme/agents" },
- ],
- },
- };
- rerender(<PageviewTracker />);
-
- expect(state.capturePageview).toHaveBeenCalledTimes(1);
- expect(state.capturePageview).toHaveBeenCalledWith("/acme/agents");
- });
-
- it("fires pageview when switchWorkspace opens a new path in another workspace", () => {
- state.byWorkspace = {
- acme: {
- activeTabId: "tA",
- tabs: [{ id: "tA", path: "/acme/issues" }],
- },
- };
- state.activeWorkspaceSlug = "acme";
-
- const { rerender } = render(<PageviewTracker />);
- state.capturePageview.mockClear();
-
- // Cross-workspace navigation: switchWorkspace("butter", "/butter/inbox")
- // creates a fresh tab in the destination workspace and makes it active.
- state.byWorkspace = {
- acme: { activeTabId: "tA", tabs: [{ id: "tA", path: "/acme/issues" }] },
- butter: {
- activeTabId: "tD",
- tabs: [{ id: "tD", path: "/butter/inbox" }],
- },
- };
- state.activeWorkspaceSlug = "butter";
- rerender(<PageviewTracker />);
-
- expect(state.capturePageview).toHaveBeenCalledTimes(1);
- expect(state.capturePageview).toHaveBeenCalledWith("/butter/inbox");
- });
-
- it("fires pageview on intra-tab navigation (path changes for the same tabId)", () => {
- state.byWorkspace = {
- acme: {
- activeTabId: "tA",
- tabs: [{ id: "tA", path: "/acme/issues" }],
- },
- };
- state.activeWorkspaceSlug = "acme";
-
- const { rerender } = render(<PageviewTracker />);
- state.capturePageview.mockClear();
-
- state.byWorkspace = {
- acme: {
- activeTabId: "tA",
- tabs: [{ id: "tA", path: "/acme/issues/123" }],
- },
- };
- rerender(<PageviewTracker />);
-
- expect(state.capturePageview).toHaveBeenCalledTimes(1);
- expect(state.capturePageview).toHaveBeenCalledWith("/acme/issues/123");
- });
-
- it("fires overlay and login pageviews and suppresses re-entry into the same tab afterward", () => {
- state.byWorkspace = {
- acme: {
- activeTabId: "tA",
- tabs: [{ id: "tA", path: "/acme/issues" }],
- },
- };
- state.activeWorkspaceSlug = "acme";
-
- const { rerender } = render(<PageviewTracker />);
- state.capturePageview.mockClear();
-
- // Open onboarding overlay.
- state.overlay = { type: "onboarding" };
- rerender(<PageviewTracker />);
- expect(state.capturePageview).toHaveBeenLastCalledWith("/onboarding");
-
- // Close overlay back to the tab — the tab is already observed on
- // /acme/issues so this is a re-activation, no pageview.
- state.capturePageview.mockClear();
- state.overlay = null;
- rerender(<PageviewTracker />);
- expect(state.capturePageview).not.toHaveBeenCalled();
-
- // Logout fires /login.
- state.user = null;
- rerender(<PageviewTracker />);
- expect(state.capturePageview).toHaveBeenLastCalledWith("/login");
- });
-
- it("suppresses on initial mount when the active tab was restored from persistence", () => {
- state.byWorkspace = {
- acme: {
- activeTabId: "tA",
- tabs: [{ id: "tA", path: "/acme/issues" }],
- },
- };
- state.activeWorkspaceSlug = "acme";
-
- render(<PageviewTracker />);
- // Restored tab — seeded, treated as a re-activation.
- expect(state.capturePageview).not.toHaveBeenCalled();
- });
-});
-
diff --git a/apps/desktop/src/renderer/src/components/pageview-tracker.tsx b/apps/desktop/src/renderer/src/components/pageview-tracker.tsx
deleted file mode 100644
index 6afdcc4c1f..0000000000
--- a/apps/desktop/src/renderer/src/components/pageview-tracker.tsx
+++ /dev/null
@@ -1,144 +0,0 @@
-import { useEffect, useRef } from "react";
-import { capturePageview } from "@multica/core/analytics";
-import { useAuthStore } from "@multica/core/auth";
-import {
- getActiveTab,
- useActiveTabIdentity,
- useTabStore,
-} from "@/stores/tab-store";
-import { useWindowOverlayStore, type WindowOverlay } from "@/stores/window-overlay-store";
-import type { RendererRouteContextInput } from "../../../shared/renderer-route-context";
-
-/**
- * Fires a PostHog $pageview whenever the user's visible surface changes,
- * EXCEPT for re-activations of an already-known tab on its already-known
- * path.
- *
- * Desktop has three layers that can own the visible page:
- *
- * 1. Logged-out state → `/login`. No workspace context, no tabs.
- * 2. Window overlays (onboarding, new-workspace, invite) → synthetic paths
- * that match the equivalent web routes. Overlays are NOT tab routes on
- * desktop (see `stores/window-overlay-store.ts` + `routes.tsx`), so the
- * tab path alone would either miss them or mislabel them as "/".
- * 3. Otherwise → the active tab's path (workspace-scoped, e.g.
- * `/acme/issues/123`). Kept in sync by `useTabRouterSync`.
- *
- * Tab-switch suppression: re-activating an already-open tab surfaces a
- * previously-visited path under a `(workspace, tabId)` we have already
- * seen — the pageview was emitted when the user originally navigated
- * there, so re-emitting on every switch just inflates PostHog billing
- * without adding signal (real-data audit: desktop tab switches were
- * ~50% of all `$pageview` events).
- *
- * Newly opened tabs (`openInNewTab`, `addTab`) and cross-workspace
- * `switchWorkspace(slug, path)` to a previously-unseen tab still fire,
- * because their key is not in the observed map yet. The map is seeded
- * from the persisted tab store on first render so tabs restored from a
- * previous session don't all re-emit on first activation.
- *
- * PostHog's `capture_pageview: true` auto-capture is intentionally off (see
- * `initAnalytics`) so this component owns the event shape, matching the web
- * implementation in `apps/web/components/pageview-tracker.tsx`.
- */
-export function PageviewTracker() {
- const user = useAuthStore((s) => s.user);
- const overlay = useWindowOverlayStore((s) => s.overlay);
- const { slug: activeWorkspaceSlug, tabId: activeTabId } = useActiveTabIdentity();
- const activeTabPath = useTabStore((s) => getActiveTab(s)?.path ?? null);
-
- // (slug:tabId) → last path observed while that tab was visible. Lets us
- // tell "re-activating a tab on a path we already saw" (suppress) apart
- // from "newly opened tab" or "intra-tab navigation" (fire). Seeded
- // synchronously on first render from the persisted tab store so
- // session-restored tabs don't re-emit on first click.
- const observedTabsRef = useRef<Map<string, string> | null>(null);
- if (observedTabsRef.current === null) {
- const seed = new Map<string, string>();
- for (const [slug, group] of Object.entries(useTabStore.getState().byWorkspace)) {
- for (const tab of group.tabs) {
- seed.set(`${slug}:${tab.id}`, tab.path);
- }
- }
- observedTabsRef.current = seed;
- }
- const lastSurfaceRef = useRef<{
- kind: "login" | "overlay" | "tab" | null;
- key: string | null;
- path: string | null;
- }>({ kind: null, key: null, path: null });
-
- useEffect(() => {
- let kind: "login" | "overlay" | "tab";
- let path: string;
- let key: string | null = null;
-
- if (!user) {
- kind = "login";
- path = "/login";
- } else if (overlay) {
- kind = "overlay";
- path = overlayPath(overlay);
- } else if (activeTabPath && activeTabId && activeWorkspaceSlug) {
- kind = "tab";
- key = `${activeWorkspaceSlug}:${activeTabId}`;
- path = activeTabPath;
- } else {
- return;
- }
-
- const observed = observedTabsRef.current!;
- const last = lastSurfaceRef.current;
- const next = { kind, key, path };
-
- const routeContext: RendererRouteContextInput = {
- surface: kind,
- path,
- };
- if (kind === "tab") {
- routeContext.workspaceSlug = activeWorkspaceSlug ?? undefined;
- routeContext.tabId = activeTabId ?? undefined;
- }
- reportRendererRouteContext(routeContext);
-
- if (kind === "tab" && key !== null) {
- const knownPath = observed.get(key);
- const isReactivation =
- last.key !== key && knownPath !== undefined && knownPath === path;
- observed.set(key, path);
- if (isReactivation) {
- lastSurfaceRef.current = next;
- return;
- }
- }
-
- const unchanged =
- last.kind === kind && last.key === key && last.path === path;
- if (unchanged) return;
-
- capturePageview(path);
- lastSurfaceRef.current = next;
- }, [user, overlay, activeWorkspaceSlug, activeTabId, activeTabPath]);
-
- return null;
-}
-
-function reportRendererRouteContext(context: RendererRouteContextInput) {
- const desktopAPI = window.desktopAPI as
- | { setRendererRouteContext?: (context: RendererRouteContextInput) => void }
- | undefined;
- desktopAPI?.setRendererRouteContext?.(context);
-}
-
-function overlayPath(overlay: WindowOverlay): string {
- switch (overlay.type) {
- case "new-workspace":
- return "/workspaces/new";
- case "onboarding":
- return "/onboarding";
- case "invite":
- return `/invite/${overlay.invitationId}`;
- case "invitations":
- return "/invitations";
- }
-}
diff --git a/apps/web/app/(auth)/login/page.tsx b/apps/web/app/(auth)/login/page.tsx
index 4273410f8a..6fb37033e5 100644
--- a/apps/web/app/(auth)/login/page.tsx
+++ b/apps/web/app/(auth)/login/page.tsx
@@ -22,7 +22,6 @@ import {
} from "@multica/ui/components/ui/card";
import { Button } from "@multica/ui/components/ui/button";
import { Loader2 } from "lucide-react";
-import { captureDownloadIntent } from "@multica/core/analytics";
import { setLoggedInCookie } from "@/features/auth/auth-cookie";
import Link from "next/link";
import { LoginPage, validateCliCallback } from "@multica/views/auth";
@@ -214,7 +213,6 @@ function LoginPageContent() {
{t(($) => $.web.prefer_desktop)}{" "}
<Link
href="/download"
- onClick={() => captureDownloadIntent("login")}
className="font-medium text-foreground underline decoration-foreground/30 underline-offset-4 hover:decoration-foreground/70"
>
{t(($) => $.web.download)}
diff --git a/apps/web/app/(landing)/download/download-client.tsx b/apps/web/app/(landing)/download/download-client.tsx
index 1c6d6d2801..0fe8de6012 100644
--- a/apps/web/app/(landing)/download/download-client.tsx
+++ b/apps/web/app/(landing)/download/download-client.tsx
@@ -14,7 +14,6 @@ import {
type DetectResult,
} from "@/features/landing/utils/os-detect";
import type { LatestRelease } from "@/features/landing/utils/github-release";
-import { captureDownloadPageViewed } from "@multica/core/analytics";
const ALL_RELEASES_URL =
"https://github.com/multica-ai/multica/releases";
@@ -28,25 +27,11 @@ export function DownloadClient({ release }: { release: LatestRelease }) {
detectOS().then((result) => {
if (cancelled) return;
setDetected(result);
- // Fires once per page mount after detect resolves. Carries the
- // detect outcome + version-unavailable flag so PostHog can split
- // Safari-mac-arm64 fallback rate, Intel-Mac dead-end rate, and
- // rate-limit degraded sessions. `first_detected_os/arch` is
- // $set_once'd on the person so every downstream event gains a
- // platform dimension (useful for "Android visitors who later
- // downloaded Windows" style cross-device queries once we land
- // the desktop install closure).
- captureDownloadPageViewed({
- detected_os: result.os,
- detected_arch: result.arch,
- detect_confident: result.archConfident,
- version_available: !versionUnavailable,
- });
});
return () => {
cancelled = true;
};
- }, [versionUnavailable]);
+ }, []);
const releaseHtmlUrl = release.htmlUrl ?? ALL_RELEASES_URL;
@@ -64,15 +49,12 @@ export function DownloadClient({ release }: { release: LatestRelease }) {
detected={detected}
assets={release.assets}
versionUnavailable={versionUnavailable}
- version={release.version}
/>
</div>
<AllPlatforms
assets={release.assets}
fallbackHref={ALL_RELEASES_URL}
- version={release.version}
- detected={detected}
/>
<CliSection />
<CloudSection />
diff --git a/apps/web/components/pageview-tracker.test.tsx b/apps/web/components/pageview-tracker.test.tsx
deleted file mode 100644
index 707e147e78..0000000000
--- a/apps/web/components/pageview-tracker.test.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-import { describe, it, expect, vi, beforeEach } from "vitest";
-import { render } from "@testing-library/react";
-
-// Mutable pathname + a spy for the shared capture helper. The tracker reads
-// usePathname() and forwards it to capturePageview; section-normalization and
-// dedup live in @multica/core/analytics and are unit-tested there, so here we
-// only assert the wiring (which path is forwarded, and that the query string
-// never re-triggers the effect).
-const { state, capturePageview } = vi.hoisted(() => ({
- state: { pathname: "/" as string | null },
- capturePageview: vi.fn<(path?: string) => void>(),
-}));
-
-vi.mock("next/navigation", () => ({
- usePathname: () => state.pathname,
-}));
-
-vi.mock("@multica/core/analytics", () => ({
- capturePageview,
-}));
-
-import { PageviewTracker } from "./pageview-tracker";
-
-beforeEach(() => {
- state.pathname = "/";
- capturePageview.mockClear();
-});
-
-describe("web PageviewTracker", () => {
- it("captures the pathname on mount and on each pathname change", () => {
- const { rerender } = render(<PageviewTracker />);
- expect(capturePageview).toHaveBeenCalledTimes(1);
- expect(capturePageview).toHaveBeenLastCalledWith("/");
-
- state.pathname = "/acme/issues";
- rerender(<PageviewTracker />);
- expect(capturePageview).toHaveBeenCalledTimes(2);
- expect(capturePageview).toHaveBeenLastCalledWith("/acme/issues");
- });
-
- it("does not re-capture on a query-string-only navigation", () => {
- state.pathname = "/acme/issues";
- const { rerender } = render(<PageviewTracker />);
- expect(capturePageview).toHaveBeenCalledTimes(1);
-
- // A filter/sort/search change alters only the query string, which the
- // tracker no longer reads — usePathname() is unchanged so the effect's
- // dependency does not change and no new pageview fires.
- rerender(<PageviewTracker />);
- expect(capturePageview).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/apps/web/components/pageview-tracker.tsx b/apps/web/components/pageview-tracker.tsx
deleted file mode 100644
index 1917895a0b..0000000000
--- a/apps/web/components/pageview-tracker.tsx
+++ /dev/null
@@ -1,30 +0,0 @@
-"use client";
-
-import { useEffect } from "react";
-import { usePathname } from "next/navigation";
-import { capturePageview } from "@multica/core/analytics";
-
-/**
- * Fires a PostHog $pageview whenever the Next.js App Router pathname changes.
- * Mounted once at the root so every route transition is covered, including
- * transitions into workspace-scoped subtrees.
- *
- * Deliberately keyed on `pathname` only — NOT `useSearchParams`. Filter / sort
- * / search state lives in the query string and changes constantly on a
- * dashboard; firing a pageview on every query-string change was ~17% pure
- * noise (and billed events) with no funnel signal. The query string is also
- * dropped from the captured URL by `capturePageview` (it section-normalizes
- * the path), so OAuth `code` / `state` never reach PostHog either.
- *
- * PostHog's own `capture_pageview: true` auto-capture is deliberately disabled
- * in `initAnalytics` so this component owns the event shape.
- */
-export function PageviewTracker() {
- const pathname = usePathname();
-
- useEffect(() => {
- if (pathname) capturePageview(pathname);
- }, [pathname]);
-
- return null;
-}
diff --git a/apps/web/components/web-providers.tsx b/apps/web/components/web-providers.tsx
index 12e9fb514d..725ecf9e95 100644
--- a/apps/web/components/web-providers.tsx
+++ b/apps/web/components/web-providers.tsx
@@ -1,6 +1,6 @@
"use client";
-import { Suspense, useMemo } from "react";
+import { useMemo } from "react";
import { CoreProvider } from "@multica/core/platform";
import { createBrowserCookieLocaleAdapter } from "@multica/core/i18n/browser";
import type { LocaleResources, SupportedLocale } from "@multica/core/i18n";
@@ -11,7 +11,6 @@ import {
setLoggedInCookie,
clearLoggedInCookie,
} from "@/features/auth/auth-cookie";
-import { PageviewTracker } from "./pageview-tracker";
// Legacy token in localStorage → keep this session in token mode so users who
// logged in before the cookie-auth migration stay authed. They migrate to
@@ -82,11 +81,6 @@ export function WebProviders({
resources={resources}
localeAdapter={localeAdapter}
>
- {/* Suspense boundary is required by Next.js for useSearchParams in
- a client component mounted this high in the tree. */}
- <Suspense fallback={null}>
- <PageviewTracker />
- </Suspense>
<WebNavigationProvider>{children}</WebNavigationProvider>
</CoreProvider>
);
diff --git a/apps/web/features/landing/components/download/all-platforms.tsx b/apps/web/features/landing/components/download/all-platforms.tsx
index 275285d6b8..e0d07a185f 100644
--- a/apps/web/features/landing/components/download/all-platforms.tsx
+++ b/apps/web/features/landing/components/download/all-platforms.tsx
@@ -1,27 +1,13 @@
import Link from "next/link";
-import {
- captureDownloadInitiated,
- type DownloadInitiatedPayload,
-} from "@multica/core/analytics";
import { useLocale } from "../../i18n";
-import type { DetectResult } from "../../utils/os-detect";
import type { DownloadAssets } from "../../utils/parse-release-assets";
import { AppleIcon, LinuxIcon, WindowsIcon } from "./os-icons";
-type Platform = DownloadInitiatedPayload["platform"];
-type Arch = DownloadInitiatedPayload["arch"];
-type Format = DownloadInitiatedPayload["format"];
-
interface Props {
assets: DownloadAssets;
/** Link to GitHub releases page, used when individual asset URLs
* couldn't be resolved (API down / parse failure). */
fallbackHref: string;
- /** Release tag (e.g. "v0.2.13"); null on fetch failure. */
- version: string | null;
- /** Current OS/arch guess. Used only to compute `matched_detect` on
- * the download_initiated event — the row UI itself is static. */
- detected: DetectResult | null;
}
/**
@@ -32,31 +18,10 @@ interface Props {
export function AllPlatforms({
assets,
fallbackHref,
- version,
- detected,
}: Props) {
const { t } = useLocale();
const d = t.download.allPlatforms;
- const trackClick = (platform: Platform, arch: Arch, format: Format) => {
- if (!version) return;
- captureDownloadInitiated({
- platform,
- arch,
- format,
- version,
- // Manual pick from the matrix — Hero is the primary CTA.
- primary_cta: false,
- // True only when the row matches what we guessed client-side.
- // Lets us measure detect accuracy from the miss rate on this
- // event alone (no need to cross-join to download_page_viewed).
- matched_detect:
- !!detected &&
- detected.os === platform &&
- detected.arch === arch,
- });
- };
-
return (
<section
id="all-platforms"
@@ -75,12 +40,10 @@ export function AllPlatforms({
{
label: d.formatDmg,
href: assets.macArm64Dmg,
- onClick: () => trackClick("mac", "arm64", "dmg"),
},
{
label: d.formatZip,
href: assets.macArm64Zip,
- onClick: () => trackClick("mac", "arm64", "zip"),
},
]}
unavailable={d.unavailable}
@@ -92,7 +55,6 @@ export function AllPlatforms({
{
label: d.formatExe,
href: assets.winX64Exe,
- onClick: () => trackClick("windows", "x64", "exe"),
},
]}
unavailable={d.unavailable}
@@ -104,7 +66,6 @@ export function AllPlatforms({
{
label: d.formatExe,
href: assets.winArm64Exe,
- onClick: () => trackClick("windows", "arm64", "exe"),
},
]}
unavailable={d.unavailable}
@@ -116,17 +77,14 @@ export function AllPlatforms({
{
label: d.formatAppImage,
href: assets.linuxAmd64AppImage,
- onClick: () => trackClick("linux", "x64", "appimage"),
},
{
label: d.formatDeb,
href: assets.linuxAmd64Deb,
- onClick: () => trackClick("linux", "x64", "deb"),
},
{
label: d.formatRpm,
href: assets.linuxAmd64Rpm,
- onClick: () => trackClick("linux", "x64", "rpm"),
},
]}
unavailable={d.unavailable}
@@ -138,17 +96,14 @@ export function AllPlatforms({
{
label: d.formatAppImage,
href: assets.linuxArm64AppImage,
- onClick: () => trackClick("linux", "arm64", "appimage"),
},
{
label: d.formatDeb,
href: assets.linuxArm64Deb,
- onClick: () => trackClick("linux", "arm64", "deb"),
},
{
label: d.formatRpm,
href: assets.linuxArm64Rpm,
- onClick: () => trackClick("linux", "arm64", "rpm"),
},
]}
unavailable={d.unavailable}
@@ -185,7 +140,6 @@ interface RowProps {
formats: {
label: string;
href: string | undefined;
- onClick: () => void;
}[];
unavailable: string;
isLast?: boolean;
@@ -208,7 +162,6 @@ function Row({ icon, label, formats, unavailable, isLast }: RowProps) {
<a
key={f.label}
href={f.href}
- onClick={f.onClick}
className="inline-flex items-center gap-1.5 rounded-lg border border-[#0a0d12]/12 bg-white px-3 py-1.5 text-[13px] font-medium transition-colors hover:border-[#0a0d12]/30 hover:bg-[#0a0d12]/5"
>
{f.label}
diff --git a/apps/web/features/landing/components/download/hero.tsx b/apps/web/features/landing/components/download/hero.tsx
index 602b0e2a50..e73a3b2e26 100644
--- a/apps/web/features/landing/components/download/hero.tsx
+++ b/apps/web/features/landing/components/download/hero.tsx
@@ -1,9 +1,5 @@
import Link from "next/link";
import { ArrowRight, Download } from "lucide-react";
-import {
- captureDownloadInitiated,
- type DownloadInitiatedPayload,
-} from "@multica/core/analytics";
import { useLocale } from "../../i18n";
import type { DetectResult } from "../../utils/os-detect";
import type { DownloadAssets } from "../../utils/parse-release-assets";
@@ -15,9 +11,6 @@ interface Props {
/** True when the GitHub API fetch failed; disables all CTAs and
* surfaces a "version unavailable" line. */
versionUnavailable: boolean;
- /** Release tag (e.g. "v0.2.13"). Null when version lookup failed —
- * in that case CTAs are already disabled, no tracking fires. */
- version: string | null;
}
/**
@@ -29,28 +22,12 @@ export function DownloadHero({
detected,
assets,
versionUnavailable,
- version,
}: Props) {
const { t } = useLocale();
const d = t.download.hero;
const content = resolveContent(detected, assets, versionUnavailable, d);
- // Fires download_initiated on primary CTA click. `primary_cta: true`
- // identifies the hero-recommended path; `matched_detect: true` is
- // always true here by construction (the primary is computed from
- // the detect result). All Platforms rows below emit with
- // matched_detect=false when the user overrides.
- const onPrimaryClick = (tracking: HeroTracking | undefined) => {
- if (!tracking || !version) return;
- captureDownloadInitiated({
- ...tracking,
- version,
- primary_cta: true,
- matched_detect: true,
- });
- };
-
return (
<section className="relative overflow-hidden bg-[#05070b] text-white">
<BackdropGradient />
@@ -67,7 +44,6 @@ export function DownloadHero({
<PrimaryCta
href={content.primary.href}
disabled={content.primary.disabled}
- onClick={() => onPrimaryClick(content.primary?.tracking)}
>
<Download className="size-4" aria-hidden />
{content.primary.label}
@@ -80,7 +56,6 @@ export function DownloadHero({
<Link
href={content.alt.href}
className={heroButtonClassName("ghost")}
- onClick={() => onPrimaryClick(content.alt?.tracking)}
>
{content.alt.label}
</Link>
@@ -107,11 +82,6 @@ export function DownloadHero({
// Content resolver — maps (detect, assets) → CTA props
// ------------------------------------------------------------
-type HeroTracking = Pick<
- DownloadInitiatedPayload,
- "platform" | "arch" | "format"
->;
-
interface HeroContent {
title: string;
sub: string;
@@ -119,9 +89,8 @@ interface HeroContent {
href: string;
label: string;
disabled: boolean;
- tracking?: HeroTracking;
};
- alt?: { href: string; label: string; tracking?: HeroTracking };
+ alt?: { href: string; label: string };
hint?: string;
}
@@ -165,7 +134,6 @@ function resolveContent(
href: dmg,
label: d.macArm64.primary,
disabled: false,
- tracking: { platform: "mac", arch: "arm64", format: "dmg" },
}
: versionUnavailable
? { href: "#", label: d.macArm64.primary, disabled: true }
@@ -174,7 +142,6 @@ function resolveContent(
? {
href: zip,
label: d.macArm64.altZip,
- tracking: { platform: "mac", arch: "arm64", format: "zip" },
}
: undefined,
hint: detected.archConfident ? undefined : d.safariMacHint,
@@ -197,11 +164,6 @@ function resolveContent(
href: url,
label: copy.primary,
disabled: false,
- tracking: {
- platform: "windows",
- arch: isArm ? "arm64" : "x64",
- format: "exe",
- },
}
: versionUnavailable
? { href: "#", label: copy.primary, disabled: true }
@@ -225,11 +187,6 @@ function resolveContent(
href: primaryUrl,
label: d.linux.primary,
disabled: false,
- tracking: {
- platform: "linux",
- arch: isArmLinux ? "arm64" : "x64",
- format: "appimage",
- },
}
: versionUnavailable
? { href: "#", label: d.linux.primary, disabled: true }
@@ -246,12 +203,10 @@ function resolveContent(
function PrimaryCta({
href,
disabled,
- onClick,
children,
}: {
href: string;
disabled: boolean;
- onClick?: () => void;
children: React.ReactNode;
}) {
if (disabled) {
@@ -265,7 +220,7 @@ function PrimaryCta({
);
}
return (
- <a href={href} onClick={onClick} className={heroButtonClassName("solid")}>
+ <a href={href} className={heroButtonClassName("solid")}>
{children}
</a>
);
diff --git a/apps/web/features/landing/components/landing-footer.tsx b/apps/web/features/landing/components/landing-footer.tsx
index f280b935e1..9282963974 100644
--- a/apps/web/features/landing/components/landing-footer.tsx
+++ b/apps/web/features/landing/components/landing-footer.tsx
@@ -4,7 +4,6 @@ import Link from "next/link";
import { MulticaIcon } from "@multica/ui/components/common/multica-icon";
import { cn } from "@multica/ui/lib/utils";
import { useAuthStore } from "@multica/core/auth";
-import { captureDownloadIntent } from "@multica/core/analytics";
import {
XMark,
GitHubMark,
@@ -88,11 +87,6 @@ export function LandingFooter() {
{...(link.href.startsWith("http")
? { target: "_blank", rel: "noreferrer" }
: {})}
- onClick={
- link.href === "/download"
- ? () => captureDownloadIntent("landing_footer")
- : undefined
- }
className="text-[14px] text-white/50 transition-colors hover:text-white"
>
{link.label}
diff --git a/apps/web/features/landing/components/landing-hero.tsx b/apps/web/features/landing/components/landing-hero.tsx
index 6eb57b51c6..3c29635cc2 100644
--- a/apps/web/features/landing/components/landing-hero.tsx
+++ b/apps/web/features/landing/components/landing-hero.tsx
@@ -4,7 +4,6 @@ import Image from "next/image";
import Link from "next/link";
import { ArrowRight, Download } from "lucide-react";
import { useAuthStore } from "@multica/core/auth";
-import { captureDownloadIntent } from "@multica/core/analytics";
import { useLocale } from "../i18n";
import {
ClaudeCodeLogo,
@@ -46,7 +45,6 @@ export function LandingHero() {
<Link
href="/download"
className={heroButtonClassName("ghost")}
- onClick={() => captureDownloadIntent("landing_hero")}
>
<Download className="size-4" aria-hidden />
{t.hero.downloadDesktop}
diff --git a/docs/analytics.md b/docs/analytics.md
index fdfe47bece..478b19e6b9 100644
--- a/docs/analytics.md
+++ b/docs/analytics.md
@@ -1,24 +1,47 @@
# Product Analytics
-This document is the source of truth for the analytics events Multica ships
-to PostHog. Events feed the acquisition → activation → expansion funnel that
-drives our weekly Active Workspaces (WAW) north-star metric.
-
-See [MUL-1122](https://github.com/multica-ai/multica) for the design context.
-
-> **PostHog is reserved for user/product-behaviour events.** High-volume
-> operational / execution-lifecycle telemetry — runtime lifecycle
-> (`runtime_registered` / `runtime_ready` / `runtime_failed` /
-> `runtime_offline`), the agent task lifecycle (`agent_task_*`), and autopilot
-> run lifecycle (`autopilot_run_started` / `autopilot_run_completed` /
-> `autopilot_run_failed`) — is **Prometheus-only** and is **not** shipped to
-> PostHog. Grafana already covers it and the per-event PostHog ingestion cost
-> (these events dominate volume and bill at the identified-event rate) is not
-> justified. The runtime/autopilot events are flagged by
-> `analytics.IsMetricsOnly`, which `metrics.RecordEvent` consults to skip the
-> PostHog `Capture` while still incrementing the Prometheus counter; the
-> `agent_task_*` lifecycle is recorded straight to Prometheus via the typed
-> `BusinessMetrics.RecordTask*` methods and has no `analytics.Event` at all.
+Multica's product analytics live in the **operational database** and in
+**Prometheus / Grafana**. This document is the catalogue of instrumentation and
+its history.
+
+See [MUL-1122](https://github.com/multica-ai/multica) for the original design
+context and [MUL-4127](https://github.com/multica-ai/multica) for the PostHog
+retirement below.
+
+> **MUL-4127 — PostHog retired for product analytics.** PostHog had become a
+> chaotic, largely-unused second copy of data we already query from the DB, so
+> the redundant instrumentation was removed:
+>
+> - **Every server-side event is now Prometheus-only.** `signup`,
+> `workspace_created`, `issue_created`, `issue_executed`, `chat_message_sent`,
+> `team_invite_sent` / `team_invite_accepted`, `onboarding_started` /
+> `onboarding_questionnaire_submitted` / `onboarding_completed`,
+> `agent_created`, `cloud_waitlist_joined`, `feedback_submitted`,
+> `contact_sales_submitted`, `squad_created`, `autopilot_created` — all are
+> now flagged by `analytics.IsMetricsOnly`, so `metrics.RecordEvent`
+> increments the Grafana counter but no longer ships to PostHog. The
+> `analytics.*` event constructors are retained solely to drive those
+> Prometheus counters; the underlying DB rows remain the source of truth. The
+> runtime lifecycle (`runtime_*`), autopilot run lifecycle
+> (`autopilot_run_*`), and `agent_task_*` were already Prometheus-only.
+> - **The frontend funnel instrumentation was removed**: `$pageview`,
+> `download_intent_expressed` / `download_page_viewed` / `download_initiated`,
+> the frontend `onboarding_started` mirror, `onboarding_runtime_path_selected`,
+> `onboarding_runtime_detected`, `feedback_opened`, and the
+> `source_backfill_*` events.
+> - **What still ships to PostHog (frontend only):** `$exception` autocapture
+> (with `before_send` redaction + dedupe) and the desktop stability events
+> `client_crash` / `client_unresponsive` — error / crash monitoring that has
+> no DB equivalent. Identity (`$identify` / `$set`) is retained only to attach
+> those.
+> - The `multica_signup_source` attribution cookie (`captureSignupSource`,
+> independent of `$pageview`) is kept: it still feeds the `signup_source`
+> Prometheus label. Persisting the raw source-channel / country to the DB —
+> the one signal PostHog uniquely held — is tracked separately.
+>
+> The per-event sections below document the historical shapes for reference; the
+> server events still describe the `analytics.Event` that drives the Prometheus
+> counter, just no longer a PostHog contract.
## Configuration
@@ -97,18 +120,24 @@ handler → analytics.Client.Capture(Event) ← non-blocking, returns immediat
`$set_once` only for values that must never be overwritten (email,
initial attribution, first-completion timestamp).
-## Taxonomy
+## Taxonomy (historical)
-Every event is assigned to one dashboard category:
+These categories described the PostHog dashboards each event once fed. After
+MUL-4127 those dashboards are retired: server events are Prometheus-only (DB is
+the source of truth) and the frontend funnel events were deleted. The `Status`
+column records where each event stands now.
-| Category | Events |
-|---|---|
-| `core_loop` | `workspace_created`, `agent_created`, `issue_created`, `chat_message_sent`, `issue_executed`, `autopilot_created`, `squad_created` |
-| `onboarding_support` | `onboarding_started`, `onboarding_questionnaire_submitted`, `onboarding_completed`, `onboarding_runtime_path_selected`, `onboarding_runtime_detected` |
-| `acquisition` | `signup`, `download_intent_expressed`, `download_page_viewed`, `download_initiated`, `cloud_waitlist_joined`, `contact_sales_submitted` |
-| `ops_feedback` | `feedback_opened`, `feedback_submitted` |
-| `system/noise` | `$pageview`, `$set`, `$identify`, `$autocapture`, `$rageclick` |
-| `operational (Prometheus-only — NOT in PostHog)` | `runtime_registered`, `runtime_ready`, `runtime_failed`, `runtime_offline`, `agent_task_queued`, `agent_task_dispatched`, `agent_task_started`, `agent_task_completed`, `agent_task_failed`, `agent_task_cancelled`, `autopilot_run_started`, `autopilot_run_completed`, `autopilot_run_failed` |
+| Category | Events | Status after MUL-4127 |
+|---|---|---|
+| `core_loop` | `workspace_created`, `agent_created`, `issue_created`, `chat_message_sent`, `issue_executed`, `autopilot_created`, `squad_created` | Prometheus-only |
+| `onboarding_support` (server) | `onboarding_started`, `onboarding_questionnaire_submitted`, `onboarding_completed` | Prometheus-only |
+| `onboarding_support` (frontend) | frontend `onboarding_started` mirror, `onboarding_runtime_path_selected`, `onboarding_runtime_detected` | **Removed** |
+| `acquisition` (server) | `signup`, `cloud_waitlist_joined`, `contact_sales_submitted` | Prometheus-only |
+| `acquisition` (frontend) | `download_intent_expressed`, `download_page_viewed`, `download_initiated` | **Removed** |
+| `ops_feedback` | `feedback_submitted` (server), `feedback_opened` (frontend) | server → Prometheus-only; frontend **removed** |
+| `attribution backfill` (frontend) | `source_backfill_shown` / `_submitted` / `_skipped` / `_dismissed` | **Removed** (modal kept; PATCHes DB) |
+| **still in PostHog (frontend only)** | `$exception`, `client_crash`, `client_unresponsive`, `$identify`, `$set` | **Shipped** |
+| `operational` (already Prometheus-only) | `runtime_registered/ready/failed/offline`, `agent_task_*`, `autopilot_run_started/completed/failed` | Prometheus-only |
The v0 core dashboard must use only `core_loop` plus the specific
`onboarding_support` steps used by the activation funnel. Acquisition,
@@ -157,12 +186,13 @@ OAuth entry points (`findOrCreateUser` is the single emission site).
| `signup_source` | string | Opaque attribution bundle from the frontend cookie `multica_signup_source` (UTM + referrer). Empty when the cookie is absent. |
| `auth_method` | string | Optional. `"google"` for Google OAuth signups. Absent for verification-code signups. |
-Person properties set with `$set_once`:
+Historical PostHog person properties (`$set_once`) — **no longer emitted** since
+MUL-4127, because `signup` is now Prometheus-only and never reaches PostHog:
| Property | Type | Description |
|---|---|---|
-| `email` | string | Full email. Never broadcast per-event. |
-| `signup_source` | string | Same as above; kept on the person for later segmentation. |
+| `email` | string | Full email. Was never broadcast per-event. |
+| `signup_source` | string | Attribution bundle. Today only its bucketed form survives, as the `multica_signup_total{signup_source}` Prometheus label (see `NormalizeSignupSource`); it is no longer set as a person property for segmentation. |
### `workspace_created`
@@ -371,11 +401,12 @@ emit `n=1`. PostHog answers the same question at query time via
and funnel steps of the form "workspace has had ≥2 `issue_executed`
events" are expressible without the property. No information is lost.
-`issue_executed` is the canonical **PostHog** core-loop success signal (the
-`agent_task_*` lifecycle that previously served per-task success dashboards is
-now Prometheus-only). Per-task completion counts live in Grafana via
-`BusinessMetrics.RecordTaskTerminal`; use `issue_executed` for the
-PostHog-side activation funnel and filter by `source` as needed.
+`issue_executed` is the canonical core-loop success signal. Since MUL-4127 it is
+metrics-only like every server event: recorded to Prometheus as
+`multica_issue_executed_total{source}` (not PostHog) and backed in the DB by
+`issue.first_executed_at`. Per-task completion counts live in Grafana via
+`BusinessMetrics.RecordTaskTerminal`; use `multica_issue_executed_total` for the
+activation funnel and break down by `source` as needed.
### `team_invite_sent`
@@ -531,6 +562,14 @@ sent from a pre-workspace surface.
### Frontend-only events
+> **Removed in MUL-4127**, except `$exception` (unchanged) and the
+> `client_crash` / `client_unresponsive` desktop stability events (documented in
+> `packages/core/diagnostics`). `$pageview`, `download_intent_expressed`,
+> `download_page_viewed`, `download_initiated`, `onboarding_runtime_path_selected`,
+> `onboarding_runtime_detected`, the frontend `onboarding_started` mirror,
+> `feedback_opened`, and `source_backfill_*` no longer fire. The descriptions
+> below are kept as historical reference only.
+
- `$pageview` — fired by the web tracker
(`apps/web/components/pageview-tracker.tsx`) on Next.js App Router
**pathname** changes, and by the desktop tracker
@@ -676,9 +715,10 @@ Compare against the equivalent Prometheus counter in Grafana. The expected
difference should be near zero; sustained drift means either an emission site
is missing or the metrics pipeline is unhealthy.
-On the PostHog side, `issue_executed` remains the product-level success signal
-(at most one per issue) and can be reconciled against
-`issue.first_executed_at` if needed.
+`issue_executed` remains the product-level success signal (at most one per
+issue). Since MUL-4127 it is Prometheus-only, so reconcile
+`multica_issue_executed_total` against `issue.first_executed_at` rather than a
+PostHog event.
## Governance
diff --git a/packages/core/analytics/download.ts b/packages/core/analytics/download.ts
deleted file mode 100644
index b45d37bcf5..0000000000
--- a/packages/core/analytics/download.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-/**
- * Download funnel instrumentation.
- *
- * Complements the onboarding events added in PR #1489 by covering
- * every surface that advertises the desktop app — landing hero,
- * landing footer, login, Welcome (web branch), Step 3 — and the
- * /download page itself. Without this layer we can see Step 3
- * path selection but not the touchpoint that got the user there,
- * nor the /download → installer conversion.
- *
- * Event names and property shapes are governed by docs/analytics.md;
- * keep the two in sync when adding a new source or field.
- */
-
-import posthog from "posthog-js";
-
-import { captureEvent, setPersonProperties } from "./index";
-
-/**
- * Where the user clicked a CTA that points at `/download`. Typed union
- * prevents drift across the five touchpoints and lets PostHog funnels
- * split cleanly by top-of-funnel entry.
- */
-export type DownloadIntentSource =
- | "landing_hero"
- | "landing_footer"
- | "login"
- | "welcome"
- | "step3";
-
-/**
- * OS + arch detect result for the /download page. Mirrors the shape of
- * `@/features/landing/utils/os-detect.ts` without importing it (that
- * module lives in the web app; core packages can't depend on it). Keep
- * these enums in lockstep.
- */
-export interface DownloadDetectPayload {
- detected_os: "mac" | "windows" | "linux" | "unknown";
- detected_arch: "arm64" | "x64" | "unknown";
- detect_confident: boolean;
- version_available: boolean;
-}
-
-/**
- * Specific installer the user chose on /download. Version is the GitHub
- * tag name (e.g. "v0.2.13") so we can correlate adoption-by-release.
- */
-export interface DownloadInitiatedPayload {
- platform: "mac" | "windows" | "linux";
- arch: "arm64" | "x64";
- format: "dmg" | "zip" | "exe" | "appimage" | "deb" | "rpm";
- version: string;
- primary_cta: boolean;
- matched_detect: boolean;
-}
-
-/**
- * Fires when a user clicks any CTA that navigates to `/download`. We
- * also write `platform_preference` to person properties so the backend
- * can segment subsequent events — same convention the Step 3 handler
- * already uses (see `step-platform-fork.tsx`).
- */
-export function captureDownloadIntent(source: DownloadIntentSource): void {
- captureEvent("download_intent_expressed", {
- source,
- });
- setPersonProperties({ platform_preference: "desktop" });
-}
-
-/**
- * Fires once on /download page mount, after OS detection resolves. The
- * first detection for a given person is mirrored into person properties
- * via `$set_once` so every downstream event gains a platform dimension
- * without re-emitting.
- */
-export function captureDownloadPageViewed(
- payload: DownloadDetectPayload,
-): void {
- captureEvent("download_page_viewed", {
- detected_os: payload.detected_os,
- detected_arch: payload.detected_arch,
- detect_confident: payload.detect_confident,
- version_available: payload.version_available,
- });
- setPersonPropertiesOnce({
- first_detected_os: payload.detected_os,
- first_detected_arch: payload.detected_arch,
- });
-}
-
-/**
- * Fires when the user clicks a concrete installer link on `/download`.
- * `primary_cta` marks the hero-level recommendation versus a manual
- * pick from the All Platforms matrix; `matched_detect` captures
- * whether the click matched what we detected (miss = detect got it
- * wrong / user overrode).
- */
-export function captureDownloadInitiated(
- payload: DownloadInitiatedPayload,
-): void {
- captureEvent("download_initiated", { ...payload });
-}
-
-/**
- * $set_once wire form. Mirrors the backend's `Event.SetOnce` path —
- * first write wins, subsequent ones are no-ops on PostHog's side.
- * Wrapping it here keeps call sites free of the no-op `$set_once`
- * envelope quirk.
- */
-function setPersonPropertiesOnce(props: Record<string, unknown>): void {
- if (typeof window === "undefined") return;
- posthog.capture("$set", { $set_once: props });
-}
diff --git a/packages/core/analytics/feedback.ts b/packages/core/analytics/feedback.ts
deleted file mode 100644
index e9cde782c2..0000000000
--- a/packages/core/analytics/feedback.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- * Feedback funnel instrumentation.
- *
- * Pairs with the backend's `feedback_submitted` event (emitted from
- * `CreateFeedback` after a successful insert) so we can compute a
- * completion rate: users who open the modal → users who actually send.
- * The message content itself is never sent to PostHog; see
- * docs/analytics.md and the backend `FeedbackSubmitted` helper for the
- * PII contract.
- */
-
-import { captureEvent } from "./index";
-
-/**
- * Entry point the user took to reach the Feedback modal. Typed union so
- * future surfaces (keyboard shortcut, error-toast CTA, sidebar menu
- * item) have to extend this list explicitly rather than drift.
- */
-export type FeedbackOpenedSource = "help_menu";
-
-/**
- * Fires once on FeedbackModal mount. Workspace id is attached when the
- * modal opens inside a workspace; pre-workspace surfaces (e.g. inbox,
- * onboarding transitions) omit it rather than sending an empty string.
- */
-export function captureFeedbackOpened(
- source: FeedbackOpenedSource,
- workspaceId?: string,
-): void {
- captureEvent("feedback_opened", {
- source,
- ...(workspaceId ? { workspace_id: workspaceId } : {}),
- });
-}
diff --git a/packages/core/analytics/index.test.ts b/packages/core/analytics/index.test.ts
index b656d8e233..c6256a9227 100644
--- a/packages/core/analytics/index.test.ts
+++ b/packages/core/analytics/index.test.ts
@@ -106,87 +106,6 @@ describe("resetAnalytics", () => {
});
});
-describe("normalizePageviewPath", () => {
- it("collapses resource-id segments to the section route", async () => {
- const { analytics } = await loadModule();
- expect(
- analytics.normalizePageviewPath("/acme/issues/8d5c1a2b-0035-4c62-9f14-1ad4215736a5"),
- ).toBe("/acme/issues");
- expect(analytics.normalizePageviewPath("/acme/issues/MUL-123")).toBe("/acme/issues");
- expect(
- analytics.normalizePageviewPath("/invite/8d5c1a2b-0035-4c62-9f14-1ad4215736a5"),
- ).toBe("/invite");
- });
-
- it("strips query string and hash", async () => {
- const { analytics } = await loadModule();
- expect(analytics.normalizePageviewPath("/acme/issues?status=open&view=board")).toBe(
- "/acme/issues",
- );
- expect(analytics.normalizePageviewPath("/acme/issues#section")).toBe("/acme/issues");
- });
-
- it("keeps non-id sub-sections and never drops the leading segment", async () => {
- const { analytics } = await loadModule();
- expect(analytics.normalizePageviewPath("/acme/settings/members")).toBe(
- "/acme/settings/members",
- );
- // A workspace slug that looks like an issue key must not be dropped.
- expect(analytics.normalizePageviewPath("/team-1/issues/MUL-9")).toBe("/team-1/issues");
- expect(analytics.normalizePageviewPath("/login")).toBe("/login");
- expect(analytics.normalizePageviewPath("/")).toBe("/");
- });
-});
-
-describe("capturePageview", () => {
- function captureMock(posthog: unknown) {
- return (posthog as { capture: ReturnType<typeof vi.fn> }).capture;
- }
-
- it("emits the section-normalized path as $current_url", async () => {
- const { analytics, posthog } = await loadModule();
- analytics.initAnalytics({ key: "k", host: "" });
- const capture = captureMock(posthog);
- capture.mockClear();
-
- analytics.capturePageview("/acme/issues/8d5c1a2b-0035-4c62-9f14-1ad4215736a5");
-
- expect(capture).toHaveBeenCalledTimes(1);
- expect(capture).toHaveBeenCalledWith("$pageview", { $current_url: "/acme/issues" });
- });
-
- it("dedupes consecutive views of the same section but fires on section change", async () => {
- const { analytics, posthog } = await loadModule();
- analytics.initAnalytics({ key: "k", host: "" });
- const capture = captureMock(posthog);
- capture.mockClear();
-
- // Two different issues collapse to the same section → one event.
- analytics.capturePageview("/acme/issues/a1b2c3d4-0035-4c62-9f14-1ad4215736a5");
- analytics.capturePageview("/acme/issues/b2c3d4e5-0035-4c62-9f14-1ad4215736a5");
- expect(capture).toHaveBeenCalledTimes(1);
-
- // A real section change fires again.
- analytics.capturePageview("/acme/projects");
- expect(capture).toHaveBeenCalledTimes(2);
- });
-
- it("re-emits the same section after resetAnalytics clears the dedup state", async () => {
- const { analytics, posthog } = await loadModule();
- analytics.initAnalytics({ key: "k", host: "" });
- const capture = captureMock(posthog);
- capture.mockClear();
-
- analytics.capturePageview("/acme/inbox");
- analytics.capturePageview("/acme/inbox");
- expect(capture).toHaveBeenCalledTimes(1);
-
- analytics.resetAnalytics();
- analytics.capturePageview("/acme/inbox");
- expect(capture).toHaveBeenCalledTimes(2);
- });
-});
-
describe("captureException", () => {
it("buffers a pre-init exception and flushes it on init", async () => {
const { analytics, posthog } = await loadModule();
diff --git a/packages/core/analytics/index.ts b/packages/core/analytics/index.ts
index b6901fe736..6f403f566c 100644
--- a/packages/core/analytics/index.ts
+++ b/packages/core/analytics/index.ts
@@ -41,17 +41,6 @@ let initialized = false;
let pendingIdentify: { userId: string; props?: Record<string, unknown> } | null = null;
let currentUserId: string | null = null;
let analyticsEnvironment = "dev";
-// Likewise pageviews: the initial "/" pageview is the anchor of the
-// acquisition funnel, and the Next.js router fires it on mount before the
-// config fetch resolves. We keep the first pending pageview so that step
-// doesn't silently drop.
-let pendingPageview: string | undefined | null = null;
-// Last $pageview path actually emitted (already section-normalized). Used to
-// collapse consecutive views of the same section so navigating between
-// resources under one section doesn't fire a billed event per resource. See
-// capturePageview / normalizePageviewPath. Cleared on reset so a fresh
-// session re-emits its first pageview.
-let lastCapturedPath: string | null = null;
// Frontend-emitted events (captureEvent) and person-property updates
// (setPersonProperties) can also arrive before init — same config-race as
// identify/pageview. We replay them in order once init succeeds. These
@@ -68,20 +57,6 @@ const pendingOps: PendingOp[] = [];
// event until a full reload.
let superProperties: Record<string, unknown> = {};
-export {
- captureDownloadIntent,
- captureDownloadPageViewed,
- captureDownloadInitiated,
- type DownloadIntentSource,
- type DownloadDetectPayload,
- type DownloadInitiatedPayload,
-} from "./download";
-
-export {
- captureFeedbackOpened,
- type FeedbackOpenedSource,
-} from "./feedback";
-
export interface AnalyticsConfig {
key: string;
host: string;
@@ -204,12 +179,6 @@ export function initAnalytics(config: AnalyticsConfig | null | undefined): boole
posthog.identify(pendingIdentify.userId, pendingIdentify.props);
pendingIdentify = null;
}
- // And any first pageview we captured while config was loading.
- if (pendingPageview !== null) {
- posthog.capture("$pageview", pendingPageview ? { $current_url: pendingPageview } : undefined);
- lastCapturedPath = pendingPageview ?? null;
- pendingPageview = null;
- }
// Replay buffered events / person-property updates in their original
// order — funnel correctness depends on sequence (e.g. a user submits
// the questionnaire and then finishes onboarding within the same
@@ -252,8 +221,6 @@ export function identify(userId: string, userProperties?: Record<string, unknown
export function resetAnalytics(): void {
currentUserId = null;
pendingIdentify = null;
- pendingPageview = null;
- lastCapturedPath = null;
pendingOps.length = 0;
if (!initialized) return;
posthog.reset();
@@ -373,62 +340,8 @@ function normalizeEnvironment(value: string | undefined): string {
}
}
-// A UUID or an issue key (e.g. MUL-123) appearing as a path segment
-// identifies a single resource. Resource-level granularity carries no
-// aggregate funnel signal and explodes $pageview volume — every distinct
-// issue / agent / project navigated to would fire its own billed event.
-const UUID_SEGMENT = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
-const ISSUE_KEY_SEGMENT = /^[A-Z][A-Z0-9]*-\d+$/;
-
-/**
- * Normalize a raw path to its section route for $pageview reporting:
- * `/acme/issues/8d5c…` and `/acme/issues/MUL-12` both collapse to
- * `/acme/issues`. We strip the query string / hash (volatile filter / sort /
- * search state, and occasionally OAuth `code` / `state`) and drop any
- * resource-id segment after the first. The leading segment — the workspace
- * slug or a top-level route word like `login` — is always kept, so a slug
- * that happens to look like an id (`team-1`) is never dropped.
- *
- * Exported for unit testing; callers should go through capturePageview.
- */
-export function normalizePageviewPath(path?: string): string | undefined {
- if (!path) return path ?? undefined;
- const clean = path.split(/[?#]/)[0] ?? "";
- const segments = clean.split("/").filter((s) => s.length > 0);
- const kept = segments.filter(
- (seg, i) => i === 0 || !(UUID_SEGMENT.test(seg) || ISSUE_KEY_SEGMENT.test(seg)),
- );
- return "/" + kept.join("/");
-}
-
-/**
- * Capture a page view. Call once per client-side navigation. We disable
- * posthog's automatic pageview tracking in init() so this module owns the
- * event shape.
- *
- * The path is normalized to its section route (see normalizePageviewPath) and
- * consecutive views of the same section are collapsed — both keep PostHog at
- * section granularity instead of paying for a billed event per resource and
- * per query-string change. Callers can therefore pass the raw path freely.
- *
- * Calls before initAnalytics() buffer the most-recent path so the first
- * pageview isn't dropped on slow /api/config fetches. Subsequent pre-init
- * pageviews overwrite the buffer; after init flushes, every navigation
- * captures synchronously as expected.
- */
-export function capturePageview(path?: string): void {
- const normalized = normalizePageviewPath(path);
- if (!initialized) {
- pendingPageview = normalized ?? "";
- return;
- }
- if (normalized && normalized === lastCapturedPath) return;
- lastCapturedPath = normalized ?? null;
- posthog.capture("$pageview", normalized ? { $current_url: normalized } : undefined);
-}
-
/**
- * On the very first anonymous pageview in a browser session, read UTM +
+ * On the very first anonymous page load in a browser session, read UTM +
* referrer and stash them in a cookie that the backend reads during signup.
*
* Never use raw `document.referrer` as attribution — it can leak OAuth
diff --git a/packages/views/modals/feedback.test.tsx b/packages/views/modals/feedback.test.tsx
index 79b3845ba3..e6ca593b80 100644
--- a/packages/views/modals/feedback.test.tsx
+++ b/packages/views/modals/feedback.test.tsx
@@ -35,7 +35,6 @@ vi.mock("@multica/core/hooks/use-file-upload", () => ({
useFileUpload: () => ({ uploadWithToast: vi.fn() }),
}));
vi.mock("@multica/core/api", () => ({ api: {} }));
-vi.mock("@multica/core/analytics", () => ({ captureFeedbackOpened: vi.fn() }));
vi.mock("sonner", () => ({ toast: { info: vi.fn(), error: vi.fn(), success: vi.fn() } }));
vi.mock("@multica/core/platform", () => ({
formatShortcut: () => "⌘↵",
diff --git a/packages/views/modals/feedback.tsx b/packages/views/modals/feedback.tsx
index 7850e41679..2e144b6d80 100644
--- a/packages/views/modals/feedback.tsx
+++ b/packages/views/modals/feedback.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useEffect, useRef, useState } from "react";
+import { useRef, useState } from "react";
import { toast } from "sonner";
import {
Dialog,
@@ -25,7 +25,6 @@ import {
import { useCurrentWorkspace } from "@multica/core/paths";
import { useFileUpload } from "@multica/core/hooks/use-file-upload";
import { api } from "@multica/core/api";
-import { captureFeedbackOpened } from "@multica/core/analytics";
import { useT } from "../i18n";
import { formatShortcut, modKey, enterKey } from "@multica/core/platform";
@@ -75,15 +74,6 @@ export function FeedbackModal({
const { uploadWithToast } = useFileUpload(api);
const mutation = useCreateFeedback();
- // Fire the "modal opened" analytics event once per mount. Pairs with
- // the backend's `feedback_submitted` to give a funnel completion rate.
- // Workspace id is captured from the closure at mount time — the modal
- // is short-lived, so there's no meaningful workspace switch to track.
- useEffect(() => {
- captureFeedbackOpened("help_menu", workspace?.id);
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
-
const canSubmit =
message.trim().length > 0 &&
message.length <= MAX_MESSAGE_LEN &&
diff --git a/packages/views/onboarding/onboarding-flow.tsx b/packages/views/onboarding/onboarding-flow.tsx
index 30d9436451..e90e06f923 100644
--- a/packages/views/onboarding/onboarding-flow.tsx
+++ b/packages/views/onboarding/onboarding-flow.tsx
@@ -1,9 +1,8 @@
"use client";
-import { useCallback, useEffect, useRef, useState } from "react";
+import { useCallback, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { toast } from "sonner";
-import { captureEvent } from "@multica/core/analytics";
import { setCurrentWorkspace } from "@multica/core/platform";
import { useAuthStore } from "@multica/core/auth";
import {
@@ -145,15 +144,6 @@ export function OnboardingFlow({
});
const existingWorkspace = workspace ?? workspaces[0] ?? null;
const canSkipWelcome = workspacesFetched && workspaces.length > 0;
- const startedEmittedRef = useRef(false);
- useEffect(() => {
- if (startedEmittedRef.current || !workspacesFetched) return;
- startedEmittedRef.current = true;
- captureEvent("onboarding_started", {
- source: "onboarding",
- ...(existingWorkspace ? { workspace_id: existingWorkspace.id } : {}),
- });
- }, [existingWorkspace, workspacesFetched]);
// The `runtimeInstructions` slot is only plumbed by the web shell
// (desktop bundles a daemon, so a CLI install card would be noise
diff --git a/packages/views/onboarding/source-backfill-modal.test.tsx b/packages/views/onboarding/source-backfill-modal.test.tsx
index 8ef72e0a2d..7e6dc9fc6d 100644
--- a/packages/views/onboarding/source-backfill-modal.test.tsx
+++ b/packages/views/onboarding/source-backfill-modal.test.tsx
@@ -7,10 +7,9 @@ import enOnboarding from "../locales/en/onboarding.json";
const TEST_RESOURCES = { en: { common: enCommon, onboarding: enOnboarding } };
-const { mockUser, mockSaveQuestionnaire, mockCaptureEvent } = vi.hoisted(() => ({
+const { mockUser, mockSaveQuestionnaire } = vi.hoisted(() => ({
mockUser: { value: null as null | Record<string, unknown> },
mockSaveQuestionnaire: vi.fn(),
- mockCaptureEvent: vi.fn(),
}));
vi.mock("@multica/core/auth", async () => {
@@ -34,11 +33,6 @@ vi.mock("@multica/core/onboarding", async () => {
return { ...actual, saveQuestionnaire: mockSaveQuestionnaire };
});
-vi.mock("@multica/core/analytics", () => ({
- captureEvent: mockCaptureEvent,
- setPersonProperties: vi.fn(),
-}));
-
import { SourceBackfillModal } from "./source-backfill-modal";
function setUser(partial: Record<string, unknown> | null) {
@@ -81,7 +75,6 @@ function mockPrefersReducedMotion(matches: boolean) {
beforeEach(() => {
mockSaveQuestionnaire.mockReset();
mockSaveQuestionnaire.mockResolvedValue(undefined);
- mockCaptureEvent.mockReset();
setUser(null);
wipeDismissCounters();
mockPrefersReducedMotion(true);
@@ -119,7 +112,7 @@ describe("SourceBackfillModal", () => {
).not.toBeInTheDocument();
});
- it("opens for an onboarded user with empty source and fires the shown event", async () => {
+ it("opens for an onboarded user with empty source", async () => {
setUser({
id: "u1",
onboarded_at: "2026-01-01T00:00:00Z",
@@ -131,7 +124,6 @@ describe("SourceBackfillModal", () => {
screen.getByText(/How did you hear about Multica/i),
).toBeInTheDocument();
});
- expect(mockCaptureEvent).toHaveBeenCalledWith("source_backfill_shown");
});
it("Submit PATCHes the merged questionnaire preserving role / use_case", async () => {
@@ -161,10 +153,6 @@ describe("SourceBackfillModal", () => {
expect(sent.role).toBe("engineer");
expect(sent.use_case).toEqual(["ship_code", "plan_research"]);
expect(sent.version).toBe(2);
- expect(mockCaptureEvent).toHaveBeenCalledWith(
- "source_backfill_submitted",
- expect.objectContaining({ source: ["friends_colleagues"] }),
- );
});
it("Skip PATCHes source_skipped=true preserving role / use_case", async () => {
@@ -191,7 +179,6 @@ describe("SourceBackfillModal", () => {
expect(sent.source_skipped).toBe(true);
expect(sent.role).toBe("founder");
expect(sent.use_case).toEqual(["manage_team"]);
- expect(mockCaptureEvent).toHaveBeenCalledWith("source_backfill_skipped");
});
it("treats a legacy single-string source as already answered", () => {
diff --git a/packages/views/onboarding/source-backfill-modal.tsx b/packages/views/onboarding/source-backfill-modal.tsx
index 39532aeccc..39b65c80db 100644
--- a/packages/views/onboarding/source-backfill-modal.tsx
+++ b/packages/views/onboarding/source-backfill-modal.tsx
@@ -11,7 +11,6 @@ import {
Users,
} from "lucide-react";
import { toast } from "sonner";
-import { captureEvent } from "@multica/core/analytics";
import { useAuthStore } from "@multica/core/auth";
import {
needsSourceBackfill,
@@ -133,13 +132,11 @@ export function SourceBackfillModal() {
if (next || !open) return;
// Base UI fires onOpenChange(false) for X, ESC, and outside
// click — all three count as "dismiss without committing".
- captureEvent("source_backfill_dismissed", { trigger: "close" });
bumpDismissCount();
setOpen(false);
}}
>
<SourceBackfillDialogBody
- open={open}
onComplete={() => setOpen(false)}
/>
</Dialog>
@@ -155,27 +152,14 @@ SourceBackfillModal.displayName = "SourceBackfillModal";
* starts fresh.
*/
function SourceBackfillDialogBody({
- open,
onComplete,
}: {
- open: boolean;
onComplete: () => void;
}) {
const { t } = useT("onboarding");
const [answers, setAnswers] = useState(EMPTY_BACKFILL);
const [busy, setBusy] = useState(false);
- const shownEmittedRef = useRef(false);
-
- // Fire the funnel-open event exactly once per open transition.
- // `open` flips back when the parent closes us, and a fresh subsequent
- // open mounts a brand-new body, so the ref starts fresh too.
- useEffect(() => {
- if (!open) return;
- if (shownEmittedRef.current) return;
- shownEmittedRef.current = true;
- captureEvent("source_backfill_shown");
- }, [open]);
const options = useMemo<QuestionOption[]>(
() => [
@@ -260,10 +244,6 @@ function SourceBackfillDialogBody({
source_skipped: false,
}),
);
- captureEvent("source_backfill_submitted", {
- source: answers.source,
- ...(answers.source_other ? { source_other: answers.source_other } : {}),
- });
onComplete();
} catch (err) {
setBusy(false);
@@ -284,7 +264,6 @@ function SourceBackfillDialogBody({
source_skipped: true,
}),
);
- captureEvent("source_backfill_skipped");
onComplete();
} catch (err) {
setBusy(false);
diff --git a/packages/views/onboarding/steps/step-platform-fork.tsx b/packages/views/onboarding/steps/step-platform-fork.tsx
index e04f847292..19060e9e7f 100644
--- a/packages/views/onboarding/steps/step-platform-fork.tsx
+++ b/packages/views/onboarding/steps/step-platform-fork.tsx
@@ -2,11 +2,6 @@
import { useEffect, useRef, useState, type ReactNode } from "react";
import { ArrowLeft, ArrowRight, Download } from "lucide-react";
-import {
- captureDownloadIntent,
- captureEvent,
- setPersonProperties,
-} from "@multica/core/analytics";
import { Button } from "@multica/ui/components/ui/button";
import {
Dialog,
@@ -74,47 +69,15 @@ export function StepPlatformFork({
const [dialog, setDialog] = useState<DialogState>(null);
const [downloaded, setDownloaded] = useState(false);
- // Platform signal retained purely for PostHog dimensions — the UI
- // no longer branches on it (Windows / Linux desktop installers now
- // ship, so all three platforms get the same card). Computed
- // lazily; SSR-safe because handlers only run client-side.
- const isMac =
- typeof navigator !== "undefined" &&
- (/Mac|iPhone|iPad|iPod/i.test(navigator.platform || "") ||
- /Mac OS X/i.test(navigator.userAgent || ""));
-
const picker = useRuntimePicker(wsId);
const pickDesktop = () => {
window.open(DOWNLOAD_PAGE_URL, "_blank", "noopener,noreferrer");
setDownloaded(true);
- // Step-3-scoped path selection event (kept for existing funnels);
- // `source: "step3"` future-proofs if the event is reused from
- // another surface later.
- captureEvent("onboarding_runtime_path_selected", {
- workspace_id: wsId,
- path: "download_desktop",
- source: "onboarding",
- surface: "step3",
- is_mac: isMac,
- });
- // Cross-surface Desktop intent event — also fires from landing
- // hero / footer / login / Welcome. Enables the top-of-funnel
- // split without retrofitting `onboarding_runtime_path_selected`
- // to non-onboarding contexts.
- captureDownloadIntent("step3");
};
const handleOpenCli = () => {
setDialog("cli");
- captureEvent("onboarding_runtime_path_selected", {
- workspace_id: wsId,
- path: "cli",
- source: "onboarding",
- surface: "step3",
- is_mac: isMac,
- });
- setPersonProperties({ platform_preference: "web" });
};
const handleCliConnect = () => {
diff --git a/packages/views/onboarding/steps/step-runtime-connect.test.tsx b/packages/views/onboarding/steps/step-runtime-connect.test.tsx
index 9b31efa500..696eda8e94 100644
--- a/packages/views/onboarding/steps/step-runtime-connect.test.tsx
+++ b/packages/views/onboarding/steps/step-runtime-connect.test.tsx
@@ -1,5 +1,5 @@
import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
-import { act, render, screen } from "@testing-library/react";
+import { render, screen } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { AgentRuntime } from "@multica/core/types";
import { I18nProvider } from "@multica/core/i18n/react";
@@ -8,13 +8,10 @@ import enOnboarding from "../../locales/en/onboarding.json";
const TEST_RESOURCES = { en: { common: enCommon, onboarding: enOnboarding } };
-// Hoisted mocks — replace analytics and the runtime picker before the SUT
-// imports them. Tests drive picker state via `mocks.pickerState`; every
-// captureEvent / setPersonProperties call lands on `mocks.captureEvent` /
-// `mocks.setPersonProperties` so we can assert the payload shape.
+// Drive the runtime picker via a hoisted mock so the step renders without a
+// live daemon. (The onboarding_runtime_detected PostHog event this file used
+// to cover was removed in MUL-4127.)
const mocks = vi.hoisted(() => ({
- captureEvent: vi.fn<(name: string, props?: Record<string, unknown>) => void>(),
- setPersonProperties: vi.fn<(props: Record<string, unknown>) => void>(),
pickerState: {
runtimes: [] as AgentRuntime[],
selected: null as AgentRuntime | null,
@@ -24,44 +21,12 @@ const mocks = vi.hoisted(() => ({
},
}));
-vi.mock("@multica/core/analytics", () => ({
- captureEvent: mocks.captureEvent,
- setPersonProperties: mocks.setPersonProperties,
-}));
-
vi.mock("../components/use-runtime-picker", () => ({
useRuntimePicker: () => mocks.pickerState,
}));
import { StepRuntimeConnect } from "./step-runtime-connect";
-function makeRuntime(overrides: Partial<AgentRuntime> = {}): AgentRuntime {
- return {
- id: "rt_test",
- workspace_id: "ws_test",
- name: "Claude Code",
- provider: "claude",
- status: "online",
- runtime_mode: "local",
- runtime_config: {},
- device_info: "",
- metadata: {},
- daemon_id: null,
- last_seen_at: new Date().toISOString(),
- created_at: new Date().toISOString(),
- updated_at: new Date().toISOString(),
- ...overrides,
- } as unknown as AgentRuntime;
-}
-
-function setPicker(patch: Partial<typeof mocks.pickerState> = {}) {
- mocks.pickerState.runtimes = patch.runtimes ?? [];
- mocks.pickerState.selected = patch.selected ?? null;
- mocks.pickerState.selectedId = patch.selectedId ?? null;
- mocks.pickerState.hasRuntimes = patch.hasRuntimes ?? false;
- mocks.pickerState.setSelectedId = vi.fn();
-}
-
function renderStep() {
const onNext = vi.fn();
const onBack = vi.fn();
@@ -78,11 +43,12 @@ function renderStep() {
return { onNext, onBack };
}
-describe("StepRuntimeConnect — onboarding_runtime_detected", () => {
+describe("StepRuntimeConnect", () => {
beforeEach(() => {
- mocks.captureEvent.mockReset();
- mocks.setPersonProperties.mockReset();
- setPicker();
+ mocks.pickerState.runtimes = [];
+ mocks.pickerState.selected = null;
+ mocks.pickerState.selectedId = null;
+ mocks.pickerState.hasRuntimes = false;
vi.useFakeTimers({ shouldAdvanceTime: true });
});
@@ -90,143 +56,7 @@ describe("StepRuntimeConnect — onboarding_runtime_detected", () => {
vi.useRealTimers();
});
- it("fires `outcome: found` when runtimes arrive synchronously on mount", () => {
- const rt = makeRuntime({
- id: "rt_claude",
- provider: "claude",
- status: "online",
- });
- setPicker({ runtimes: [rt], selected: rt, selectedId: rt.id, hasRuntimes: true });
-
- renderStep();
-
- expect(mocks.captureEvent).toHaveBeenCalledTimes(1);
- const [name, props] = mocks.captureEvent.mock.calls[0]!;
- expect(name).toBe("onboarding_runtime_detected");
- expect(props).toMatchObject({
- source: "onboarding",
- surface: "step3_desktop",
- workspace_id: "ws_test",
- outcome: "found",
- runtime_count: 1,
- online_count: 1,
- providers: ["claude"],
- has_claude: true,
- has_codex: false,
- has_cursor: false,
- });
- expect(typeof (props as Record<string, unknown>).detect_ms).toBe("number");
-
- expect(mocks.setPersonProperties).toHaveBeenCalledWith({
- has_any_cli: true,
- detected_cli_count: 1,
- });
- });
-
- it("derives has_claude / has_codex / has_cursor from distinct providers", () => {
- setPicker({
- runtimes: [
- makeRuntime({ id: "rt1", provider: "claude" }),
- makeRuntime({ id: "rt2", provider: "codex", status: "offline" }),
- makeRuntime({ id: "rt3", provider: "cursor" }),
- ],
- hasRuntimes: true,
- });
-
- renderStep();
-
- expect(mocks.captureEvent).toHaveBeenCalledTimes(1);
- const props = mocks.captureEvent.mock.calls[0]![1] as Record<string, unknown>;
- expect(props.runtime_count).toBe(3);
- expect(props.online_count).toBe(2);
- expect(props.providers).toEqual(["claude", "codex", "cursor"]);
- expect(props.has_claude).toBe(true);
- expect(props.has_codex).toBe(true);
- expect(props.has_cursor).toBe(true);
- });
-
- it("fires `outcome: empty` after the 5s scanning timeout when no runtimes arrive", () => {
- setPicker({ runtimes: [] });
-
- renderStep();
-
- // Scanning phase: no event yet.
- expect(mocks.captureEvent).not.toHaveBeenCalled();
-
- // Advance past the 5s empty-timeout inside act so the state flip
- // flushes React updates before we assert.
- act(() => {
- vi.advanceTimersByTime(5_001);
- });
-
- expect(mocks.captureEvent).toHaveBeenCalledTimes(1);
- const props = mocks.captureEvent.mock.calls[0]![1] as Record<string, unknown>;
- expect(props).toMatchObject({
- source: "onboarding",
- surface: "step3_desktop",
- workspace_id: "ws_test",
- outcome: "empty",
- runtime_count: 0,
- online_count: 0,
- providers: [],
- has_claude: false,
- has_codex: false,
- has_cursor: false,
- });
-
- expect(mocks.setPersonProperties).toHaveBeenCalledWith({
- has_any_cli: false,
- detected_cli_count: 0,
- });
- });
-
- it("does not re-emit if the component re-renders after resolution", () => {
- const rt = makeRuntime({ id: "rt_claude", provider: "claude" });
- setPicker({ runtimes: [rt], selected: rt, selectedId: rt.id, hasRuntimes: true });
-
- const { onNext } = renderStep();
- expect(mocks.captureEvent).toHaveBeenCalledTimes(1);
-
- // Simulate a runtime coming online / a second runtime registering:
- // the event has already resolved once; it must not re-emit.
- setPicker({
- runtimes: [rt, makeRuntime({ id: "rt_codex", provider: "codex" })],
- selected: rt,
- selectedId: rt.id,
- hasRuntimes: true,
- });
- // Force a re-render by firing a timer tick — React will re-read the
- // mocked picker state but the ref latch keeps the event unique.
- act(() => {
- vi.advanceTimersByTime(1_000);
- });
-
- expect(mocks.captureEvent).toHaveBeenCalledTimes(1);
- expect(onNext).not.toHaveBeenCalled();
- });
-
- it("only counts distinct providers (multiple runtimes of the same provider)", () => {
- setPicker({
- runtimes: [
- makeRuntime({ id: "rt1", provider: "claude" }),
- makeRuntime({ id: "rt2", provider: "claude", status: "offline" }),
- ],
- hasRuntimes: true,
- });
-
- renderStep();
-
- const props = mocks.captureEvent.mock.calls[0]![1] as Record<string, unknown>;
- expect(props.runtime_count).toBe(2);
- expect(props.online_count).toBe(1);
- expect(props.providers).toEqual(["claude"]);
- });
-
- it("mounts without touching framework-level globals", () => {
- // Sanity: the StepHeader renders and the DragStrip doesn't explode
- // under jsdom. Keeps the test file honest if someone refactors the
- // shell around the effect.
- setPicker({ runtimes: [] });
+ it("mounts and shows the scanning UI without touching framework-level globals", () => {
renderStep();
expect(
screen.getByText(/connecting this computer/i),
diff --git a/packages/views/onboarding/steps/step-runtime-connect.tsx b/packages/views/onboarding/steps/step-runtime-connect.tsx
index 9db0b61267..7692304e34 100644
--- a/packages/views/onboarding/steps/step-runtime-connect.tsx
+++ b/packages/views/onboarding/steps/step-runtime-connect.tsx
@@ -3,7 +3,6 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { ArrowLeft, ArrowRight, Loader2, RefreshCw } from "lucide-react";
-import { captureEvent, setPersonProperties } from "@multica/core/analytics";
import { Button } from "@multica/ui/components/ui/button";
import { cn } from "@multica/ui/lib/utils";
import { useScrollFade } from "@multica/ui/hooks/use-scroll-fade";
@@ -117,52 +116,6 @@ function FancyView({
const onlineCount = runtimes.filter((r) => r.status === "online").length;
- // One-shot analytics event when the scan window resolves. Answers the
- // question "did the user actually have any AI CLI installed on this
- // machine when they hit Step 3" — currently unanswerable from the
- // existing funnel because a zero-CLI daemon fails to register at all,
- // so `runtime_registered` is silent on that cohort. Emitting from here
- // (rather than the daemon) keeps the signal in sync with what the UI
- // actually showed the user: "scanning → found" vs "scanning → empty"
- // after the 5s grace period.
- const detectStartRef = useRef<number | null>(null);
- if (detectStartRef.current === null) {
- detectStartRef.current =
- typeof performance !== "undefined" ? performance.now() : Date.now();
- }
- const detectedEmittedRef = useRef(false);
- useEffect(() => {
- if (detectedEmittedRef.current) return;
- if (phase === "scanning") return;
- detectedEmittedRef.current = true;
-
- const providers = Array.from(
- new Set(runtimes.map((r) => r.provider).filter(Boolean)),
- ).sort();
- const now =
- typeof performance !== "undefined" ? performance.now() : Date.now();
- const detectMs = Math.round(now - (detectStartRef.current ?? now));
-
- captureEvent("onboarding_runtime_detected", {
- source: "onboarding",
- surface: "step3_desktop",
- workspace_id: wsId,
- outcome: phase,
- runtime_count: runtimes.length,
- online_count: onlineCount,
- providers,
- has_claude: providers.includes("claude"),
- has_codex: providers.includes("codex"),
- has_cursor: providers.includes("cursor"),
- detect_ms: detectMs,
- });
-
- setPersonProperties({
- has_any_cli: runtimes.length > 0,
- detected_cli_count: runtimes.length,
- });
- }, [phase, runtimes, onlineCount]);
-
const [submitting, setSubmitting] = useState(false);
const [refreshing, setRefreshing] = useState(false);
@@ -177,9 +130,6 @@ function FancyView({
try {
if (onRefresh) await onRefresh();
await qc.invalidateQueries({ queryKey: runtimeKeys.all(wsId) });
- detectedEmittedRef.current = false;
- detectStartRef.current =
- typeof performance !== "undefined" ? performance.now() : Date.now();
setScanEpoch((n) => n + 1);
} finally {
setRefreshing(false);
diff --git a/packages/views/onboarding/steps/step-welcome.tsx b/packages/views/onboarding/steps/step-welcome.tsx
index eaf866c8b0..572b059a14 100644
--- a/packages/views/onboarding/steps/step-welcome.tsx
+++ b/packages/views/onboarding/steps/step-welcome.tsx
@@ -4,7 +4,6 @@ import { useState } from "react";
import { ArrowRight, Download, Loader2 } from "lucide-react";
import { Button, buttonVariants } from "@multica/ui/components/ui/button";
import { MulticaIcon } from "@multica/ui/components/common/multica-icon";
-import { captureDownloadIntent } from "@multica/core/analytics";
import { cn } from "@multica/ui/lib/utils";
import { DragStrip } from "@multica/views/platform";
import { STATUS_CONFIG } from "@multica/core/issues/config";
@@ -117,7 +116,6 @@ export function StepWelcome({
href="/download"
target="_blank"
rel="noopener noreferrer"
- onClick={() => captureDownloadIntent("welcome")}
className={buttonVariants({ size: "lg" })}
>
<Download className="h-4 w-4" />
diff --git a/server/internal/analytics/events.go b/server/internal/analytics/events.go
index 5a8fbdbd2e..67e03bc039 100644
--- a/server/internal/analytics/events.go
+++ b/server/internal/analytics/events.go
@@ -31,19 +31,45 @@ const (
const EventSchemaVersion = 2
-// metricsOnlyEvents are operational / execution-lifecycle events that are
-// recorded to Prometheus (via metrics.IncForEvent, for Grafana) but are
-// deliberately NOT shipped to PostHog. They are high-volume runtime/autopilot
-// telemetry whose per-event PostHog ingestion cost is not justified — Grafana
-// already carries the equivalent counters. metrics.RecordEvent consults this
-// set and skips the PostHog Capture for these names while still incrementing
-// the counter. PostHog is reserved for user/product-behaviour events.
+// metricsOnlyEvents lists every server-side event that is recorded to
+// Prometheus (via metrics.IncForEvent, for Grafana) but deliberately NOT
+// shipped to PostHog. metrics.RecordEvent consults this set and skips the
+// PostHog Capture for these names while still incrementing the counter.
+//
+// As of MUL-4127, PostHog is no longer used for server-side product analytics:
+// the acquisition / activation / expansion funnel is now read straight from the
+// operational database and from these Grafana counters, so the redundant
+// PostHog copy of every product event was retired. That makes ALL server-side
+// events metrics-only — both the product-behaviour group and the original
+// high-volume runtime/autopilot telemetry are Prometheus-only. PostHog now only
+// receives frontend error/crash telemetry ($exception, client_crash,
+// client_unresponsive); see packages/core/analytics and docs/analytics.md.
//
// Note: agent_task_* lifecycle events are also Prometheus-only, but their
// Prometheus side is handled by typed BusinessMetrics.RecordTask* methods, so
// they never build an analytics.Event in the first place and don't need an
// entry here.
var metricsOnlyEvents = map[string]struct{}{
+ // Product-behaviour events — DB + Grafana are the source of truth
+ // (MUL-4127); the PostHog copy was redundant.
+ EventSignup: {},
+ EventWorkspaceCreated: {},
+ EventIssueCreated: {},
+ EventIssueExecuted: {},
+ EventChatMessageSent: {},
+ EventTeamInviteSent: {},
+ EventTeamInviteAccepted: {},
+ EventOnboardingStarted: {},
+ EventOnboardingQuestionnaireSubmit: {},
+ EventAgentCreated: {},
+ EventOnboardingCompleted: {},
+ EventCloudWaitlistJoined: {},
+ EventFeedbackSubmitted: {},
+ EventContactSalesSubmitted: {},
+ EventSquadCreated: {},
+ EventAutopilotCreated: {},
+ // High-volume runtime / autopilot execution-lifecycle telemetry — always
+ // Prometheus-only (Grafana already carries the equivalent counters).
EventRuntimeRegistered: {},
EventRuntimeReady: {},
EventRuntimeFailed: {},
@@ -53,8 +79,9 @@ var metricsOnlyEvents = map[string]struct{}{
EventAutopilotRunFailed: {},
}
-// IsMetricsOnly reports whether an event name is operational telemetry that
-// must be counted in Prometheus but not sent to PostHog. See metricsOnlyEvents.
+// IsMetricsOnly reports whether an event name is recorded to Prometheus but must
+// not be sent to PostHog. As of MUL-4127 this is true for every server-side
+// event. See metricsOnlyEvents.
func IsMetricsOnly(name string) bool {
_, ok := metricsOnlyEvents[name]
return ok
diff --git a/server/internal/analytics/events_test.go b/server/internal/analytics/events_test.go
index fcb911f6bd..f6d9d3613d 100644
--- a/server/internal/analytics/events_test.go
+++ b/server/internal/analytics/events_test.go
@@ -25,23 +25,25 @@ func TestFailedEventsUseWillRetry(t *testing.T) {
}
func TestIsMetricsOnly(t *testing.T) {
- // Operational / execution-lifecycle events are Prometheus-only and must
- // not be shipped to PostHog.
+ // As of MUL-4127, PostHog is retired for server-side product analytics:
+ // every server-side event is Prometheus-only and must not ship to PostHog.
for _, name := range []string{
+ // runtime / autopilot execution-lifecycle telemetry
EventRuntimeRegistered, EventRuntimeReady, EventRuntimeFailed, EventRuntimeOffline,
EventAutopilotRunStarted, EventAutopilotRunCompleted, EventAutopilotRunFailed,
+ // product-behaviour events (now DB + Grafana only)
+ EventSignup, EventWorkspaceCreated, EventIssueCreated, EventIssueExecuted,
+ EventChatMessageSent, EventTeamInviteSent, EventTeamInviteAccepted,
+ EventOnboardingStarted, EventOnboardingQuestionnaireSubmit, EventAgentCreated,
+ EventOnboardingCompleted, EventCloudWaitlistJoined, EventFeedbackSubmitted,
+ EventContactSalesSubmitted, EventSquadCreated, EventAutopilotCreated,
} {
if !IsMetricsOnly(name) {
- t.Errorf("IsMetricsOnly(%q) = false, want true (operational event must stay out of PostHog)", name)
+ t.Errorf("IsMetricsOnly(%q) = false, want true (server events stay out of PostHog since MUL-4127)", name)
}
}
- // Product-behaviour events must still reach PostHog.
- for _, name := range []string{
- EventSignup, EventWorkspaceCreated, EventIssueCreated, EventIssueExecuted,
- EventChatMessageSent, EventAgentCreated, EventAutopilotCreated,
- } {
- if IsMetricsOnly(name) {
- t.Errorf("IsMetricsOnly(%q) = true, want false (product event must reach PostHog)", name)
- }
+ // A name that isn't a declared server event is not metrics-only.
+ if IsMetricsOnly("$exception") {
+ t.Errorf("IsMetricsOnly(%q) = true, want false (frontend-only event)", "$exception")
}
}
diff --git a/server/internal/metrics/business_events.go b/server/internal/metrics/business_events.go
index aaf6295663..2e352f3771 100644
--- a/server/internal/metrics/business_events.go
+++ b/server/internal/metrics/business_events.go
@@ -234,20 +234,20 @@ func (e *businessEventMetrics) collectors() []prometheus.Collector {
}
}
-// RecordEvent enqueues a PostHog event AND increments the matching Prometheus
-// counter so the two cannot drift. Pass `client = nil` (no PostHog) or
-// `m = nil` (no metrics) safely; both sides are best-effort and never block
-// the request path.
+// RecordEvent increments the matching Prometheus counter and, for any event
+// that still ships to PostHog, enqueues the PostHog event too — so the two
+// cannot drift. Pass `client = nil` (no PostHog) or `m = nil` (no metrics)
+// safely; both sides are best-effort and never block the request path.
//
-// Operational / execution-lifecycle events flagged by analytics.IsMetricsOnly
-// (runtime_*, autopilot_run_*) still increment their Prometheus counter but are
-// NOT shipped to PostHog — Grafana already covers them and their high volume is
-// not worth the per-event PostHog ingestion cost. PostHog is reserved for
-// user/product-behaviour events.
+// As of MUL-4127 every server-side event is flagged by analytics.IsMetricsOnly
+// (all product events plus the runtime_* / autopilot_run_* lifecycle), so the
+// client.Capture below is skipped for all of them — server analytics is served
+// from the DB and Grafana, not PostHog. The Capture path is retained only so a
+// future non-metrics-only event name would still ship.
//
-// This is the canonical way to emit any of the funnel / community / commercial
-// PostHog events from server code. Direct analytics.Client.Capture(...) with
-// an event constructed from analytics.* is rejected by the lint test in
+// This is the canonical way to record any funnel / community / commercial event
+// from server code. Direct analytics.Client.Capture(...) with an event
+// constructed from analytics.* is rejected by the lint test in
// business_pairing_test.go.
func RecordEvent(client analytics.Client, m *BusinessMetrics, ev analytics.Event) {
if client != nil && !analytics.IsMetricsOnly(ev.Name) {
diff --git a/server/internal/metrics/record_event_test.go b/server/internal/metrics/record_event_test.go
index a3ac4e0169..27bdd94f6a 100644
--- a/server/internal/metrics/record_event_test.go
+++ b/server/internal/metrics/record_event_test.go
@@ -14,9 +14,10 @@ type captureSpy struct{ names []string }
func (c *captureSpy) Capture(e analytics.Event) { c.names = append(c.names, e.Name) }
func (c *captureSpy) Close() {}
-// TestRecordEventSkipsPostHogForMetricsOnly verifies that operational events
-// flagged by analytics.IsMetricsOnly still increment a Prometheus counter but
-// are NOT shipped to PostHog, while product-behaviour events are shipped.
+// TestRecordEventSkipsPostHogForMetricsOnly verifies that events flagged by
+// analytics.IsMetricsOnly increment a Prometheus counter but are NOT shipped to
+// PostHog. As of MUL-4127 every server-side event is metrics-only, so none of
+// them reach PostHog; only a name outside the set (a frontend event) would.
func TestRecordEventSkipsPostHogForMetricsOnly(t *testing.T) {
spy := &captureSpy{}
m := metrics.NewBusinessMetrics()
@@ -31,14 +32,21 @@ func TestRecordEventSkipsPostHogForMetricsOnly(t *testing.T) {
t.Fatalf("runtime_offline did not increment a Prometheus counter")
}
- metrics.RecordEvent(spy, m, analytics.AutopilotRunCompleted("user-1", "ws-1", "ap-1", "run-1", "manual", analytics.AutopilotAssignee{AgentID: "agent-1", AssigneeType: "agent"}, "manual", 10))
+ // Product-behaviour event: since MUL-4127 it is metrics-only too — the
+ // Prometheus counter still moves but nothing ships to PostHog.
+ before = metrics.SumAllCounters(m)
+ metrics.RecordEvent(spy, m, analytics.WorkspaceCreated("user-1", "ws-1"))
if len(spy.names) != 0 {
- t.Fatalf("autopilot_run_completed shipped to PostHog, want 0: %v", spy.names)
+ t.Fatalf("workspace_created shipped to PostHog, want 0 (metrics-only since MUL-4127): %v", spy.names)
+ }
+ if metrics.SumAllCounters(m) <= before {
+ t.Fatalf("workspace_created did not increment a Prometheus counter")
}
- // Product-behaviour event: still shipped to PostHog.
- metrics.RecordEvent(spy, m, analytics.WorkspaceCreated("user-1", "ws-1"))
- if len(spy.names) != 1 || spy.names[0] != analytics.EventWorkspaceCreated {
- t.Fatalf("workspace_created was not shipped to PostHog exactly once: %v", spy.names)
+ // Sanity-check the Capture path is still wired: a name outside the
+ // metrics-only set (i.e. a frontend event) is shipped to PostHog.
+ metrics.RecordEvent(spy, m, analytics.Event{Name: "frontend_only_probe", DistinctID: "user-1"})
+ if len(spy.names) != 1 || spy.names[0] != "frontend_only_probe" {
+ t.Fatalf("a non-metrics-only event should ship to PostHog exactly once: %v", spy.names)
}
}