Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat: metric (#21018)

ecmadao41154459ea89
diff --git a/.github/workflows/build-push-cloud-image.yml b/.github/workflows/build-push-cloud-image.yml
index 4072630501..28ad84a0cc 100644
--- a/.github/workflows/build-push-cloud-image.yml
+++ b/.github/workflows/build-push-cloud-image.yml
@@ -52,6 +52,14 @@ jobs:
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
+ - name: Write frontend release env
+ run: |
+ {
+ echo "BB_POSTHOG_KEY=${{ secrets.BB_POSTHOG_KEY }}"
+ echo "BB_POSTHOG_HOST=${{ vars.BB_POSTHOG_HOST }}"
+ echo "BB_POSTHOG_RECORDING_SAMPLE_RATE=${{ vars.BB_POSTHOG_RECORDING_SAMPLE_RATE || '1' }}"
+ } > frontend/.env.release
+
- name: Build and push Docker image
uses: docker/build-push-action@v7
with:
diff --git a/frontend/package.json b/frontend/package.json
index 3844093017..c57fcecbb4 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -71,6 +71,7 @@
"monaco-editor": "npm:@codingame/[email protected]",
"normalize-wheel": "^1.0.1",
"pev2": "1.23.0",
+ "posthog-js": "^1.406.2",
"pouchdb": "^9.0.0",
"pouchdb-find": "^9.0.0",
"qrcode.react": "^4.2.0",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index 82dac44dbc..60bc5933d3 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -148,6 +148,9 @@ importers:
pev2:
specifier: 1.23.0
+ posthog-js:
+ specifier: ^1.406.2
+ version: 1.407.1
pouchdb:
specifier: ^9.0.0
version: 9.0.0
@@ -1427,6 +1430,15 @@ packages:
'@popperjs/[email protected]':
resolution: {integrity: sha512-P1st0aksCrn9sGZhp8GMYwBnQsbvAWsZAX44oXNNvLHGqAOcoVxmjZiohstwQ7SqKnbR47akdNi+uleWD8+g6A==}
+ '@posthog/[email protected]':
+ resolution: {integrity: sha512-w+/0/Be/x48uNM7d/M37ZimSGwhuh8WBSvx61xzKzFnuoV5HqmH7GNDhaM3E3exXoBZmWNPS8hM/Ufy8zoOQSg==}
+
+ '@posthog/[email protected]':
+ resolution: {integrity: sha512-nP5FGwkIk8Ngy45BHzwN/kBGV6jqNZINn+iSge5CbdjMevZsEYK8OG3QOSyysml3yWn4tsRJroGi76+HrBIJuQ==}
+
+ '@posthog/[email protected]':
+ resolution: {integrity: sha512-sJMkl4k+u8yS/0fjHsKqE9xTdsAh30a2WvgChiptellnVoE0e8QJKFgqOMD2sk8FaEArPdeFklAhXvmENAt3Sg==}
+
'@react-dnd/[email protected]':
resolution: {integrity: sha512-kLy0PJDDwvwwTXxqTFNAAllPHD73AycE9ypWeln/IguoGBEbvFcPDbCV03G52bEcC5E+YgupBE0VzHGdC8SIXg==}
@@ -2810,6 +2822,9 @@ packages:
resolution: {integrity: sha512-h9AgfjURuCgA2+2ISl8GbavpUdR+WGAM2McW/ovn4tVccegp8ZqCKWSBR8uRdM8dDNlx5WdKRWxBYUwteLDCNQ==}
+ resolution: {integrity: sha512-zdxgIEddhfsyCaWpJ2SdXEP8ZMrKJ6+5jl4OupODcywU0IhRk6gdXuVGcPICyfx2H97hVK7xmJtRLPjkxAX8Vw==}
+
resolution: {integrity: sha512-P9bmyZ3h/PRG+Nzga+rbdI4OEpNDzAVyy74uVO9ATgzLK6VtAsYybF/+TOCvrc0MO793d6+42lLyZTw7/ArVzA==}
@@ -3537,6 +3552,9 @@ packages:
resolution: {integrity: sha512-KBDEIpLrvpv16pp3K0Fw+UCoZfopFjjgeB+0tA/aaThfEE74kKDLrgg603YvOWJyg3+WYtyq3xYsQWsIyZlPqQ==}
engines: {node: ^10 || ^12 || >=14}
+ resolution: {integrity: sha512-aR3G12pgnSeOOrT16QlgdpDu+KR4mt+FiDgRbp9JDZT8VXp+ihR1dN/tNI7LhtEijUrDm/F6KeqbXCXT/1ox7Q==}
+
resolution: {integrity: sha512-SnTtqwAEiAa3uxKbc1J7LfiBViwEkKe2xkK92zxyTXPqWBvMnh4UU3GXxx7GrXTM4L9llsQ3lSjpbH4CNqG1Mw==}
@@ -3570,6 +3588,14 @@ packages:
resolution: {integrity: sha512-6wjFc/PzwaWz86rmMXoqdBlR/fBSkNoWO1mEJO7RZNS6n3xf+fhhXWAWtws741KpLKx84IkmmJ48tp+fhFzj4A==}
+ resolution: {integrity: sha512-DCHYrK/B10yUD3ZjLfhZ3WIE/9Vf9VFUODcRE2dRomTYDpJk6z6L9wecSfhfE6M9ZTHUdyQkoC46arIDhEV84Q==}
+ peerDependencies:
+ preact-render-to-string: '>=5'
+ peerDependenciesMeta:
+ preact-render-to-string:
+ optional: true
+
resolution: {integrity: sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==}
engines: {node: ^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0}
@@ -3606,6 +3632,9 @@ packages:
resolution: {integrity: sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==}
engines: {node: '>=0.6'}
+ resolution: {integrity: sha512-lT5yCqEBgfoMYpf3F2xQRK7zEr1rhIIZuceDK6+xRkJQ4NMbHTwXqk4NkwDwQMNqXgG9r9fyHnzwNVs6zV5KRw==}
+
resolution: {integrity: sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==}
@@ -4302,6 +4331,9 @@ packages:
resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-q6LWsLatGYZp5VGBIOvbTj6JBV2nOmC8KvWztXBmwJcfFAzhwKwbOxhUH306XY3CcaZDUlSmSuNPBsCn0bFu+g==}
+
resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==}
@@ -5543,6 +5575,17 @@ snapshots:
'@popperjs/[email protected]': {}
+ '@posthog/[email protected]':
+ dependencies:
+ '@posthog/core': 1.45.0
+ '@posthog/types': 1.398.0
+
+ '@posthog/[email protected]':
+ dependencies:
+ '@posthog/types': 1.398.0
+
+ '@posthog/[email protected]': {}
+
'@react-dnd/[email protected]': {}
'@react-dnd/[email protected]': {}
@@ -6844,6 +6887,8 @@ snapshots:
set-cookie-parser: 2.7.2
tough-cookie: 4.1.4
+
@@ -7741,6 +7786,20 @@ snapshots:
picocolors: 1.1.1
source-map-js: 1.2.1
+ dependencies:
+ '@posthog/browser-common': 0.2.0
+ '@posthog/core': 1.45.0
+ '@posthog/types': 1.398.0
+ core-js: 3.49.0
+ dompurify: 3.4.12
+ fflate: 0.4.9
+ preact: 10.29.7
+ query-selector-shadow-dom: 1.0.1
+ web-vitals: 5.3.0
+ transitivePeerDependencies:
+ - preact-render-to-string
+
dependencies:
pouchdb-binary-utils: 9.0.0
@@ -7817,6 +7876,8 @@ snapshots:
transitivePeerDependencies:
- encoding
+
dependencies:
ansi-regex: 5.0.1
@@ -7848,6 +7909,8 @@ snapshots:
es-define-property: 1.0.1
side-channel: 1.1.1
+
@@ -8581,6 +8644,8 @@ snapshots:
dependencies:
xml-name-validator: 5.0.0
+
diff --git a/frontend/src/app/RootLayout.tsx b/frontend/src/app/RootLayout.tsx
index 8167637eca..679426425e 100644
--- a/frontend/src/app/RootLayout.tsx
+++ b/frontend/src/app/RootLayout.tsx
@@ -2,6 +2,7 @@ import { useRef } from "react";
import type { Location } from "react-router";
import { matchRoutes, Outlet, useBlocker } from "react-router";
import { AuthGate } from "@/app/AuthGate";
+import { RouteBehaviorRecorder } from "@/app/analytics/RouteBehaviorRecorder";
import type { ReactRoute } from "@/app/router";
import { buildReactRoute, runBeforeEachGuards } from "@/app/router";
import { NavigationScrollRestoration } from "@/app/router/NavigationScrollRestoration";
@@ -70,6 +71,7 @@ export function RootLayout() {
<AgentWindow />
<SessionExpiredSurfaceGate />
<LeaveGuardBlocker />
+ <RouteBehaviorRecorder />
<NavigationScrollRestoration>
<AuthGate>
<Outlet />
diff --git a/frontend/src/app/analytics/RouteBehaviorRecorder.test.tsx b/frontend/src/app/analytics/RouteBehaviorRecorder.test.tsx
new file mode 100644
index 0000000000..20d33a7f88
--- /dev/null
+++ b/frontend/src/app/analytics/RouteBehaviorRecorder.test.tsx
@@ -0,0 +1,240 @@
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const mocks = vi.hoisted(() => ({
+ route: {
+ name: "workspace.project.database",
+ fullPath: "/projects/customer-a/[email protected]",
+ },
+ appStore: {
+ isSaaS: true,
+ enableMetricCollection: true,
+ currentUserName: "users/[email protected]",
+ workspace: "workspaces/customer-a",
+ },
+ analytics: {
+ disable: vi.fn(),
+ init: vi.fn(),
+ identify: vi.fn(),
+ reset: vi.fn(),
+ captureMetric: vi.fn(),
+ },
+}));
+
+vi.mock("@/app/router", () => ({
+ useCurrentRoute: () => mocks.route,
+}));
+
+vi.mock("@/stores/app", () => ({
+ useAppStore: (selector: (state: unknown) => unknown) =>
+ selector({
+ currentUserName: mocks.appStore.currentUserName,
+ isSaaSMode: () => mocks.appStore.isSaaS,
+ getWorkspaceProfile: () => ({
+ enableMetricCollection: mocks.appStore.enableMetricCollection,
+ }),
+ workspaceResourceName: () => mocks.appStore.workspace,
+ }),
+}));
+
+vi.mock("./provider", () => ({
+ behaviorAnalytics: mocks.analytics,
+}));
+
+import { RouteBehaviorRecorder } from "./RouteBehaviorRecorder";
+
+describe("RouteBehaviorRecorder", () => {
+ let container: HTMLDivElement;
+ let root: Root;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ mocks.route.name = "workspace.project.database";
+ mocks.route.fullPath = "/projects/customer-a/[email protected]";
+ mocks.appStore.isSaaS = true;
+ mocks.appStore.enableMetricCollection = true;
+ mocks.appStore.currentUserName = "users/[email protected]";
+ mocks.appStore.workspace = "workspaces/customer-a";
+ vi.stubEnv("BB_POSTHOG_KEY", "phc_test");
+ vi.stubEnv("BB_POSTHOG_HOST", "https://us.i.posthog.com");
+ vi.stubEnv("BB_POSTHOG_RECORDING_SAMPLE_RATE", "1");
+ vi.stubEnv("GIT_COMMIT", "abc123");
+ });
+
+ afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ vi.clearAllMocks();
+ vi.unstubAllEnvs();
+ vi.useRealTimers();
+ });
+
+ test("initializes PostHog without manually starting route recordings", async () => {
+ await act(async () => {
+ root.render(<RouteBehaviorRecorder />);
+ });
+
+ expect(mocks.analytics.init).toHaveBeenCalledOnce();
+ expect(mocks.analytics.identify).toHaveBeenCalledWith(
+ expect.objectContaining({
+ user: "users/[email protected]",
+ workspace: "workspaces/customer-a",
+ })
+ );
+ expect(mocks.analytics.init).toHaveBeenCalledWith(
+ expect.objectContaining({
+ options: expect.objectContaining({
+ capture_pageview: "history_change",
+ disable_session_recording: false,
+ }),
+ properties: {
+ git_commit: "abc123",
+ },
+ })
+ );
+ });
+
+ test("does not initialize PostHog outside Bytebase Cloud", async () => {
+ mocks.appStore.isSaaS = false;
+
+ await act(async () => {
+ root.render(<RouteBehaviorRecorder />);
+ });
+
+ expect(mocks.analytics.init).not.toHaveBeenCalled();
+ expect(mocks.analytics.disable).toHaveBeenCalledOnce();
+ });
+
+ test("does not initialize PostHog when workspace metric collection is disabled", async () => {
+ mocks.appStore.enableMetricCollection = false;
+
+ await act(async () => {
+ root.render(<RouteBehaviorRecorder />);
+ });
+
+ expect(mocks.analytics.init).not.toHaveBeenCalled();
+ expect(mocks.analytics.disable).toHaveBeenCalledOnce();
+ });
+
+ test("disables PostHog after workspace metric collection is disabled", async () => {
+ await act(async () => {
+ root.render(<RouteBehaviorRecorder />);
+ });
+
+ mocks.appStore.enableMetricCollection = false;
+ await act(async () => {
+ root.render(<RouteBehaviorRecorder />);
+ });
+
+ expect(mocks.analytics.init).toHaveBeenCalledOnce();
+ expect(mocks.analytics.disable).toHaveBeenCalledOnce();
+ });
+
+ test("passes replay sample rate to PostHog without local route sampling", async () => {
+ vi.stubEnv("BB_POSTHOG_RECORDING_SAMPLE_RATE", "0");
+
+ await act(async () => {
+ root.render(<RouteBehaviorRecorder />);
+ });
+
+ expect(mocks.analytics.init).toHaveBeenCalledOnce();
+ expect(mocks.analytics.init).toHaveBeenCalledWith(
+ expect.objectContaining({
+ options: expect.objectContaining({
+ session_recording: expect.objectContaining({
+ sampleRate: 0,
+ }),
+ }),
+ })
+ );
+ });
+
+ test("uses default replay sample rate when the env value is invalid", async () => {
+ vi.stubEnv("BB_POSTHOG_RECORDING_SAMPLE_RATE", "abc");
+
+ await act(async () => {
+ root.render(<RouteBehaviorRecorder />);
+ });
+
+ expect(mocks.analytics.init).toHaveBeenCalledOnce();
+ expect(mocks.analytics.init).toHaveBeenCalledWith(
+ expect.objectContaining({
+ options: expect.objectContaining({
+ session_recording: expect.objectContaining({
+ sampleRate: 1,
+ }),
+ }),
+ })
+ );
+ });
+
+ test("keeps PostHog initialized when entering a sensitive route", async () => {
+ await act(async () => {
+ root.render(<RouteBehaviorRecorder />);
+ });
+
+ mocks.route.name = "sql-editor.database";
+ mocks.route.fullPath =
+ "/sql-editor/projects/customer-a/instances/prod/databases/main";
+
+ await act(async () => {
+ root.render(<RouteBehaviorRecorder />);
+ });
+
+ expect(mocks.analytics.init).toHaveBeenCalledOnce();
+ });
+
+ test("emits a page session metric when leaving an allowed activation route", async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(1_000);
+
+ await act(async () => {
+ root.render(<RouteBehaviorRecorder />);
+ });
+
+ vi.setSystemTime(6_000);
+ mocks.route.name = "workspace.instance.create";
+ mocks.route.fullPath = "/instances/new";
+
+ await act(async () => {
+ root.render(<RouteBehaviorRecorder />);
+ });
+
+ expect(mocks.analytics.captureMetric).toHaveBeenCalledWith({
+ event: "page session",
+ properties: expect.objectContaining({
+ route_id: "workspace.project.database",
+ duration_ms: 5000,
+ visible_duration_ms: 5000,
+ }),
+ });
+ });
+
+ test("emits a route-level page navigation metric on route changes", async () => {
+ await act(async () => {
+ root.render(<RouteBehaviorRecorder />);
+ });
+
+ mocks.route.name = "workspace.instance.create";
+ mocks.route.fullPath = "/instances/new";
+
+ await act(async () => {
+ root.render(<RouteBehaviorRecorder />);
+ });
+
+ expect(mocks.analytics.captureMetric).toHaveBeenCalledWith({
+ event: "page navigated",
+ properties: {
+ from_route_id: "workspace.project.database",
+ to_route_id: "workspace.instance.create",
+ },
+ });
+ });
+});
diff --git a/frontend/src/app/analytics/RouteBehaviorRecorder.tsx b/frontend/src/app/analytics/RouteBehaviorRecorder.tsx
new file mode 100644
index 0000000000..ebf6779e9f
--- /dev/null
+++ b/frontend/src/app/analytics/RouteBehaviorRecorder.tsx
@@ -0,0 +1,170 @@
+import { useEffect, useMemo, useRef } from "react";
+import { useCurrentRoute } from "@/app/router";
+import { useAppStore } from "@/stores/app";
+import type { BehaviorRecordingDecision } from "./behavior";
+import {
+ buildBehaviorAnalyticsConfig,
+ classifyBehaviorRoute,
+ createBehaviorMetric,
+} from "./behavior";
+import { behaviorAnalytics } from "./provider";
+
+type ActivePageSession = {
+ decision: Extract<BehaviorRecordingDecision, { recording: "allow" }>;
+ startedAt: number;
+ visibleStartedAt: number | undefined;
+ visibleDurationMs: number;
+};
+
+const BOUNCE_THRESHOLD_MS = 5_000;
+const DEFAULT_RECORDING_SAMPLE_RATE = 1;
+
+export function RouteBehaviorRecorder() {
+ const isSaaSMode = useAppStore((state) => state.isSaaSMode());
+ const enableMetricCollection = useAppStore(
+ (state) => state.getWorkspaceProfile().enableMetricCollection
+ );
+ const enabled = isSaaSMode && enableMetricCollection;
+
+ useEffect(() => {
+ if (!enabled) {
+ behaviorAnalytics.disable();
+ }
+ }, [enabled]);
+
+ if (!enabled) {
+ return null;
+ }
+
+ return <EnabledRouteBehaviorRecorder />;
+}
+
+function EnabledRouteBehaviorRecorder() {
+ const route = useCurrentRoute();
+ const currentUserName = useAppStore((state) => state.currentUserName);
+ const workspaceName = useAppStore((state) => state.workspaceResourceName());
+ const pageSessionRef = useRef<ActivePageSession | undefined>(undefined);
+
+ const config = useMemo(
+ () =>
+ buildBehaviorAnalyticsConfig({
+ posthogKey: import.meta.env.BB_POSTHOG_KEY as string | undefined,
+ posthogHost: import.meta.env.BB_POSTHOG_HOST as string | undefined,
+ gitCommit: import.meta.env.GIT_COMMIT as string | undefined,
+ recordingSampleRate: parseRecordingSampleRate(
+ import.meta.env.BB_POSTHOG_RECORDING_SAMPLE_RATE as string | undefined
+ ),
+ }),
+ []
+ );
+
+ useEffect(() => {
+ if (!config) {
+ return;
+ }
+ void behaviorAnalytics.init(config);
+ }, [config]);
+
+ useEffect(() => {
+ if (!config) {
+ return;
+ }
+ if (!currentUserName) {
+ behaviorAnalytics.reset();
+ return;
+ }
+ behaviorAnalytics.identify({
+ user: currentUserName,
+ workspace: workspaceName,
+ });
+ }, [config, currentUserName, workspaceName]);
+
+ useEffect(() => {
+ if (!config) {
+ return;
+ }
+
+ const decision = classifyBehaviorRoute({
+ name: route.name,
+ });
+ const previousSession = pageSessionRef.current;
+ endPageSession(previousSession);
+ if (
+ previousSession &&
+ decision.recording === "allow" &&
+ previousSession.decision.routeId !== decision.routeId
+ ) {
+ behaviorAnalytics.captureMetric(
+ createBehaviorMetric("page navigated", {
+ properties: {
+ from_route_id: previousSession.decision.routeId,
+ to_route_id: decision.routeId,
+ },
+ })
+ );
+ }
+ pageSessionRef.current =
+ decision.recording === "allow"
+ ? {
+ decision,
+ startedAt: Date.now(),
+ visibleStartedAt: document.hidden ? undefined : Date.now(),
+ visibleDurationMs: 0,
+ }
+ : undefined;
+ }, [config, route.name, route.fullPath]);
+
+ useEffect(() => {
+ const handleVisibilityChange = () => {
+ const session = pageSessionRef.current;
+ if (!session) {
+ return;
+ }
+ if (document.hidden) {
+ session.visibleDurationMs += visibleSegmentMs(session);
+ session.visibleStartedAt = undefined;
+ return;
+ }
+ session.visibleStartedAt = Date.now();
+ };
+ document.addEventListener("visibilitychange", handleVisibilityChange);
+ return () => {
+ document.removeEventListener("visibilitychange", handleVisibilityChange);
+ endPageSession(pageSessionRef.current);
+ pageSessionRef.current = undefined;
+ };
+ }, []);
+
+ return null;
+}
+
+function endPageSession(session: ActivePageSession | undefined): void {
+ if (!session) {
+ return;
+ }
+ const durationMs = Date.now() - session.startedAt;
+ const visibleDurationMs =
+ session.visibleDurationMs + visibleSegmentMs(session);
+ behaviorAnalytics.captureMetric(
+ createBehaviorMetric("page session", {
+ routeId: session.decision.routeId,
+ durationMs,
+ visibleDurationMs,
+ isBounce: durationMs < BOUNCE_THRESHOLD_MS,
+ })
+ );
+}
+
+function visibleSegmentMs(session: ActivePageSession): number {
+ return session.visibleStartedAt === undefined
+ ? 0
+ : Date.now() - session.visibleStartedAt;
+}
+
+function parseRecordingSampleRate(value: string | undefined): number {
+ const parsed = Number(value);
+ if (!Number.isFinite(parsed)) {
+ return DEFAULT_RECORDING_SAMPLE_RATE;
+ }
+ return Math.min(Math.max(parsed, 0), 1);
+}
diff --git a/frontend/src/app/analytics/behavior.test.ts b/frontend/src/app/analytics/behavior.test.ts
new file mode 100644
index 0000000000..b952c736cf
--- /dev/null
+++ b/frontend/src/app/analytics/behavior.test.ts
@@ -0,0 +1,286 @@
+import { describe, expect, test } from "vitest";
+import type { BehaviorMetricInput } from "./behavior";
+import {
+ behaviorMetricDefinitions,
+ buildBehaviorAnalyticsConfig,
+ classifyBehaviorRoute,
+ createBehaviorMetric,
+ sanitizeBehaviorProperties,
+} from "./behavior";
+
+describe("behavior analytics config", () => {
+ test("stays disabled unless a PostHog key and host are both present", () => {
+ expect(
+ buildBehaviorAnalyticsConfig({
+ posthogKey: "",
+ posthogHost: "https://us.i.posthog.com",
+ recordingSampleRate: 0.1,
+ })
+ ).toBeNull();
+
+ expect(
+ buildBehaviorAnalyticsConfig({
+ posthogKey: "phc_test",
+ recordingSampleRate: 0.1,
+ })
+ ).toBeNull();
+ });
+
+ test("uses PostHog-native pageview and recording defaults when enabled", () => {
+ const config = buildBehaviorAnalyticsConfig({
+ posthogKey: "phc_test",
+ posthogHost: "https://us.i.posthog.com",
+ recordingSampleRate: 0.25,
+ });
+
+ expect(config).toMatchObject({
+ apiKey: "phc_test",
+ options: {
+ api_host: "https://us.i.posthog.com",
+ autocapture: {
+ capture_copied_text: false,
+ css_selector_ignorelist: [
+ ".ph-no-autocapture",
+ "[data-ph-no-autocapture]",
+ ".ph-no-capture",
+ "[data-sensitive]",
+ ],
+ dom_event_allowlist: ["click", "submit"],
+ element_allowlist: ["a", "button", "form", "label"],
+ element_attribute_ignorelist: [
+ "aria-label",
+ "href",
+ "title",
+ "data-sensitive",
+ ],
+ },
+ capture_pageview: "history_change",
+ capture_pageleave: true,
+ disable_session_recording: false,
+ person_profiles: "identified_only",
+ session_recording: {
+ maskAllInputs: true,
+ blockClass: "ph-no-capture",
+ sampleRate: 0.25,
+ },
+ },
+ });
+ if (!config) {
+ throw new Error("Expected behavior analytics config");
+ }
+ expect(
+ (config.options.session_recording as Record<string, unknown>)
+ .maskTextSelector
+ ).toBeUndefined();
+ });
+
+ test("adds build commit metadata to PostHog event properties", () => {
+ const config = buildBehaviorAnalyticsConfig({
+ posthogKey: "phc_test",
+ posthogHost: "https://us.i.posthog.com",
+ recordingSampleRate: 0.25,
+ gitCommit: "abc123",
+ });
+
+ if (!config) {
+ throw new Error("Expected behavior analytics config");
+ }
+ expect(config.properties).toEqual({
+ git_commit: "abc123",
+ });
+
+ const sanitizeProperties = config.options.sanitize_properties as (
+ properties: Record<string, unknown>,
+ eventName?: string
+ ) => Record<string, unknown>;
+
+ expect(
+ sanitizeProperties(
+ {
+ $current_url: "https://cloud.bytebase.com/projects/acme?token=secret",
+ },
+ "$pageview"
+ )
+ ).toEqual({
+ git_commit: "abc123",
+ });
+ });
+});
+
+describe("behavior analytics routes", () => {
+ test("allows page sessions on any named route", () => {
+ expect(
+ classifyBehaviorRoute({
+ name: "auth.profile.setup",
+ })
+ ).toMatchObject({
+ routeId: "auth.profile.setup",
+ recording: "allow",
+ });
+
+ expect(
+ classifyBehaviorRoute({
+ name: "sql-editor.database",
+ })
+ ).toMatchObject({
+ routeId: "sql-editor.database",
+ recording: "allow",
+ });
+
+ expect(
+ classifyBehaviorRoute({
+ name: "workspace.audit-log",
+ })
+ ).toMatchObject({
+ routeId: "workspace.audit-log",
+ recording: "allow",
+ });
+ });
+
+ test("ignores missing route names", () => {
+ expect(
+ classifyBehaviorRoute({
+ name: undefined,
+ })
+ ).toEqual({
+ recording: "ignore",
+ });
+ });
+});
+
+describe("behavior analytics privacy helpers", () => {
+ test("removes URL-like and raw error properties before provider capture", () => {
+ expect(
+ sanitizeBehaviorProperties({
+ route_id: "workspace.instance.create",
+ $current_url:
+ "https://cloud.bytebase.com/projects/customer-a/[email protected]",
+ current_url:
+ "https://cloud.bytebase.com/sql-editor/projects/p1/sheets/s1",
+ raw_error: "dial tcp db.internal:5432 failed",
+ safe: true,
+ })
+ ).toEqual({
+ route_id: "workspace.instance.create",
+ safe: true,
+ });
+ });
+
+ test("removes page URL properties for PostHog pageviews", () => {
+ expect(
+ sanitizeBehaviorProperties(
+ {
+ $current_url:
+ "https://cloud.bytebase.com/projects/customer-a/[email protected]#token",
+ $pathname: "/projects/customer-a/databases",
+ current_url:
+ "https://cloud.bytebase.com/sql-editor/projects/p1/sheets/s1",
+ },
+ "$pageview"
+ )
+ ).toEqual({});
+ });
+
+ test("removes visible element text from autocapture payloads", () => {
+ expect(
+ sanitizeBehaviorProperties(
+ {
+ $el_text: "users/[email protected]",
+ $elements: [
+ {
+ $el_text: "users/[email protected]",
+ attr__href: "/users/[email protected]",
+ tag_name: "a",
+ },
+ ],
+ $elements_chain: "a.users attr__href=/users/[email protected]",
+ safe: true,
+ },
+ "$autocapture"
+ )
+ ).toEqual({
+ safe: true,
+ });
+ });
+});
+
+describe("behavior analytics metrics", () => {
+ test("defines metric names in one map", () => {
+ expect([...behaviorMetricDefinitions.keys()]).toContain("page session");
+ expect([...behaviorMetricDefinitions.keys()]).toContain("page navigated");
+ });
+
+ test("creates allowlisted page session metrics with route context", () => {
+ expect(
+ createBehaviorMetric("page session", {
+ routeId: "workspace.instance.create",
+ durationMs: 12_000,
+ visibleDurationMs: 9_000,
+ isBounce: false,
+ })
+ ).toEqual({
+ event: "page session",
+ properties: {
+ route_id: "workspace.instance.create",
+ duration_ms: 12_000,
+ visible_duration_ms: 9_000,
+ is_bounce: false,
+ },
+ });
+ });
+
+ test("creates allowlisted page navigation metrics with route transition context", () => {
+ expect(
+ createBehaviorMetric("page navigated", {
+ properties: {
+ from_route_id: "workspace.landing",
+ to_route_id: "workspace.instance.create",
+ },
+ })
+ ).toEqual({
+ event: "page navigated",
+ properties: {
+ from_route_id: "workspace.landing",
+ to_route_id: "workspace.instance.create",
+ },
+ });
+ });
+
+ test("keeps route transition context out of the shared metric input fields", () => {
+ const routeTransitionInput = {
+ // @ts-expect-error route transitions should use event-specific properties.
+ fromRouteId: "workspace.landing",
+ } satisfies BehaviorMetricInput;
+
+ expect(routeTransitionInput).toEqual({
+ fromRouteId: "workspace.landing",
+ });
+ });
+
+ test("creates allowlisted custom action metrics and drops unsafe properties", () => {
+ expect(
+ createBehaviorMetric("setup guide action clicked", {
+ routeId: "workspace.landing",
+ resource: "projects/demo",
+ properties: {
+ step: "hasProject",
+ },
+ })
+ ).toEqual({
+ event: "setup guide action clicked",
+ properties: {
+ route_id: "workspace.landing",
+ resource: "projects/demo",
+ step: "hasProject",
+ },
+ });
+ });
+
+ test("drops unset metric properties", () => {
+ const metric = createBehaviorMetric("instance connection test clicked", {
+ routeId: "workspace.instance.detail",
+ });
+
+ expect(Object.keys(metric.properties)).toEqual(["route_id"]);
+ });
+});
diff --git a/frontend/src/app/analytics/behavior.ts b/frontend/src/app/analytics/behavior.ts
new file mode 100644
index 0000000000..861bc302a1
--- /dev/null
+++ b/frontend/src/app/analytics/behavior.ts
@@ -0,0 +1,181 @@
+export type BehaviorRecordingDecision =
+ | {
+ routeId: string;
+ recording: "allow";
+ }
+ | {
+ recording: "ignore";
+ };
+
+export type BehaviorRouteInput = {
+ name?: string;
+};
+
+export type BehaviorAnalyticsConfig = {
+ apiKey: string;
+ options: Record<string, unknown>;
+ properties?: Record<string, unknown>;
+};
+
+// PostHog recommends "[object] [verb]" event names.
+// https://posthog.com/docs/product-analytics/capture-events
+export const behaviorMetricDefinitions = new Map([
+ ["page session", {}],
+ ["page navigated", {}],
+ ["connect database clicked", {}],
+ ["instance connection test clicked", {}],
+ ["instance create clicked", {}],
+ ["setup guide action clicked", {}],
+ ["setup guide dismissed", {}],
+ ["post sync first change clicked", {}],
+ ["post sync sql editor clicked", {}],
+ ["trust guidance viewed", {}],
+ ["sample database started", {}],
+] as const);
+
+export type BehaviorMetricName =
+ typeof behaviorMetricDefinitions extends ReadonlyMap<infer Name, unknown>
+ ? Name
+ : never;
+
+export type BehaviorMetric = {
+ event: BehaviorMetricName;
+ properties: Record<string, unknown>;
+};
+
+export type BehaviorMetricInput = {
+ routeId?: string;
+ properties?: Record<string, unknown>;
+ resource?: string;
+ durationMs?: number;
+ visibleDurationMs?: number;
+ isBounce?: boolean;
+};
+
+export function buildBehaviorAnalyticsConfig(params: {
+ posthogKey?: string;
+ posthogHost?: string;
+ gitCommit?: string;
+ recordingSampleRate: number;
+}): BehaviorAnalyticsConfig | null {
+ const apiKey = params.posthogKey?.trim();
+ const apiHost = params.posthogHost?.trim();
+ if (!apiKey || !apiHost) {
+ return null;
+ }
+ const properties = sanitizeBehaviorProperties({
+ git_commit: params.gitCommit?.trim() || undefined,
+ });
+
+ return {
+ apiKey,
+ properties,
+ options: {
+ api_host: apiHost,
+ autocapture: {
+ capture_copied_text: false,
+ css_selector_ignorelist: [
+ ".ph-no-autocapture",
+ "[data-ph-no-autocapture]",
+ ".ph-no-capture",
+ "[data-sensitive]",
+ ],
+ dom_event_allowlist: ["click", "submit"],
+ element_allowlist: ["a", "button", "form", "label"],
+ element_attribute_ignorelist: [
+ "aria-label",
+ "href",
+ "title",
+ "data-sensitive",
+ ],
+ },
+ capture_pageview: "history_change",
+ capture_pageleave: true,
+ disable_session_recording: false,
+ person_profiles: "identified_only",
+ sanitize_properties: (
+ eventProperties: Record<string, unknown>,
+ eventName?: string
+ ) => ({
+ ...sanitizeBehaviorProperties(eventProperties, eventName),
+ ...properties,
+ }),
+ session_recording: {
+ maskAllInputs: true,
+ blockClass: "ph-no-capture",
+ sampleRate: params.recordingSampleRate,
+ maskCapturedNetworkRequestFn: () => null,
+ },
+ },
+ };
+}
+
+export function classifyBehaviorRoute(
+ route: BehaviorRouteInput
+): BehaviorRecordingDecision {
+ const name = route.name;
+ if (!name) {
+ return { recording: "ignore" };
+ }
+ return {
+ routeId: name,
+ recording: "allow",
+ };
+}
+
+export function sanitizeBehaviorProperties(
+ properties: Record<string, unknown>,
+ _eventName?: string
+): Record<string, unknown> {
+ const sanitized: Record<string, unknown> = {};
+ for (const [key, value] of Object.entries(properties)) {
+ if (value === undefined) {
+ continue;
+ }
+ if (isForbiddenPropertyKey(key)) {
+ continue;
+ }
+ sanitized[key] = value;
+ }
+ return sanitized;
+}
+
+export function createBehaviorMetric(
+ event: BehaviorMetricName,
+ input: BehaviorMetricInput = {}
+): BehaviorMetric {
+ if (!behaviorMetricDefinitions.has(event)) {
+ throw new Error(`Unsupported behavior metric: ${event}`);
+ }
+ const customProperties = sanitizeBehaviorProperties(input.properties ?? {});
+ const standardProperties = sanitizeBehaviorProperties({
+ route_id: input.routeId,
+ resource: input.resource,
+ duration_ms: input.durationMs,
+ visible_duration_ms: input.visibleDurationMs,
+ is_bounce: input.isBounce,
+ });
+
+ return {
+ event,
+ properties: {
+ ...customProperties,
+ ...standardProperties,
+ },
+ };
+}
+
+function isForbiddenPropertyKey(key: string): boolean {
+ const normalized = key.toLowerCase();
+ return (
+ normalized === "$el_text" ||
+ normalized === "$elements" ||
+ normalized === "$elements_chain" ||
+ normalized.includes("url") ||
+ normalized.includes("path") ||
+ normalized.includes("referrer") ||
+ normalized.includes("host") ||
+ normalized.includes("error") ||
+ normalized.includes("message")
+ );
+}
diff --git a/frontend/src/app/analytics/provider.test.ts b/frontend/src/app/analytics/provider.test.ts
new file mode 100644
index 0000000000..a197a0db6a
--- /dev/null
+++ b/frontend/src/app/analytics/provider.test.ts
@@ -0,0 +1,170 @@
+import { describe, expect, test, vi } from "vitest";
+import type { BehaviorAnalyticsConfig } from "./behavior";
+import { createBehaviorAnalytics } from "./provider";
+
+function createClient() {
+ return {
+ init: vi.fn(),
+ identify: vi.fn(),
+ opt_in_capturing: vi.fn(),
+ opt_out_capturing: vi.fn(),
+ reset: vi.fn(),
+ capture: vi.fn(),
+ startSessionRecording: vi.fn(),
+ stopSessionRecording: vi.fn(),
+ };
+}
+
+const config: BehaviorAnalyticsConfig = {
+ apiKey: "phc_test",
+ options: {},
+};
+
+const configWithProperties: BehaviorAnalyticsConfig = {
+ apiKey: "phc_test",
+ options: {},
+ properties: {
+ git_commit: "abc123",
+ },
+};
+
+describe("BehaviorAnalytics provider", () => {
+ test("applies pending identify requests after async init", async () => {
+ const client = createClient();
+ const analytics = createBehaviorAnalytics(
+ () => new Promise((resolve) => setTimeout(() => resolve(client), 0))
+ );
+
+ const init = analytics.init(config);
+ analytics.identify({
+ user: "users/[email protected]",
+ workspace: "workspaces/acme",
+ });
+
+ await init;
+
+ expect(client.identify).toHaveBeenCalledWith("users/[email protected]", {
+ user: "users/[email protected]",
+ workspace: "workspaces/acme",
+ });
+ });
+
+ test("queues metrics captured before async init completes", async () => {
+ const client = createClient();
+ const analytics = createBehaviorAnalytics(
+ () => new Promise((resolve) => setTimeout(() => resolve(client), 0))
+ );
+
+ const init = analytics.init(config);
+ analytics.identify({
+ user: "users/[email protected]",
+ workspace: "workspaces/acme",
+ });
+ analytics.captureMetric({
+ event: "connect database clicked",
+ properties: {
+ route_id: "workspace.project.database",
+ },
+ });
+
+ await init;
+
+ expect(client.capture).toHaveBeenCalledWith("connect database clicked", {
+ route_id: "workspace.project.database",
+ user: "users/[email protected]",
+ workspace: "workspaces/acme",
+ });
+ });
+
+ test("captures metrics without empty identity properties before identify", async () => {
+ const client = createClient();
+ const analytics = createBehaviorAnalytics(() => Promise.resolve(client));
+
+ await analytics.init(config);
+ analytics.captureMetric({
+ event: "connect database clicked",
+ properties: {
+ route_id: "workspace.project.database",
+ },
+ });
+
+ expect(client.capture.mock.calls[0]?.[1]).toStrictEqual({
+ route_id: "workspace.project.database",
+ });
+ });
+
+ test("adds global config properties to captured metrics", async () => {
+ const client = createClient();
+ const analytics = createBehaviorAnalytics(() => Promise.resolve(client));
+
+ await analytics.init(configWithProperties);
+ analytics.captureMetric({
+ event: "connect database clicked",
+ properties: {
+ route_id: "workspace.project.database",
+ },
+ });
+
+ expect(client.capture).toHaveBeenCalledWith("connect database clicked", {
+ git_commit: "abc123",
+ route_id: "workspace.project.database",
+ });
+ });
+
+ test("opts out and ignores identity and metrics while disabled", async () => {
+ const client = createClient();
+ const analytics = createBehaviorAnalytics(() => Promise.resolve(client));
+
+ await analytics.init(config);
+ analytics.disable();
+ analytics.identify({
+ user: "users/[email protected]",
+ workspace: "workspaces/acme",
+ });
+ analytics.captureMetric({
+ event: "connect database clicked",
+ properties: {
+ route_id: "workspace.project.database",
+ },
+ });
+
+ expect(client.stopSessionRecording).toHaveBeenCalledOnce();
+ expect(client.opt_out_capturing).toHaveBeenCalledOnce();
+ expect(client.reset).toHaveBeenCalledOnce();
+ expect(client.identify).not.toHaveBeenCalled();
+ expect(client.capture).not.toHaveBeenCalled();
+ });
+
+ test("drops pending metrics when disabled before async init completes", async () => {
+ const client = createClient();
+ const analytics = createBehaviorAnalytics(
+ () => new Promise((resolve) => setTimeout(() => resolve(client), 0))
+ );
+
+ const init = analytics.init(config);
+ analytics.captureMetric({
+ event: "connect database clicked",
+ properties: {
+ route_id: "workspace.project.database",
+ },
+ });
+ analytics.disable();
+
+ await init;
+
+ expect(client.init).not.toHaveBeenCalled();
+ expect(client.capture).not.toHaveBeenCalled();
+ });
+
+ test("restarts session recording when re-enabled after disable", async () => {
+ const client = createClient();
+ const analytics = createBehaviorAnalytics(() => Promise.resolve(client));
+
+ await analytics.init(config);
+ analytics.disable();
+ await analytics.init(config);
+
+ expect(client.opt_in_capturing).toHaveBeenCalledOnce();
+ expect(client.startSessionRecording).toHaveBeenCalledOnce();
+ });
+});
diff --git a/frontend/src/app/analytics/provider.ts b/frontend/src/app/analytics/provider.ts
new file mode 100644
index 0000000000..6ead62d1e1
--- /dev/null
+++ b/frontend/src/app/analytics/provider.ts
@@ -0,0 +1,133 @@
+import type { BehaviorAnalyticsConfig, BehaviorMetric } from "./behavior";
+
+type PostHogClient = {
+ init: (apiKey: string, options?: Record<string, unknown>) => void;
+ identify: (id: string, properties?: Record<string, unknown>) => void;
+ opt_in_capturing?: () => void;
+ opt_out_capturing?: () => void;
+ reset: () => void;
+ capture: (event: string, properties?: Record<string, unknown>) => void;
+ startSessionRecording?: () => void;
+ stopSessionRecording?: () => void;
+};
+
+type AnalyticsIdentity = {
+ user: string;
+ workspace: string;
+};
+
+type LoadPostHog = () => Promise<PostHogClient>;
+
+class BehaviorAnalytics {
+ private client: PostHogClient | undefined;
+ private configKey: string | undefined;
+ private properties: Record<string, unknown> = {};
+ private enabled = false;
+ private initialized = false;
+ private pendingIdentity: AnalyticsIdentity | undefined;
+ private pendingMetrics: BehaviorMetric[] = [];
+
+ constructor(private readonly loadClient: LoadPostHog) {}
+
+ async init(config: BehaviorAnalyticsConfig): Promise<void> {
+ this.enabled = true;
+ this.properties = config.properties ?? {};
+ if (this.initialized && this.configKey === config.apiKey) {
+ this.client?.opt_in_capturing?.();
+ this.client?.startSessionRecording?.();
+ return;
+ }
+ const posthog = await this.loadClient();
+ if (!this.enabled) {
+ return;
+ }
+ posthog.init(config.apiKey, config.options);
+ this.client = posthog;
+ this.configKey = config.apiKey;
+ this.initialized = true;
+ this.applyPendingIdentity();
+ this.flushPendingMetrics();
+ }
+
+ identify(identity: AnalyticsIdentity): void {
+ if (!this.enabled) {
+ return;
+ }
+ this.pendingIdentity = identity;
+ if (!this.client || !identity.user) {
+ return;
+ }
+ this.applyPendingIdentity();
+ }
+
+ reset(): void {
+ this.client?.reset();
+ this.pendingIdentity = undefined;
+ this.pendingMetrics = [];
+ }
+
+ disable(): void {
+ this.enabled = false;
+ this.pendingIdentity = undefined;
+ this.pendingMetrics = [];
+ this.client?.stopSessionRecording?.();
+ this.client?.opt_out_capturing?.();
+ this.client?.reset();
+ }
+
+ captureMetric(metric: BehaviorMetric): void {
+ if (!this.enabled) {
+ return;
+ }
+ if (!this.client) {
+ this.pendingMetrics.push(metric);
+ return;
+ }
+ this.captureMetricNow(metric);
+ }
+
+ private applyPendingIdentity(): void {
+ if (!this.client || !this.pendingIdentity?.user) {
+ return;
+ }
+ this.client.identify(this.pendingIdentity.user, {
+ user: this.pendingIdentity.user,
+ workspace: this.pendingIdentity.workspace,
+ });
+ }
+
+ private flushPendingMetrics(): void {
+ if (!this.client) {
+ return;
+ }
+ for (const metric of this.pendingMetrics) {
+ this.captureMetricNow(metric);
+ }
+ this.pendingMetrics = [];
+ }
+
+ private captureMetricNow(metric: BehaviorMetric): void {
+ if (!this.client) {
+ return;
+ }
+ const properties = { ...metric.properties, ...this.properties };
+ if (this.pendingIdentity) {
+ properties.user = this.pendingIdentity.user;
+ properties.workspace = this.pendingIdentity.workspace;
+ }
+ this.client.capture(metric.event, properties);
+ }
+}
+
+async function loadPostHog(): Promise<PostHogClient> {
+ const mod = (await import("posthog-js")) as unknown as {
+ default?: PostHogClient;
+ } & PostHogClient;
+ return mod.default ?? mod;
+}
+
+export function createBehaviorAnalytics(loadClient = loadPostHog) {
+ return new BehaviorAnalytics(loadClient);
+}
+
+export const behaviorAnalytics = createBehaviorAnalytics();
diff --git a/frontend/src/components/WorkspaceSetupGuide.test.tsx b/frontend/src/components/WorkspaceSetupGuide.test.tsx
index c456b1a8c3..bddacdd783 100644
--- a/frontend/src/components/WorkspaceSetupGuide.test.tsx
+++ b/frontend/src/components/WorkspaceSetupGuide.test.tsx
@@ -41,6 +41,7 @@ const mocks = vi.hoisted(() => ({
preCreateIssue: vi.fn(),
currentRoute: { name: "workspace.home" } as { name?: string },
routerPush: vi.fn(),
+ captureMetric: vi.fn(),
defaultProjectName: "projects/default",
}));
@@ -87,6 +88,12 @@ vi.mock("@/app/router", () => ({
useCurrentRoute: () => mocks.currentRoute,
}));
+vi.mock("@/app/analytics/provider", () => ({
+ behaviorAnalytics: {
+ captureMetric: mocks.captureMetric,
+ },
+}));
+
vi.mock("@/stores/app", () => {
const getState = () => ({
isSaaSMode: mocks.isSaaSMode,
@@ -360,6 +367,12 @@ describe("WorkspaceSetupGuide", () => {
key: dismissedIntroStateKey,
newState: true,
});
+ expect(mocks.captureMetric).toHaveBeenCalledWith({
+ event: "setup guide dismissed",
+ properties: {
+ step: "hasProject",
+ },
+ });
expect(mocks.introState[dismissedIntroStateKey]).toBe(true);
await render(<WorkspaceSetupGuide />);
@@ -367,6 +380,26 @@ describe("WorkspaceSetupGuide", () => {
expect(container.textContent).toBe("");
});
+ it("captures the selected setup guide action", async () => {
+ await render(<WorkspaceSetupGuide />);
+
+ const instanceStep = container.querySelector(
+ "[data-testid='setup-step-hasInstance']"
+ ) as HTMLButtonElement | null;
+
+ await act(async () => {
+ instanceStep?.click();
+ await Promise.resolve();
+ });
+
+ expect(mocks.captureMetric).toHaveBeenCalledWith({
+ event: "setup guide action clicked",
+ properties: {
+ step: "hasInstance",
+ },
+ });
+ });
+
it("stays hidden after it is dismissed", async () => {
mocks.introState[dismissedIntroStateKey] = true;
diff --git a/frontend/src/components/WorkspaceSetupGuide.tsx b/frontend/src/components/WorkspaceSetupGuide.tsx
index 1030f07c90..bda5aee992 100644
--- a/frontend/src/components/WorkspaceSetupGuide.tsx
+++ b/frontend/src/components/WorkspaceSetupGuide.tsx
@@ -3,6 +3,8 @@ import { CheckCircle, Circle, X } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { sqlServiceClientConnect } from "@/api";
+import { createBehaviorMetric } from "@/app/analytics/behavior";
+import { behaviorAnalytics } from "@/app/analytics/provider";
import { type RouteTarget, router, useCurrentRoute } from "@/app/router";
import {
DATABASE_ROUTE_DASHBOARD,
@@ -102,6 +104,13 @@ export function WorkspaceSetupGuide() {
}, [currentRoute.name]);
const onSelectStep = (step: SetupStep) => {
+ behaviorAnalytics.captureMetric(
+ createBehaviorMetric("setup guide action clicked", {
+ properties: {
+ step: step.key,
+ },
+ })
+ );
setSelectedStepKey(step.key);
if (step.link) {
void router.push(step.link);
@@ -311,10 +320,24 @@ export function WorkspaceSetupGuide() {
highlightedStep && !highlightedStep.done ? highlightedStep : activeStep;
const handleCreateFirstChange = () => {
+ behaviorAnalytics.captureMetric(
+ createBehaviorMetric("setup guide action clicked", {
+ properties: {
+ step: "createFirstChange",
+ },
+ })
+ );
void preCreateIssue(setupState.projectName, [setupState.databaseName]);
};
const handleDismiss = () => {
+ behaviorAnalytics.captureMetric(
+ createBehaviorMetric("setup guide dismissed", {
+ properties: {
+ step: actionStep.key,
+ },
+ })
+ );
useAppStore.getState().saveIntroStateByKey({
key: WORKSPACE_SETUP_GUIDE_DISMISSED_KEY,
newState: true,
diff --git a/frontend/src/components/instance/InstanceFormButtons.test.tsx b/frontend/src/components/instance/InstanceFormButtons.test.tsx
index 8a5a1ce845..c2a467afe7 100644
--- a/frontend/src/components/instance/InstanceFormButtons.test.tsx
+++ b/frontend/src/components/instance/InstanceFormButtons.test.tsx
@@ -16,12 +16,14 @@ import { InstanceFormButtons } from "./InstanceFormButtons";
).IS_REACT_ACT_ENVIRONMENT = true;
const mocks = vi.hoisted(() => ({
+ routerCurrentName: "workspace.instance.create",
routerCurrentQuery: {} as Record<string, unknown>,
routerPush: vi.fn(),
pushNotification: vi.fn(),
createInstance: vi.fn(),
fetchDatabases: vi.fn(),
batchUpdateDatabases: vi.fn(),
+ captureMetric: vi.fn(),
context: undefined as Record<string, unknown> | undefined,
}));
@@ -41,12 +43,21 @@ vi.mock("@/app/router", () => ({
push: mocks.routerPush,
currentRoute: {
get value() {
- return { query: mocks.routerCurrentQuery };
+ return {
+ name: mocks.routerCurrentName,
+ query: mocks.routerCurrentQuery,
+ };
},
},
},
}));
+vi.mock("@/app/analytics/provider", () => ({
+ behaviorAnalytics: {
+ captureMetric: mocks.captureMetric,
+ },
+}));
+
vi.mock("@/stores/app", () => {
const appState = {
hasFeature: () => true,
@@ -148,6 +159,7 @@ const flushPromises = async () => {
beforeEach(() => {
vi.clearAllMocks();
+ mocks.routerCurrentName = "workspace.instance.create";
mocks.routerCurrentQuery = {};
const adminDataSource = {
@@ -269,6 +281,75 @@ describe("InstanceFormButtons", () => {
},
});
expect(mocks.context?.onDismiss).not.toHaveBeenCalled();
+ expect(mocks.captureMetric).toHaveBeenCalledWith({
+ event: "instance create clicked",
+ properties: {
+ route_id: "workspace.instance.create",
+ resource: "projects/demo",
+ },
+ });
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+
+ test("captures standalone connection test clicks on instance edit", async () => {
+ mocks.routerCurrentName = "workspace.instance.detail";
+ const adminDataSource = create(DataSourceSchema, {
+ id: "admin",
+ type: DataSourceType.ADMIN,
+ host: "127.0.0.1",
+ port: "5432",
+ });
+ mocks.context = {
+ ...mocks.context,
+ instance: create(InstanceSchema, {
+ name: "instances/prod",
+ title: "Production",
+ engine: Engine.POSTGRES,
+ dataSources: [adminDataSource],
+ }),
+ isCreating: false,
+ adminDataSource: {
+ ...adminDataSource,
+ pendingCreate: false,
+ updatedPassword: "",
+ updatedMasterPassword: "",
+ updatedToken: "",
+ },
+ editingDataSource: {
+ ...adminDataSource,
+ pendingCreate: false,
+ updatedPassword: "",
+ updatedMasterPassword: "",
+ updatedToken: "",
+ },
+ valueChanged: true,
+ };
+ const container = document.createElement("div");
+ const root = createRoot(container);
+
+ await act(async () => {
+ root.render(<InstanceFormButtons />);
+ });
+
+ const testConnectionButton = Array.from(
+ container.querySelectorAll("button")
+ ).find((button) =>
+ button.textContent?.includes("instance.test-connection")
+ ) as HTMLButtonElement;
+ await act(async () => {
+ testConnectionButton.click();
+ await flushPromises();
+ });
+
+ expect(mocks.captureMetric).toHaveBeenCalledWith({
+ event: "instance connection test clicked",
+ properties: {
+ route_id: "workspace.instance.detail",
+ },
+ });
await act(async () => {
root.unmount();
diff --git a/frontend/src/components/instance/InstanceFormButtons.tsx b/frontend/src/components/instance/InstanceFormButtons.tsx
index 706ccc5d01..0b6982b849 100644
--- a/frontend/src/components/instance/InstanceFormButtons.tsx
+++ b/frontend/src/components/instance/InstanceFormButtons.tsx
@@ -2,6 +2,8 @@ import { create } from "@bufbuild/protobuf";
import { cloneDeep, isEqual } from "lodash-es";
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
+import { createBehaviorMetric } from "@/app/analytics/behavior";
+import { behaviorAnalytics } from "@/app/analytics/provider";
import { router } from "@/app/router";
import {
INSTANCE_ROUTE_DETAIL,
@@ -307,6 +309,13 @@ export function InstanceFormButtons({
};
const tryCreate = async () => {
+ behaviorAnalytics.captureMetric(
+ createBehaviorMetric("instance create clicked", {
+ routeId: router.currentRoute.value.name?.toString(),
+ resource: projectContext?.name,
+ })
+ );
+
const editingDS = adminDataSource;
const testResult = await testConnection(editingDS, true);
if (testResult.success) {
@@ -521,6 +530,12 @@ export function InstanceFormButtons({
const testConnectionForCurrentEditingDS = async () => {
if (!editingDataSource) return;
+ behaviorAnalytics.captureMetric(
+ createBehaviorMetric("instance connection test clicked", {
+ routeId: router.currentRoute.value.name?.toString(),
+ })
+ );
+
const testResult = await testConnection(editingDataSource, false);
if (!testResult.success) {
maybeOpenConnectionOptions(editingDataSource);
diff --git a/frontend/src/modules/sql-editor/components/ResultPanel/ResultPanel.tsx b/frontend/src/modules/sql-editor/components/ResultPanel/ResultPanel.tsx
index bf693c996a..80c866b8aa 100644
--- a/frontend/src/modules/sql-editor/components/ResultPanel/ResultPanel.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultPanel/ResultPanel.tsx
@@ -172,7 +172,11 @@ export function ResultPanel() {
// (`TabsTrigger` does, our `Tooltip` wrapper doesn't). With
// Tooltip on the outside, the trigger renders `TabsTrigger`
// directly and the right-click handler reaches the DOM.
- <Tooltip key={context.id} content={context.params.statement}>
+ <Tooltip
+ key={context.id}
+ content={context.params.statement}
+ popupClassName="ph-no-capture"
+ >
<TabContextMenu
onSelect={(action) => {
switch (action) {
diff --git a/frontend/src/modules/sql-editor/components/ResultView/ResultView.test.tsx b/frontend/src/modules/sql-editor/components/ResultView/ResultView.test.tsx
new file mode 100644
index 0000000000..82efb3e781
--- /dev/null
+++ b/frontend/src/modules/sql-editor/components/ResultView/ResultView.test.tsx
@@ -0,0 +1,117 @@
+import { render } from "@testing-library/react";
+import { describe, expect, test, vi } from "vitest";
+import type { SQLEditorQueryParams } from "@/types";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import type { Database } from "@/types/proto-es/v1/database_service_pb";
+import { ResultView } from "./ResultView";
+
+vi.mock("react-i18next", () => ({
+ initReactI18next: {
+ init: vi.fn(),
+ type: "3rdParty",
+ },
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/components/DataExportButton", () => ({
+ DataExportButton: () => null,
+}));
+
+vi.mock("@/modules/sql-editor/components/RequestExportButton", () => ({
+ RequestExportButton: () => null,
+}));
+
+vi.mock("@/modules/sql-editor/components/RequestQueryButton", () => ({
+ RequestQueryButton: () => null,
+}));
+
+vi.mock("@/modules/sql-editor/components/useExportGrantBypass", () => ({
+ useExportGrantBypass: () => ({
+ grantName: undefined,
+ tooltip: undefined,
+ }),
+}));
+
+vi.mock("@/modules/sql-editor/hooks/useSQLEditorState", () => ({
+ useSQLEditorQueryDataPolicy: () => undefined,
+}));
+
+vi.mock("@/modules/sql-editor/store/editor", () => ({
+ useSQLEditorEditorState: (
+ selector: (state: { project: string }) => unknown
+ ) => selector({ project: "projects/prod" }),
+ useSQLEditorEditorStore: {},
+}));
+
+vi.mock("@/modules/sql-editor/store/tab", () => ({
+ getSQLEditorTabsState: () => ({
+ currentTabId: "",
+ tabsById: new Map(),
+ }),
+ useSQLEditorTabsStore: {},
+}));
+
+vi.mock("@/stores/app", () => {
+ const state = {
+ exportData: vi.fn(),
+ getOrFetchDatabaseMetadata: vi.fn(),
+ getOrFetchPolicyByParentAndType: vi.fn(),
+ getQueryDataPolicyByParent: vi.fn(),
+ notify: vi.fn(),
+ syncDatabase: vi.fn(),
+ };
+ return {
+ useAppStore: Object.assign(
+ (selector: (value: typeof state) => unknown) => selector(state),
+ { getState: () => state }
+ ),
+ };
+});
+
+vi.mock("@/utils/iam/permission", () => ({
+ hasProjectPermissionV2: () => false,
+}));
+
+vi.mock("@/utils/v1/database", () => ({
+ extractDatabaseResourceName: () => ({ databaseName: "main" }),
+ getDatabaseProject: () => "projects/prod",
+}));
+
+vi.mock("./EmptyView", () => ({
+ EmptyView: () => <div data-testid="empty-view" />,
+}));
+
+vi.mock("./ErrorView", () => ({
+ ErrorView: () => <div data-testid="error-view" />,
+}));
+
+vi.mock("./SingleResultView", () => ({
+ SingleResultView: () => <div data-testid="single-result-view" />,
+}));
+
+const executeParams: SQLEditorQueryParams = {
+ connection: {
+ database: "instances/prod/databases/main",
+ instance: "instances/prod",
+ },
+ engine: Engine.POSTGRES,
+ explain: false,
+ selection: null,
+ statement: "select secret from customer",
+};
+
+const database = {
+ effectiveEnvironment: "environments/prod",
+ name: "instances/prod/databases/main",
+ project: "projects/prod",
+} as Database;
+
+describe("ResultView", () => {
+ test("blocks analytics recording for query results", () => {
+ const { container } = render(
+ <ResultView executeParams={executeParams} database={database} />
+ );
+
+ expect(container.firstElementChild).toHaveClass("ph-no-capture");
+ });
+});
diff --git a/frontend/src/modules/sql-editor/components/ResultView/ResultView.tsx b/frontend/src/modules/sql-editor/components/ResultView/ResultView.tsx
index 6a8e9c3e22..1c85252d0d 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/ResultView.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/ResultView.tsx
@@ -234,7 +234,7 @@ export function ResultView({
<div
className={cn(
"relative flex flex-col justify-start items-start pb-1 overflow-y-auto h-full w-full",
- "bg-background"
+ "bg-background ph-no-capture"
)}
>
{executeParams && resultSet && !showPlaceholder && (
@@ -272,7 +272,11 @@ export function ResultView({
<div className="flex items-center justify-between gap-x-2">
<TabsList>
{filteredResults.map((result, i) => (
- <Tooltip key={i} content={result.statement}>
+ <Tooltip
+ key={i}
+ content={result.statement}
+ popupClassName="ph-no-capture"
+ >
<TabsTrigger value={tabName(i)}>
<div className="flex items-center gap-x-2 mb-1">
<span>{tabName(i)}</span>
diff --git a/frontend/src/routes/project/ProjectDatabasesPage.test.tsx b/frontend/src/routes/project/ProjectDatabasesPage.test.tsx
index 7d7699e736..e15a4fe422 100644
--- a/frontend/src/routes/project/ProjectDatabasesPage.test.tsx
+++ b/frontend/src/routes/project/ProjectDatabasesPage.test.tsx
@@ -11,9 +11,11 @@ const mocks = vi.hoisted(() => ({
visibleDatabases: [] as { name: string }[],
databasesByName: {} as Record<string, { name: string }>,
instancesByName: {} as Record<string, { name: string; title: string }>,
+ routerCurrentName: "workspace.project.database",
routerCurrentQuery: {} as Record<string, unknown>,
routerPush: vi.fn(),
useProductIntro: vi.fn(),
+ captureMetric: vi.fn(),
removeDatabaseMetadataCache: vi.fn(),
fetchInstance: vi.fn(),
fetchInstanceList: vi.fn(async () => ({
@@ -53,12 +55,21 @@ vi.mock("@/app/router", () => ({
resolve: ({ name }: { name?: string }) => ({ href: `/${name ?? ""}` }),
currentRoute: {
get value() {
- return { query: mocks.routerCurrentQuery };
+ return {
+ name: mocks.routerCurrentName,
+ query: mocks.routerCurrentQuery,
+ };
},
},
},
}));
+vi.mock("@/app/analytics/provider", () => ({
+ behaviorAnalytics: {
+ captureMetric: mocks.captureMetric,
+ },
+}));
+
vi.mock("@/components/AdvancedSearch", () => ({
AdvancedSearch: () => <div data-testid="advanced-search" />,
getValueFromScopes: () => undefined,
@@ -217,6 +228,7 @@ beforeEach(async () => {
mocks.visibleDatabases = [];
mocks.databasesByName = {};
mocks.instancesByName = {};
+ mocks.routerCurrentName = "workspace.project.database";
mocks.routerCurrentQuery = {};
mocks.workspacePermissions = new Set([
"bb.instances.create",
@@ -292,6 +304,13 @@ describe("ProjectDatabasesPage", () => {
name: "workspace.instance.create",
query: { project: "demo" },
});
+ expect(mocks.captureMetric).toHaveBeenCalledWith({
+ event: "connect database clicked",
+ properties: {
+ route_id: "workspace.project.database",
+ resource: "projects/demo",
+ },
+ });
act(() => {
root.unmount();
diff --git a/frontend/src/routes/project/ProjectDatabasesPage.tsx b/frontend/src/routes/project/ProjectDatabasesPage.tsx
index a97e2f10af..740831b5a9 100644
--- a/frontend/src/routes/project/ProjectDatabasesPage.tsx
+++ b/frontend/src/routes/project/ProjectDatabasesPage.tsx
@@ -3,6 +3,8 @@ import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
import { Plus, SquareTerminal } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Trans, useTranslation } from "react-i18next";
+import { createBehaviorMetric } from "@/app/analytics/behavior";
+import { behaviorAnalytics } from "@/app/analytics/provider";
import { router } from "@/app/router";
import {
INSTANCE_ROUTE_CREATE,
@@ -510,12 +512,24 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
const handleCreateFirstChange = useCallback(() => {
const firstDatabase = visibleDatabases[0];
if (!firstDatabase) return;
+ behaviorAnalytics.captureMetric(
+ createBehaviorMetric("post sync first change clicked", {
+ routeId: router.currentRoute.value.name?.toString(),
+ resource: projectName,
+ })
+ );
preCreateIssue(projectName, [firstDatabase.name]);
}, [projectName, visibleDatabases]);
const handleOpenFirstDatabaseInSQLEditor = useCallback(() => {
const firstDatabase = visibleDatabases[0];
if (!firstDatabase) return;
+ behaviorAnalytics.captureMetric(
+ createBehaviorMetric("post sync sql editor clicked", {
+ routeId: router.currentRoute.value.name?.toString(),
+ resource: projectName,
+ })
+ );
const { instanceName, databaseName } = extractDatabaseResourceName(
firstDatabase.name
);
@@ -527,7 +541,7 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
database: databaseName,
},
});
- }, [projectId, visibleDatabases]);
+ }, [projectId, projectName, visibleDatabases]);
useProductIntro({
id: CONNECT_DATABASE_PRODUCT_INTRO,
@@ -550,6 +564,12 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
if (checkingWorkspaceInstance) return;
if (emptyProjectShouldConnectInstance) {
if (!hasWorkspacePermissionV2("bb.instances.create")) return;
+ behaviorAnalytics.captureMetric(
+ createBehaviorMetric("connect database clicked", {
+ routeId: router.currentRoute.value.name?.toString(),
+ resource: projectName,
+ })
+ );
router.push({
name: INSTANCE_ROUTE_CREATE,
query: { project: projectId },
@@ -557,7 +577,12 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
return;
}
setShowCreateDrawer(true);
- }, [checkingWorkspaceInstance, emptyProjectShouldConnectInstance, projectId]);
+ }, [
+ checkingWorkspaceInstance,
+ emptyProjectShouldConnectInstance,
+ projectId,
+ projectName,
+ ]);
return (
<ProjectPageLayout>