diff --git a/doc/cloud-browser-analytics.md b/doc/cloud-browser-analytics.md index 4bd172a0dc5..14c0d081fdf 100644 --- a/doc/cloud-browser-analytics.md +++ b/doc/cloud-browser-analytics.md @@ -237,11 +237,14 @@ This value is used only for location, never for limits. The in-workspace onboarding wizard (`ui/src/components/OnboardingWizard.tsx`) captures four browser events through `ui/src/lib/analytics/onboarding-analytics.ts`. -They follow the same consent rules as every other browser event: without a -browser analytics config or with consent not granted, nothing is captured. -Events from before posthog-js loads wait in a short queue (at most 50) and keep -their original time. Withdrawing consent or a change of signed-in person drops -the queue. +Without a browser analytics config or after consent is declined, these events +are discarded. While the choice is pending, events wait only in page memory +in a bounded queue (at most 50); PostHog does not load and nothing is sent. +Accepting consent flushes that queue after PostHog loads, preserving event +order and original timestamps. This also covers events emitted after consent +while posthog-js is still loading. Declining consent or changing the signed-in +person drops the queue. Reloading the page loses pending events; they are +never persisted in browser storage. | Event | When | Properties | | --- | --- | --- | diff --git a/tests/runner-e2e/chat-catalog-domains/identity-new-company-native.test.ts b/tests/runner-e2e/chat-catalog-domains/identity-new-company-native.test.ts index 8b13339c9ea..386f8eb8b8d 100644 --- a/tests/runner-e2e/chat-catalog-domains/identity-new-company-native.test.ts +++ b/tests/runner-e2e/chat-catalog-domains/identity-new-company-native.test.ts @@ -97,9 +97,8 @@ describe("actual supported route and provider contracts", () => { expect(aiRoutingModel(routing, "opencode_local", NEW_COMPANY_NATIVE_MODEL)).toBe(NEW_COMPANY_NATIVE_MODEL); expect(createAiConnectionSchema.parse({ provider: "openrouter", method: "api_key", name: "My OpenRouter", ownership: "personal", allAgents: false, agentIds: [agentId], routing, apiKey: "synthetic-private-key" })).toMatchObject({ ownership: "personal", agentIds: [agentId], allAgents: false }); }); - it("binds the original production UI draft gate and public first-agent hold/reuse", () => { + it("binds public first-agent hold/reuse", () => { const source = (file: string) => readFileSync(new URL(`../../../${file}`, import.meta.url), "utf8"); - expect(source("ui/src/components/OnboardingWizard.tsx")).toContain('const setupSnapshot = step === 4'); expect(source("ui/src/context/DialogContext.tsx")).toContain('const [onboardingOpen, setOnboardingOpen] = useState(false)'); expect(source("ui/src/components/new-agent/AgentBasicsDialog.tsx")).toContain('role: existing.length ? "general" : "ceo"'); expect(source("ui/src/components/new-agent/AgentBasicsDialog.tsx")).toContain('buildNewAgentRuntimeConfig({ heartbeatEnabled: false })'); diff --git a/ui/src/components/ProductAnalyticsGate.test.tsx b/ui/src/components/ProductAnalyticsGate.test.tsx index 892919c2701..ca3f094770a 100644 --- a/ui/src/components/ProductAnalyticsGate.test.tsx +++ b/ui/src/components/ProductAnalyticsGate.test.tsx @@ -4,7 +4,7 @@ import { act } from "react"; import { createRoot } from "react-dom/client"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { resetProductAnalyticsForTest } from "@/lib/analytics/product-analytics"; +import { captureProductAnalyticsEvent, resetProductAnalyticsForTest } from "@/lib/analytics/product-analytics"; import { ANALYTICS_CONSENT_STORAGE_KEY, resetAnalyticsConsentForTest, @@ -20,6 +20,7 @@ const posthogMock = vi.hoisted(() => ({ identify: vi.fn(), group: vi.fn(), reset: vi.fn(), + capture: vi.fn(), opt_out_capturing: vi.fn(), opt_in_capturing: vi.fn(), has_opted_out_capturing: vi.fn(() => false), @@ -185,6 +186,28 @@ describe("ProductAnalyticsGate", () => { act(() => root.unmount()); }); + it("sends events from before Accept once, in order and with their original timestamps", async () => { + getSessionMock.mockResolvedValue(session(analyticsConfig({ consentRequired: true }))); + const root = await renderGate(); + const openedAt = new Date(); + captureProductAnalyticsEvent("onboarding_opened", { step: "create_agent" }); + await act(async () => { await vi.advanceTimersByTimeAsync(1_000); }); + const completedAt = new Date(); + captureProductAnalyticsEvent("onboarding_step_completed", { step: "create_agent" }); + expect(injectedScripts()).toHaveLength(0); + expect(posthogMock.capture).not.toHaveBeenCalled(); + + await act(async () => { bannerButton("Accept").click(); }); + + expect(posthogMock.capture.mock.calls).toEqual([ + ["onboarding_opened", { step: "create_agent" }, { timestamp: openedAt }], + ["onboarding_step_completed", { step: "create_agent" }, { timestamp: completedAt }], + ]); + await settle(); + expect(posthogMock.capture).toHaveBeenCalledTimes(2); + act(() => root.unmount()); + }); + it("keeps analytics off when the visitor declines", async () => { getSessionMock.mockResolvedValue(session(analyticsConfig({ consentRequired: true }))); const root = await renderGate(); diff --git a/ui/src/lib/analytics/onboarding-analytics.test.tsx b/ui/src/lib/analytics/onboarding-analytics.test.tsx index 441ab949d93..8e5b1084f17 100644 --- a/ui/src/lib/analytics/onboarding-analytics.test.tsx +++ b/ui/src/lib/analytics/onboarding-analytics.test.tsx @@ -130,6 +130,43 @@ describe("browser product events", () => { ); }); + it("discards pending events on Decline and ignores events until a later Accept", async () => { + syncProductAnalytics(config, "ask", { load, schedule }); + captureProductAnalyticsEvent("onboarding_opened", { step: "create_agent" }); + syncProductAnalytics(config, "denied", { load, schedule }); + captureProductAnalyticsEvent("onboarding_step_completed", { step: "create_agent" }); + await startAnalytics(); + expect(client.capture).not.toHaveBeenCalled(); + captureProductAnalyticsEvent("onboarding_opened", { step: "connect_model" }); + expect(captured()).toEqual([["onboarding_opened", { step: "connect_model" }]]); + }); + + it("bounds the pending-consent queue to 50 events", async () => { + syncProductAnalytics(config, "ask", { load, schedule }); + for (let index = 0; index < 50; index++) { + captureProductAnalyticsEvent("onboarding_step_viewed", { step: "create_agent" }); + } + captureProductAnalyticsEvent("onboarding_step_viewed", { step: "review" }); + await startAnalytics(); + expect(client.capture).toHaveBeenCalledTimes(50); + expect(captured()).not.toContainEqual(["onboarding_step_viewed", { step: "review" }]); + }); + + it("queues while consent is pending again after the client has initialized", async () => { + setProductAnalyticsUser({ id: "user-1", email: null, name: null }); + await startAnalytics(); + syncProductAnalytics(config, "ask", { load, schedule }); + captureProductAnalyticsEvent("onboarding_opened", { step: "create_agent" }); + expect(client.capture).not.toHaveBeenCalled(); + setProductAnalyticsUser({ id: "user-2", email: null, name: null }); + expect(client.identify).toHaveBeenCalledTimes(1); + captureProductAnalyticsEvent("onboarding_opened", { step: "connect_model" }); + await startAnalytics(); + expect(captured()).toEqual([["onboarding_opened", { step: "connect_model" }]]); + expect(client.identify).toHaveBeenLastCalledWith("user-2", {}); + expect(client.init).toHaveBeenCalledTimes(1); + }); + it("drops held events when consent is withdrawn before posthog-js loads", async () => { syncProductAnalytics(config, "granted", { load, schedule }); captureProductAnalyticsEvent("onboarding_opened", { step: "create_agent" }); @@ -140,13 +177,14 @@ describe("browser product events", () => { expect(client.capture).not.toHaveBeenCalled(); }); - it("drops held events when the signed-in person changes before posthog-js loads", async () => { + it.each(["granted", "ask"] as const)("drops held events on a person change while consent is %s", async (consent) => { setProductAnalyticsUser({ id: "user-1", email: null, name: null }); - syncProductAnalytics(config, "granted", { load, schedule }); + syncProductAnalytics(config, consent, { load, schedule }); captureProductAnalyticsEvent("onboarding_opened", { step: "create_agent" }); setProductAnalyticsUser(null); setProductAnalyticsUser({ id: "user-2", email: null, name: null }); captureProductAnalyticsEvent("onboarding_opened", { step: "connect_model" }); + syncProductAnalytics(config, "granted", { load, schedule }); scheduled!(); await flush(); expect(captured()).toEqual([["onboarding_opened", { step: "connect_model" }]]); @@ -256,13 +294,24 @@ describe("onboarding funnel events", () => { ]); }); - it("captures nothing in the wizard when consent is not granted", async () => { + it("sends queued wizard events after consent without reopening the wizard", async () => { syncProductAnalytics(config, "ask", { load, schedule, immediate: true }); const wizard = renderWizard({ open: true, step: 3 }); act(() => wizard.result.current.opened(3, 3)); wizard.rerender({ open: true, step: 4, connectOutcome: "subscription" }); act(() => wizard.result.current.dismissed(4)); expect(client.capture).not.toHaveBeenCalled(); + expect(client.init).not.toHaveBeenCalled(); + expect(scheduled).toBeNull(); + + await startAnalytics(); + expect(captured()).toEqual([ + ["onboarding_opened", { step: "create_agent" }], + ["onboarding_step_viewed", { step: "create_agent" }], + ["onboarding_step_completed", { step: "create_agent" }], + ["onboarding_step_viewed", { step: "connect_model" }], + ["onboarding_dismissed", { step: "connect_model" }], + ]); }); it("captures structured onboarding failures and drops unsafe provider strings", async () => { diff --git a/ui/src/lib/analytics/product-analytics.ts b/ui/src/lib/analytics/product-analytics.ts index 4bc24f9faa3..d1c414099a0 100644 --- a/ui/src/lib/analytics/product-analytics.ts +++ b/ui/src/lib/analytics/product-analytics.ts @@ -23,6 +23,7 @@ // be captured here; `product-analytics-events.test.ts` enforces that. import type { BrowserAnalyticsConfig } from "@paperclipai/shared"; +import type { AnalyticsConsent } from "./consent"; import { ANALYTICS_MASK_TEXT_SELECTOR, ANALYTICS_NO_CAPTURE_CLASS, @@ -220,7 +221,7 @@ type State = { cancelSchedule: (() => void) | null; pendingClient: ProductAnalyticsClient | null; loading: boolean; - optedOut: boolean; + consent: AnalyticsConsent; queued: QueuedProductEvent[]; }; @@ -236,6 +237,18 @@ let state: State | null = null; let wantedUser: ProductAnalyticsUser | null = null; let identifiedUserId: string | null = null; +function createAnalyticsState(config: BrowserAnalyticsConfig, consent: AnalyticsConsent): State { + return { + config, + client: null, + pendingClient: null, + cancelSchedule: null, + loading: false, + consent, + queued: [], + }; +} + function applyIdentity(client: ProductAnalyticsClient, config: BrowserAnalyticsConfig) { const user = wantedUser; if (user) { @@ -268,9 +281,9 @@ function sendProductEvent(client: ProductAnalyticsClient, queued: QueuedProductE export function captureProductAnalyticsEvent(event: string, properties: Record = {}): void { const current = state; - if (!current || current.optedOut) return; + if (!current || current.consent === "denied") return; const queued = { event, properties: { ...properties }, timestamp: new Date() }; - if (current.client) { + if (current.client && current.consent === "granted") { sendProductEvent(current.client, queued); return; } @@ -287,6 +300,12 @@ function optIn(client: ProductAnalyticsClient, config: BrowserAnalyticsConfig) { if (config.replayEnabled) client.startSessionRecording?.(); } +function flushQueuedProductEvents(current: State, client: ProductAnalyticsClient) { + const queued = current.queued; + current.queued = []; + for (const event of queued) sendProductEvent(client, event); +} + function initialize(current: State, client: ProductAnalyticsClient) { const { config } = current; client.init(config.token, buildPostHogInitOptions(config, window.location.hostname)); @@ -294,9 +313,7 @@ function initialize(current: State, client: ProductAnalyticsClient) { client.register(superProperties(config)); current.client = client; applyIdentity(client, config); - const queued = current.queued; - current.queued = []; - for (const event of queued) sendProductEvent(client, event); + flushQueuedProductEvents(current, client); } /** @@ -308,28 +325,23 @@ export function startProductAnalytics( config: BrowserAnalyticsConfig, options: ProductAnalyticsOptions, ): void { - if (state) { - if (!state.optedOut) return; - state.optedOut = false; - if (state.client) { - optIn(state.client, state.config); - } else if (state.pendingClient) { - const client = state.pendingClient; - state.pendingClient = null; - initialize(state, client); - } + if (state?.consent === "granted") return; + const current = state ?? createAnalyticsState(config, "granted"); + state = current; + current.consent = "granted"; + if (current.client) { + optIn(current.client, current.config); + applyIdentity(current.client, current.config); + flushQueuedProductEvents(current, current.client); return; } - const current: State = { - config, - client: null, - pendingClient: null, - cancelSchedule: null, - loading: false, - optedOut: false, - queued: [], - }; - state = current; + if (current.pendingClient) { + const client = current.pendingClient; + current.pendingClient = null; + initialize(current, client); + return; + } + if (current.loading) return; const load = options.load ?? loadPostHog; current.cancelSchedule = options.schedule(() => { // The scheduler may call back more than once (settled page, deadline). @@ -338,10 +350,10 @@ export function startProductAnalytics( cancel?.(); if (state !== current || current.loading) return; current.loading = true; - load(config) + load(current.config) .then((client) => { if (state !== current) return; - if (current.optedOut) current.pendingClient = client; + if (current.consent !== "granted") current.pendingClient = client; else initialize(current, client); }) .catch(() => { @@ -356,7 +368,7 @@ export function startProductAnalytics( export function setProductAnalyticsUser(user: ProductAnalyticsUser | null): void { if (wantedUser && wantedUser.id !== user?.id && state) state.queued = []; wantedUser = user; - if (state?.client) applyIdentity(state.client, state.config); + if (state?.client && state.consent === "granted") applyIdentity(state.client, state.config); } /** @@ -379,25 +391,24 @@ export function cancelPendingProductAnalytics(): void { state = null; } -function stopProductAnalytics(): void { +function stopProductAnalytics(consent: "ask" | "denied"): void { if (!state) return; - if (!state.client && !state.pendingClient && !state.loading) { - state.cancelSchedule?.(); - state = null; - return; - } - state.optedOut = true; - state.queued = []; - if (state.client) optOut(state.client); + state.cancelSchedule?.(); + state.cancelSchedule = null; + const wasGranted = state.consent === "granted"; + state.consent = consent; + if (consent === "denied") state.queued = []; + if (state.client && wasGranted) optOut(state.client); } export function syncProductAnalytics( config: BrowserAnalyticsConfig, - consent: "granted" | "denied" | "ask", + consent: AnalyticsConsent, options: ProductAnalyticsOptions & { immediate?: boolean }, ): () => void { if (consent !== "granted") { - stopProductAnalytics(); + if (!state && consent === "ask") state = createAnalyticsState(config, consent); + stopProductAnalytics(consent); return () => undefined; } const schedule: ProductAnalyticsOptions["schedule"] = options.immediate