Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(analytics): suppress PostHog $pageview on desktop tab/workspace switches (#2033)
Bohan Jiangae9098637d39
diff --git a/apps/desktop/src/renderer/src/components/pageview-tracker.test.tsx b/apps/desktop/src/renderer/src/components/pageview-tracker.test.tsxnew file mode 100644index 0000000000..cadefdb04e--- /dev/null+++ b/apps/desktop/src/renderer/src/components/pageview-tracker.test.tsx@@ -0,0 +1,243 @@+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 new tab is opened (openInNewTab / addTab)", () => {+ state.byWorkspace = {+ acme: {+ activeTabId: "tA",+ tabs: [{ id: "tA", path: "/acme/issues" }],+ },+ };+ state.activeWorkspaceSlug = "acme";++ const { rerender } = render(<PageviewTracker />);+ state.capturePageview.mockClear();++ // Simulate openInNewTab("/acme/agents") → new tab tC added and activated.+ 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.tsxindex 2c07e42f90..17f1694a0e 100644--- a/apps/desktop/src/renderer/src/components/pageview-tracker.tsx+++ b/apps/desktop/src/renderer/src/components/pageview-tracker.tsx@@ -1,11 +1,17 @@-import { useEffect } from "react";+import { useEffect, useRef } from "react";import { capturePageview } from "@multica/core/analytics";import { useAuthStore } from "@multica/core/auth";-import { useTabStore } from "@/stores/tab-store";+import {+ getActiveTab,+ useActiveTabIdentity,+ useTabStore,+} from "@/stores/tab-store";import { useWindowOverlayStore, type WindowOverlay } from "@/stores/window-overlay-store";/**- * Fires a PostHog $pageview whenever the user's visible surface changes.+ * 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:*@@ -17,10 +23,18 @@ import { useWindowOverlayStore, type WindowOverlay } from "@/stores/window-overl* 3. Otherwise → the active tab's path (workspace-scoped, e.g.* `/acme/issues/123`). Kept in sync by `useTabRouterSync`.*- * The overlay takes precedence over the tab path because it is visually in- * front of the tab system; the logged-out state shadows both because the- * shell doesn't render at all yet. This keeps the `$pageview` stream aligned- * with what the user actually sees.+ * 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@@ -29,34 +43,75 @@ import { useWindowOverlayStore, type WindowOverlay } from "@/stores/window-overlexport function PageviewTracker() {const user = useAuthStore((s) => s.user);const overlay = useWindowOverlayStore((s) => s.overlay);- const activeTabPath = useTabStore((s) => {- 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)?.path ?? null;- });+ const { slug: activeWorkspaceSlug, tabId: activeTabId } = useActiveTabIdentity();+ const activeTabPath = useTabStore((s) => getActiveTab(s)?.path ?? null);- const path = resolvePath(user, overlay, activeTabPath);+ // (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(() => {- if (!path) return;+ 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 };++ 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);- }, [path]);+ lastSurfaceRef.current = next;+ }, [user, overlay, activeWorkspaceSlug, activeTabId, activeTabPath]);return null;}-function resolvePath(- user: unknown,- overlay: WindowOverlay | null,- activeTabPath: string | null,-): string | null {- if (!user) return "/login";- if (overlay) return overlayPath(overlay);- return activeTabPath;-}-function overlayPath(overlay: WindowOverlay): string {switch (overlay.type) {case "new-workspace":diff --git a/apps/desktop/vitest.config.ts b/apps/desktop/vitest.config.tsindex 6910af105b..49dcb60b26 100644--- a/apps/desktop/vitest.config.ts+++ b/apps/desktop/vitest.config.ts@@ -1,8 +1,14 @@+import { resolve } from "path";import { defineConfig } from "vitest/config";import react from "@vitejs/plugin-react";export default defineConfig({plugins: [react()],+ resolve: {+ alias: {+ "@": resolve(__dirname, "src/renderer/src"),+ },+ },test: {globals: true,include: ["src/**/*.test.{ts,tsx}", "scripts/**/*.test.mjs"],