:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(desktop): turn on posthog-js network request metrics (#100620)
Paul D'Ambra4af2048ccce2
diff --git a/products/desktop/packages/ui/src/router/navigationTiming.test.ts b/products/desktop/packages/ui/src/router/navigationTiming.test.tsdeleted file mode 100644index 47886eda8850..000000000000--- a/products/desktop/packages/ui/src/router/navigationTiming.test.ts+++ /dev/null@@ -1,54 +0,0 @@-import { afterEach, describe, expect, it, vi } from "vitest";-import { createNavigationTiming } from "./navigationTiming";--describe("createNavigationTiming", () => {- afterEach(() => {- vi.restoreAllMocks();- });-- function stubVisibility(state: DocumentVisibilityState): void {- vi.spyOn(document, "visibilityState", "get").mockReturnValue(state);- }-- it.each(["visible", "hidden"] as const)(- "records the duration when the route settles while %s",- (visibility) => {- stubVisibility(visibility);- vi.spyOn(performance, "now")- .mockReturnValueOnce(100)- .mockReturnValueOnce(175);- const timing = createNavigationTiming();- const record = vi.fn();-- timing.start();- timing.settle(record);-- expect(record).toHaveBeenCalledWith(75, visibility);- },- );-- it("uses the latest navigation start", () => {- stubVisibility("visible");- vi.spyOn(performance, "now")- .mockReturnValueOnce(100)- .mockReturnValueOnce(200)- .mockReturnValueOnce(275);- const timing = createNavigationTiming();- const record = vi.fn();-- timing.start();- timing.start();- timing.settle(record);-- expect(record).toHaveBeenCalledWith(75, "visible");- });-- it("does not record before navigation starts", () => {- const timing = createNavigationTiming();- const record = vi.fn();-- timing.settle(record);-- expect(record).not.toHaveBeenCalled();- });-});diff --git a/products/desktop/packages/ui/src/router/navigationTiming.ts b/products/desktop/packages/ui/src/router/navigationTiming.tsdeleted file mode 100644index ea49efe0a39b..000000000000--- a/products/desktop/packages/ui/src/router/navigationTiming.ts+++ /dev/null@@ -1,24 +0,0 @@-export function createNavigationTiming(): {- start: () => void;- settle: (- record: (- durationMs: number,- visibilityAtSettle: DocumentVisibilityState,- ) => void,- ) => void;-} {- let startedAt: number | null = null;-- return {- start: () => {- startedAt = performance.now();- },- settle: (record) => {- if (startedAt === null) return;-- const durationMs = performance.now() - startedAt;- startedAt = null;- record(durationMs, document.visibilityState);- },- };-}diff --git a/products/desktop/packages/ui/src/router/router.ts b/products/desktop/packages/ui/src/router/router.tsindex 78b05b3c8fa8..82692268c10b 100644--- a/products/desktop/packages/ui/src/router/router.ts+++ b/products/desktop/packages/ui/src/router/router.ts@@ -2,8 +2,6 @@ import {createHashHistory,createRouter as createTanStackRouter,} from "@tanstack/react-router";-import { recordNavigationSettled } from "../shell/analytics";-import { createNavigationTiming } from "./navigationTiming";import { RouteNotFound } from "./RouteNotFound";import { RoutePending } from "./RoutePending";import { isReportPath } from "./reportNavigation";@@ -11,7 +9,6 @@ import { setRouter } from "./routerRef";import { routeTree } from "./routeTree.gen";const reportSourceEntries = new Set<string>();-const navigationTiming = createNavigationTiming();export const router = createTanStackRouter({routeTree,@@ -38,19 +35,11 @@ export const router = createTanStackRouter({});router.subscribe("onBeforeLoad", ({ fromLocation, toLocation }) => {- navigationTiming.start();if (fromLocation?.state.__TSR_key && isReportPath(toLocation.pathname)) {reportSourceEntries.add(fromLocation.state.__TSR_key);}});-router.subscribe("onResolved", () => {- navigationTiming.settle((durationMs, visibilityAtSettle) => {- const route = router.state.matches.at(-1)?.routeId;- if (route) recordNavigationSettled(durationMs, route, visibilityAtSettle);- });-});-// Publish the instance to the leaf ref so imperative callers reach it without a// static import of this module (which would re-create the route-tree cycle).setRouter(router);diff --git a/products/desktop/packages/ui/src/shell/analytics.ts b/products/desktop/packages/ui/src/shell/analytics.tsindex 4171c048c699..011ddc64e960 100644--- a/products/desktop/packages/ui/src/shell/analytics.ts+++ b/products/desktop/packages/ui/src/shell/analytics.ts@@ -30,11 +30,6 @@ export interface AnalyticsTracker {identifyUser(userId: string, properties?: UserIdentifyProperties): void;setUserGroups(user: AnalyticsUserGroups): void;resetUser(): void;- recordNavigationSettled(- durationMs: number,- route: string,- visibilityAtSettle: DocumentVisibilityState,- ): void;captureSurveyResponse(params: {surveyId: string;responses: Array<{ questionId: string; response: string }>;@@ -84,18 +79,6 @@ export function resetUser(): void {resolveService<AnalyticsTracker>(ANALYTICS_TRACKER).resetUser();}-export function recordNavigationSettled(- durationMs: number,- route: string,- visibilityAtSettle: DocumentVisibilityState,-): void {- resolveService<AnalyticsTracker>(ANALYTICS_TRACKER).recordNavigationSettled(- durationMs,- route,- visibilityAtSettle,- );-}-export function captureSurveyResponse(params: {surveyId: string;responses: Array<{ questionId: string; response: string }>;diff --git a/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.test.ts b/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.test.tsindex 67b50255ef25..250fe003aacb 100644--- a/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.test.ts+++ b/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.test.ts@@ -14,7 +14,6 @@ const mockPosthog = {reset: vi.fn(),captureException: vi.fn(),reloadFeatureFlags: vi.fn(),- metrics: { histogram: vi.fn() },};vi.mock("posthog-js/dist/module.full.no-external", () => ({@@ -222,33 +221,78 @@ describe("track", () => {});});-describe("recordNavigationSettled", () => {- it("records duration by route after init", async () => {- const { initializePostHog, recordNavigationSettled } =- await loadAnalytics();- initializePostHog();+describe("networkMetricPath", () => {+ const apiHost = "https://internal-c.posthog.com";- recordNavigationSettled(125, "/tasks/$taskId", "hidden");+ it("leaves the path undefined for the app's own API host", async () => {+ const { networkMetricPath } = await loadAnalytics();- expect(mockPosthog.metrics.histogram).toHaveBeenCalledWith(- "desktop.navigation.settled.duration",- 125,+ const path = networkMetricPath({- unit: "ms",- attributes: {- route: "/tasks/$taskId",- visibility_at_settle: "hidden",- },+ url: "https://internal-c.posthog.com/api/projects/1/tasks/",+ method: "GET",},+ apiHost,);++ expect(path).toBeUndefined();});- it("does nothing before init", async () => {- const { recordNavigationSettled } = await loadAnalytics();+ it("collapses the path for a presigned artifact URL on another host", async () => {+ const { networkMetricPath } = await loadAnalytics();++ const path = networkMetricPath(+ {+ url: "https://s3.example.com/bucket/artifacts/ab12cd34_customer-roadmap.pdf?X-Amz-Signature=abc",+ method: "GET",+ },+ apiHost,+ );++ expect(path).toBe("external");+ });++ it("collapses the path for an unparseable URL", async () => {+ const { networkMetricPath } = await loadAnalytics();++ const path = networkMetricPath(+ { url: "not a url", method: "GET" },+ apiHost,+ );++ expect(path).toBe("external");+ });+});++describe("metrics.network.attributes callback", () => {+ it("returns undefined for requests to the app's own API host", async () => {+ const { initializePostHog } = await loadAnalytics();++ initializePostHog();++ const attributesCallback =+ mockPosthog.init.mock.calls[0][1].metrics.network.attributes;+ const result = attributesCallback({+ url: "https://internal-c.posthog.com/api/projects/1/tasks/",+ method: "GET",+ });- recordNavigationSettled(125, "/tasks/$taskId", "visible");+ expect(result).toBeUndefined();+ });++ it("returns { path: 'external' } for requests to other hosts", async () => {+ const { initializePostHog } = await loadAnalytics();++ initializePostHog();++ const attributesCallback =+ mockPosthog.init.mock.calls[0][1].metrics.network.attributes;+ const result = attributesCallback({+ url: "https://s3.example.com/bucket/artifacts/secret_filename.pdf",+ method: "GET",+ });- expect(mockPosthog.metrics.histogram).not.toHaveBeenCalled();+ expect(result).toEqual({ path: "external" });});});@@ -298,6 +342,7 @@ describe("initializePostHog", () => {metrics: {serviceName: "posthog-desktop",environment: "development",+ network: { attributes: expect.any(Function) },},}),);diff --git a/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.ts b/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.tsindex 8f8e48c13d97..9227936611a8 100644--- a/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.ts+++ b/products/desktop/packages/ui/src/shell/posthogAnalyticsImpl.ts@@ -1,3 +1,4 @@+import type { NetworkMetricsRequest } from "posthog-js/dist/module.full.no-external";import posthog from "posthog-js/dist/module.full.no-external";// Import the recorder to set up __PosthogExtensions__.initSessionRecording// The module.full.no-external bundle includes rrweb but not the initSessionRecording function@@ -110,6 +111,29 @@ let flagsUnavailable = false;const SESSION_IDLE_TIMEOUT_SECONDS = 36_000;+/**+ * Path attribute for the automatic network-duration metric. posthog-js's default+ * path templating only replaces numeric/uuid-like segments, so a presigned+ * task-artifact download/preview URL (whose path embeds the artifact's original,+ * user-controlled filename — see `_build_artifact_storage_path` in+ * products/tasks/backend/facade/api.py) or any other non-API request would leak+ * that filename into the shared Metrics project. Only requests to the app's own+ * API host get path-based attribution; everything else collapses to a fixed+ * value.+ */+export function networkMetricPath(+ request: NetworkMetricsRequest,+ apiHost: string,+): string | undefined {+ try {+ const requestHost = new URL(request.url).host;+ const appHost = new URL(apiHost).host;+ return requestHost === appHost ? undefined : "external";+ } catch {+ return "external";+ }+}+export function initializePostHog(sessionId?: string) {const apiKey = import.meta.env.VITE_POSTHOG_API_KEY;const apiHost =@@ -137,6 +161,17 @@ export function initializePostHog(sessionId?: string) {metrics: {serviceName: "posthog-desktop",environment: import.meta.env.PROD ? "production" : "development",+ // Records every fetch/XHR as an `http.client.request.duration` histogram,+ // keyed by method/host/path (posthog-js templates numeric and uuid-like+ // path segments to `:id` before dimensioning). posthog-js's own capture/flags/session-recording+ // requests are excluded automatically. `attributes` keeps path-based+ // attribution to this app's own API — see `networkMetricPath`.+ network: {+ attributes: (request) => {+ const path = networkMetricPath(request, apiHost);+ return path === undefined ? undefined : { path };+ },+ },},// The epoch turns capture_pageview into "history_change". This app routes via// createHashHistory() (packages/ui/src/router/router.ts), so the route lives in@@ -342,21 +377,6 @@ export function track<K extends keyof EventPropertyMap>(posthog.capture(eventName, properties);}-export function recordNavigationSettled(- durationMs: number,- route: string,- visibilityAtSettle: DocumentVisibilityState,-): void {- if (!isInitialized) {- return;- }-- posthog.metrics.histogram("desktop.navigation.settled.duration", durationMs, {- unit: "ms",- attributes: { route, visibility_at_settle: visibilityAtSettle },- });-}-/*** Record a survey response via posthog-js's `survey sent` event. Pass one entry* per answered question; they're submitted together as a single response. The@@ -521,7 +541,6 @@ export const posthogAnalyticsTracker: AnalyticsTracker = {identifyUser,setUserGroups,resetUser,- recordNavigationSettled,captureSurveyResponse,};