diff --git a/doc/cloud-browser-analytics.md b/doc/cloud-browser-analytics.md index 14c0d081fdf..9fc8e3f7bed 100644 --- a/doc/cloud-browser-analytics.md +++ b/doc/cloud-browser-analytics.md @@ -33,7 +33,6 @@ extensions posthog-js loads at run time (recorder, web vitals). | `PAPERCLIP_POSTHOG_REPLAY_ENABLED` | on (when browser analytics is on) | `0` turns session replay off for this stack and keeps the other browser analytics. | | `PAPERCLIP_POSTHOG_PROXY_MAX_IN_FLIGHT` | `1024` | Proxy requests in flight for the whole server. See [Proxy limits](#proxy-limits). | | `PAPERCLIP_POSTHOG_PROXY_MAX_IN_FLIGHT_PER_CLIENT` | `128` | Proxy requests in flight from one public client address. See [Proxy limits](#proxy-limits). | -| `PAPERCLIP_POSTHOG_COUNTRY_HEADER` | — | Name of a request header that the platform edge sets to the visitor's two-letter country code (for example `CF-IPCountry` behind a proxied Cloudflare zone). Leave it unset unless the edge sets the header and drops a value from the client. See [Consent](#consent). | ### Per-stack opt-out @@ -44,70 +43,12 @@ effect on the next server restart. ## Consent -Visitors in the EU, the EEA, the UK and Switzerland must agree before browser -analytics and session replay start. Everyone else keeps analytics on by -default. Both can change the choice later. Server events are not affected: -they set no cookies. - -### Who must agree - -1. The server decides when it knows the visitor's country. If - `PAPERCLIP_POSTHOG_COUNTRY_HEADER` names a header and the request carries a - valid two-letter code in it, `browserAnalytics.consentRequired` is `true` - for the EU and EEA countries (and their outermost regions and Svalbard), the - UK (and the Crown Dependencies and Gibraltar) and Switzerland, and `false` - for every other ISO 3166-1 alpha-2 country. The aliases `UK` and `EL` count - as `GB` and `GR`, and `EU` and `EZ` count as consent required. Any other - value (for example `XX`, `UN`, `XK` or `T1`) gives `null`. -2. Otherwise `consentRequired` is `null`, and the browser decides from its time - zone. It asks when the zone starts with - `Europe/`, is an EU, EEA or UK zone outside Europe (for example - `Atlantic/Canary`, `Atlantic/Reykjavik`, `Asia/Nicosia`, `Indian/Reunion`), - or is unknown (`UTC`, `Etc/*`, empty, or `Intl` fails). When unsure, it asks. - -Both lists live in one place, `packages/shared/src/analytics-consent.ts` -(`countryRequiresAnalyticsConsent`, `timeZoneRequiresAnalyticsConsent`). The -browser's choice logic is in `ui/src/lib/analytics/consent.ts`. - -Paperclip Cloud uses the time zone today. Requests reach Railway through -DNS-only Cloudflare records, so no Cloudflare country header arrives, and the -Railway edge adds no country header. Set `PAPERCLIP_POSTHOG_COUNTRY_HEADER` -only when an edge that sets and overwrites a country header is in front of -the stack. A visitor who forges the header can only change the default for -their own browser. - -### What happens - -| Visitor | Before a choice | Accept / switch on | Decline / switch off | -| --- | --- | --- | --- | -| Must agree, no Do Not Track or Global Privacy Control | Banner. posthog-js does not load: no `/_ph` requests, no PostHog cookies or storage. | posthog-js loads at once, without a reload. | Nothing loads. | -| Must agree, `navigator.doNotTrack === "1"` or `navigator.globalPrivacyControl === true` | No banner. Counts as Decline, also over a stored Accept. | Not possible: the settings switch is off and disabled, and says why. | Nothing loads. A running client opts out. | -| Everyone else | Loads after the page settles, as before. | — | `opt_out_capturing()` and `stopSessionRecording()` run at once. After the next load, posthog-js does not load. | - -The gate calls one function, `syncProductAnalytics(config, consent)` in -`ui/src/lib/analytics/product-analytics.ts`. It starts, opts in, opts out or -cancels. Analytics stops whenever the choice is not `granted`, also when it goes back -to "ask" (another tab removes the stored choice, or a session refresh changes -`consentRequired` to `true`). If the choice changes while posthog-js is still -downloading, `init()` does not run until the choice is `granted` again. - -The banner sits at the bottom of the page and does not block the board. It -says that recordings hide what the visitor types and their messages, -documents and connected accounts, but can show page names such as task -titles. It links to the privacy policy (https://paperclip.ing/privacy/). - -### Where the choice is kept - -The choice is per browser, in `localStorage` under -`paperclip.analyticsConsent` (`granted` or `denied`). The latest choice on -the page wins, also when storage rejects the write; it then lasts for the open -page only. Each user can change it in -**Settings → Profile → Product analytics**. The switch shows only when browser -analytics is on for the instance. Turning it on after an earlier opt-out also -clears the PostHog opt-out (`opt_in_capturing()`). - -To reset the choice and see the banner again, remove the key in the browser -console: `localStorage.removeItem("paperclip.analyticsConsent")`, then reload. +The per-browser EU/UK/Swiss consent banner and Profile opt-out switch are +disabled during private beta. When `PAPERCLIP_POSTHOG_BROWSER_ENABLED=1` is set +for a Cloud stack, `ProductAnalyticsGate` loads posthog-js after the page +settles without prompting, and clears any earlier PostHog opt-out flag on +initialization. `browserAnalytics.consentRequired` is always returned as +`false`. ## Reverse proxy @@ -237,14 +178,12 @@ 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`. -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. +Without a browser analytics config, these events are discarded. While +posthog-js is still loading, events wait only in page memory in a bounded +queue (at most 50) and flush once posthog-js initializes, preserving event +order and original timestamps. 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/server/src/__tests__/auth-routes.test.ts b/server/src/__tests__/auth-routes.test.ts index 67b3392bd6e..4fbdf659bb2 100644 --- a/server/src/__tests__/auth-routes.test.ts +++ b/server/src/__tests__/auth-routes.test.ts @@ -131,13 +131,13 @@ describe("auth routes", () => { environment: "staging", stackId: "stack-1", replayEnabled: true, - consentRequired: null, + consentRequired: false, cloudTrialInferenceEnabled: false, }); vi.stubEnv("PAPERCLIP_POSTHOG_COUNTRY_HEADER", "cf-ipcountry"); const eu = await request(createApp(actor, baseUser)).get("/api/auth/get-session").set("CF-IPCountry", "FR"); - expect(eu.body.browserAnalytics.consentRequired).toBe(true); + expect(eu.body.browserAnalytics.consentRequired).toBe(false); const us = await request(createApp(actor, baseUser)).get("/api/auth/get-session").set("CF-IPCountry", "US"); expect(us.body.browserAnalytics.consentRequired).toBe(false); }); diff --git a/server/src/__tests__/cloud-posthog-browser.test.ts b/server/src/__tests__/cloud-posthog-browser.test.ts index 32ee3321248..711d778ef6c 100644 --- a/server/src/__tests__/cloud-posthog-browser.test.ts +++ b/server/src/__tests__/cloud-posthog-browser.test.ts @@ -49,23 +49,20 @@ describe("browser analytics config exposure", () => { environment: "production", stackId: "stack-1", replayEnabled, - consentRequired: null, + consentRequired: false, cloudTrialInferenceEnabled: false, }); }); - it("decides consent from the configured edge country header, and leaves it to the browser otherwise", () => { + it("never requires consent regardless of edge country headers", () => { const on = { ...CLOUD, ...TOKEN, ...BROWSER }; const withHeader = { ...on, PAPERCLIP_POSTHOG_COUNTRY_HEADER: "CF-IPCountry" }; - expect(resolveBrowserAnalyticsConfig(on, { "cf-ipcountry": "DE" })?.consentRequired).toBeNull(); - expect(resolveBrowserAnalyticsConfig(withHeader, { "cf-ipcountry": "DE" })?.consentRequired).toBe(true); - expect(resolveBrowserAnalyticsConfig(withHeader, { "cf-ipcountry": "gb" })?.consentRequired).toBe(true); - expect(resolveBrowserAnalyticsConfig(withHeader, { "cf-ipcountry": "CH" })?.consentRequired).toBe(true); - expect(resolveBrowserAnalyticsConfig(withHeader, { "cf-ipcountry": "NO" })?.consentRequired).toBe(true); + expect(resolveBrowserAnalyticsConfig(on, { "cf-ipcountry": "DE" })?.consentRequired).toBe(false); + expect(resolveBrowserAnalyticsConfig(withHeader, { "cf-ipcountry": "DE" })?.consentRequired).toBe(false); + expect(resolveBrowserAnalyticsConfig(withHeader, { "cf-ipcountry": "gb" })?.consentRequired).toBe(false); + expect(resolveBrowserAnalyticsConfig(withHeader, { "cf-ipcountry": "CH" })?.consentRequired).toBe(false); expect(resolveBrowserAnalyticsConfig(withHeader, { "cf-ipcountry": "US" })?.consentRequired).toBe(false); - expect(resolveBrowserAnalyticsConfig(withHeader, { "cf-ipcountry": "XX" })?.consentRequired).toBeNull(); - expect(resolveBrowserAnalyticsConfig(withHeader, {})?.consentRequired).toBeNull(); - expect(resolveBrowserAnalyticsConfig(withHeader, { "cf-ipcountry": ["FR", "US"] })?.consentRequired).toBe(true); + expect(resolveBrowserAnalyticsConfig(withHeader, {})?.consentRequired).toBe(false); }); it("always sends an environment: the explicit variable, else staging or production from the host", () => { diff --git a/server/src/services/cloud-posthog-browser.ts b/server/src/services/cloud-posthog-browser.ts index 88284426ac1..254a01aaf79 100644 --- a/server/src/services/cloud-posthog-browser.ts +++ b/server/src/services/cloud-posthog-browser.ts @@ -9,7 +9,7 @@ // The browser sends to `POSTHOG_PROXY_PATH` on its own origin, not to PostHog, // so ad blockers do not drop the events. See `routes/posthog-proxy.ts`. -import { countryRequiresAnalyticsConsent, type BrowserAnalyticsConfig } from "@paperclipai/shared"; +import type { BrowserAnalyticsConfig } from "@paperclipai/shared"; import { isCloudStagingInstance, type CloudInstanceEnv } from "./cloud-instance.js"; import { resolveCloudPostHogConfig, type CloudPostHogConfig } from "./cloud-posthog-config.js"; @@ -20,13 +20,6 @@ const POSTHOG_CLOUD_INGEST_HOST = /^(us|eu)\.i\.posthog\.com$/i; export type RequestHeaders = Record; -export function resolveAnalyticsConsentRequired(env: CloudInstanceEnv, headers: RequestHeaders): boolean | null { - const headerName = env.PAPERCLIP_POSTHOG_COUNTRY_HEADER?.trim().toLowerCase(); - if (!headerName) return null; - const value = headers[headerName]; - return countryRequiresAnalyticsConsent(Array.isArray(value) ? value[0] : value); -} - /** The browser analytics part of the Cloud PostHog config, or null when it is off. */ export function resolveBrowserPostHogConfig(env: CloudInstanceEnv = process.env): CloudPostHogConfig | null { const config = resolveCloudPostHogConfig(env); @@ -53,7 +46,7 @@ export function posthogUiHost(ingestHost: string): string | null { export function resolveBrowserAnalyticsConfig( env: CloudInstanceEnv = process.env, - headers: RequestHeaders = {}, + _headers: RequestHeaders = {}, options?: { cloudTrialInferenceEnabled?: boolean }, ): BrowserAnalyticsConfig | null { const config = resolveBrowserPostHogConfig(env); @@ -74,7 +67,9 @@ export function resolveBrowserAnalyticsConfig( environment: config.environment ?? (isCloudStagingInstance(env) ? "staging" : "production"), stackId: config.stackId, replayEnabled: config.replayEnabled, - consentRequired: resolveAnalyticsConsentRequired(env, headers), + // Consent banner is disabled during private beta; sending false also keeps + // any cached older UI bundle from prompting during rollout. + consentRequired: false, cloudTrialInferenceEnabled: typeof options?.cloudTrialInferenceEnabled === "boolean" ? options.cloudTrialInferenceEnabled diff --git a/ui/src/components/AnalyticsConsentBanner.test.tsx b/ui/src/components/AnalyticsConsentBanner.test.tsx deleted file mode 100644 index 0bd9bbc3709..00000000000 --- a/ui/src/components/AnalyticsConsentBanner.test.tsx +++ /dev/null @@ -1,54 +0,0 @@ -// @vitest-environment jsdom - -import { act } from "react"; -import { createRoot } from "react-dom/client"; -import { afterEach, describe, expect, it, vi } from "vitest"; -import { AnalyticsConsentBanner } from "./AnalyticsConsentBanner"; - -Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); - -describe("AnalyticsConsentBanner", () => { - let container: HTMLDivElement; - - afterEach(() => { - container.remove(); - }); - - function render(props: Parameters[0]) { - container = document.createElement("div"); - document.body.appendChild(container); - const root = createRoot(container); - act(() => root.render()); - return root; - } - - it("is a labelled region with plain copy, a privacy link and two keyboard buttons", () => { - const onAccept = vi.fn(); - const onDecline = vi.fn(); - const root = render({ recordings: true, onAccept, onDecline }); - const region = container.querySelector("section")!; - expect(region.getAttribute("aria-label")).toBe("Analytics choice"); - const description = document.getElementById(region.getAttribute("aria-describedby")!); - expect(description?.textContent).toContain( - "Paperclip uses analytics and session recordings to improve the product. Recordings hide what you type and your messages, documents and connected accounts, but may show page names like task titles.", - ); - const link = region.querySelector("a")!; - expect(link.textContent).toBe("Privacy policy"); - expect(link.getAttribute("href")).toBe("https://paperclip.ing/privacy/"); - const buttons = [...region.querySelectorAll("button")]; - expect(buttons.map((button) => button.textContent)).toEqual(["Decline", "Accept"]); - expect(buttons.every((button) => button.type === "button")).toBe(true); - act(() => buttons[0]!.click()); - act(() => buttons[1]!.click()); - expect(onDecline).toHaveBeenCalledTimes(1); - expect(onAccept).toHaveBeenCalledTimes(1); - expect(container.querySelector("[aria-modal]")).toBeNull(); - act(() => root.unmount()); - }); - - it("does not mention recordings when replay is off", () => { - const root = render({ recordings: false, onAccept: vi.fn(), onDecline: vi.fn() }); - expect(container.textContent).not.toContain("recordings"); - act(() => root.unmount()); - }); -}); diff --git a/ui/src/components/AnalyticsConsentBanner.tsx b/ui/src/components/AnalyticsConsentBanner.tsx deleted file mode 100644 index 7a5525bbb60..00000000000 --- a/ui/src/components/AnalyticsConsentBanner.tsx +++ /dev/null @@ -1,47 +0,0 @@ -import { useId } from "react"; -import { Button } from "@/components/ui/button"; - -export const PRIVACY_POLICY_URL = "https://paperclip.ing/privacy/"; - -export function AnalyticsConsentBanner({ - recordings, - onAccept, - onDecline, -}: { - recordings: boolean; - onAccept: () => void; - onDecline: () => void; -}) { - const textId = useId(); - return ( -
-
-

- {recordings - ? "Paperclip uses analytics and session recordings to improve the product. Recordings hide what you type and your messages, documents and connected accounts, but may show page names like task titles. " - : "Paperclip uses analytics to improve the product. "} - - Privacy policy - -

-
- - -
-
-
- ); -} diff --git a/ui/src/components/ProductAnalyticsGate.test.tsx b/ui/src/components/ProductAnalyticsGate.test.tsx index ca3f094770a..8f34a2ba67b 100644 --- a/ui/src/components/ProductAnalyticsGate.test.tsx +++ b/ui/src/components/ProductAnalyticsGate.test.tsx @@ -5,12 +5,6 @@ import { createRoot } from "react-dom/client"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { captureProductAnalyticsEvent, resetProductAnalyticsForTest } from "@/lib/analytics/product-analytics"; -import { - ANALYTICS_CONSENT_STORAGE_KEY, - resetAnalyticsConsentForTest, - storeAnalyticsChoice, -} from "@/lib/analytics/consent"; -import { queryKeys } from "@/lib/queryKeys"; import { ProductAnalyticsGate } from "./ProductAnalyticsGate"; const getSessionMock = vi.hoisted(() => vi.fn()); @@ -71,14 +65,6 @@ function analyticsConfig(overrides: Record = {}) { }; } -function banner() { - return document.querySelector('section[aria-label="Analytics choice"]'); -} - -function bannerButton(name: string) { - return [...(banner()?.querySelectorAll("button") ?? [])].find((button) => button.textContent === name)!; -} - function session(browserAnalytics: unknown) { return { session: { id: `paperclip:session:${ACTOR_ID}`, userId: ACTOR_ID }, @@ -109,7 +95,6 @@ describe("ProductAnalyticsGate", () => { vi.useRealTimers(); container.remove(); resetProductAnalyticsForTest(); - resetAnalyticsConsentForTest(); window.localStorage.clear(); scriptDownload.hold = false; scriptDownload.pending = []; @@ -119,7 +104,7 @@ describe("ProductAnalyticsGate", () => { vi.clearAllMocks(); }); - async function renderGate() { + async function renderGate(waitForSettle = true) { const root = createRoot(container); await act(async () => { root.render( @@ -128,7 +113,7 @@ describe("ProductAnalyticsGate", () => { , ); }); - await settle(); + if (waitForSettle) await settle(); return root; } @@ -147,9 +132,12 @@ describe("ProductAnalyticsGate", () => { act(() => root.unmount()); }); - it("loads posthog-js and identifies the user when the session carries a config", async () => { - getSessionMock.mockResolvedValue(session(analyticsConfig({ consentRequired: false }))); + it("loads posthog-js and identifies the user without showing any consent banner", async () => { + window.localStorage.setItem("paperclip.analyticsConsent", "denied"); + Object.defineProperty(navigator, "globalPrivacyControl", { value: true, configurable: true }); + getSessionMock.mockResolvedValue(session(analyticsConfig({ consentRequired: true }))); const root = await renderGate(); + expect(document.querySelector('section[aria-label="Analytics choice"]')).toBeNull(); // PostHog's script comes through the same-origin proxy, never from PostHog directly. expect(injectedScripts().map((script) => new URL(script.src).pathname)).toEqual(["/_ph/static/array.js"]); expect(posthogMock.init).toHaveBeenCalledWith("phc_test", expect.objectContaining({ disable_session_recording: true })); @@ -160,151 +148,37 @@ describe("ProductAnalyticsGate", () => { act(() => root.unmount()); }); - it("asks first and loads nothing for a visitor who must consent", async () => { - getSessionMock.mockResolvedValue(session(analyticsConfig({ consentRequired: true }))); - const root = await renderGate(); - expect(banner()).not.toBeNull(); - expect(banner()?.textContent).toContain("Paperclip uses analytics to improve the product."); - expect(banner()?.querySelector("a")?.getAttribute("href")).toBe("https://paperclip.ing/privacy/"); - expect(injectedScripts()).toHaveLength(0); - expect(posthogMock.init).not.toHaveBeenCalled(); - act(() => root.unmount()); - }); - - it("loads analytics at once when the visitor accepts, and remembers the choice", async () => { - getSessionMock.mockResolvedValue(session(analyticsConfig({ consentRequired: true, replayEnabled: true }))); - const root = await renderGate(); - await act(async () => { - bannerButton("Accept").click(); - await Promise.resolve(); - await Promise.resolve(); - }); - expect(window.localStorage.getItem(ANALYTICS_CONSENT_STORAGE_KEY)).toBe("granted"); - expect(banner()).toBeNull(); - expect(injectedScripts()).toHaveLength(1); - expect(posthogMock.init).toHaveBeenCalledWith("phc_test", expect.objectContaining({ disable_session_recording: false })); - act(() => root.unmount()); - }); - - it("sends events from before Accept once, in order and with their original timestamps", async () => { - getSessionMock.mockResolvedValue(session(analyticsConfig({ consentRequired: true }))); + it("sends events queued before posthog-js loads once, in order and with their original timestamps", async () => { + scriptDownload.hold = true; + getSessionMock.mockResolvedValue(session(analyticsConfig())); const root = await renderGate(); const openedAt = new Date(); captureProductAnalyticsEvent("onboarding_opened", { step: "create_agent" }); - await act(async () => { await vi.advanceTimersByTimeAsync(1_000); }); + 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(); }); + await act(async () => { + for (const finish of scriptDownload.pending.splice(0)) finish(); + await Promise.resolve(); + }); 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 }))); + it("clears an earlier PostHog opt-out when initializing", async () => { + posthogMock.has_opted_out_capturing.mockReturnValueOnce(true); + getSessionMock.mockResolvedValue(session(analyticsConfig({ replayEnabled: true }))); const root = await renderGate(); - await act(async () => { - bannerButton("Decline").click(); - }); - await settle(); - expect(window.localStorage.getItem(ANALYTICS_CONSENT_STORAGE_KEY)).toBe("denied"); - expect(banner()).toBeNull(); - expect(injectedScripts()).toHaveLength(0); - act(() => root.unmount()); - }); - - it("treats Global Privacy Control as a decline for a visitor who must consent", async () => { - Object.defineProperty(navigator, "globalPrivacyControl", { value: true, configurable: true }); - getSessionMock.mockResolvedValue(session(analyticsConfig({ consentRequired: true }))); - const root = await renderGate(); - expect(banner()).toBeNull(); - expect(injectedScripts()).toHaveLength(0); - act(() => root.unmount()); - }); - - it("keeps a stored decline across page loads", async () => { - window.localStorage.setItem(ANALYTICS_CONSENT_STORAGE_KEY, "denied"); - getSessionMock.mockResolvedValue(session(analyticsConfig({ consentRequired: false }))); - const root = await renderGate(); - expect(banner()).toBeNull(); - expect(injectedScripts()).toHaveLength(0); - act(() => root.unmount()); - }); - - it("opts out and stops recording now when the choice changes to off, and opts back in", async () => { - getSessionMock.mockResolvedValue(session(analyticsConfig({ consentRequired: false, replayEnabled: true }))); - const root = await renderGate(); - expect(posthogMock.init).toHaveBeenCalledTimes(1); - act(() => storeAnalyticsChoice("denied")); - expect(posthogMock.opt_out_capturing).toHaveBeenCalledTimes(1); - expect(posthogMock.stopSessionRecording).toHaveBeenCalledTimes(1); - act(() => storeAnalyticsChoice("granted")); expect(posthogMock.opt_in_capturing).toHaveBeenCalledTimes(1); expect(posthogMock.startSessionRecording).toHaveBeenCalledTimes(1); - expect(posthogMock.init).toHaveBeenCalledTimes(1); - expect(injectedScripts()).toHaveLength(1); - act(() => root.unmount()); - }); - - it("clears an earlier PostHog opt-out when the stored choice is on", async () => { - posthogMock.has_opted_out_capturing.mockReturnValueOnce(true); - window.localStorage.setItem(ANALYTICS_CONSENT_STORAGE_KEY, "granted"); - getSessionMock.mockResolvedValue(session(analyticsConfig({ consentRequired: true }))); - const root = await renderGate(); - expect(posthogMock.opt_in_capturing).toHaveBeenCalledTimes(1); - act(() => root.unmount()); - }); - - it("never initializes PostHog when the visitor turns analytics off while its script is downloading", async () => { - scriptDownload.hold = true; - getSessionMock.mockResolvedValue(session(analyticsConfig({ consentRequired: false, replayEnabled: true }))); - const root = await renderGate(); - expect(injectedScripts()).toHaveLength(1); - act(() => storeAnalyticsChoice("denied")); - await act(async () => { - for (const finish of scriptDownload.pending.splice(0)) finish(); - await Promise.resolve(); - }); - expect(posthogMock.init).not.toHaveBeenCalled(); - act(() => storeAnalyticsChoice("granted")); - expect(posthogMock.init).toHaveBeenCalledTimes(1); - expect(injectedScripts()).toHaveLength(1); - act(() => root.unmount()); - }); - - it("stops analytics when another tab clears the choice and the visitor must be asked again", async () => { - window.localStorage.setItem(ANALYTICS_CONSENT_STORAGE_KEY, "granted"); - getSessionMock.mockResolvedValue(session(analyticsConfig({ consentRequired: true, replayEnabled: true }))); - const root = await renderGate(); - expect(posthogMock.init).toHaveBeenCalledTimes(1); - act(() => { - window.localStorage.removeItem(ANALYTICS_CONSENT_STORAGE_KEY); - window.dispatchEvent(new StorageEvent("storage", { key: ANALYTICS_CONSENT_STORAGE_KEY })); - }); - expect(banner()).not.toBeNull(); - expect(posthogMock.opt_out_capturing).toHaveBeenCalledTimes(1); - expect(posthogMock.stopSessionRecording).toHaveBeenCalledTimes(1); - act(() => root.unmount()); - }); - - it("stops analytics when a session refresh says the visitor must consent", async () => { - getSessionMock.mockResolvedValue(session(analyticsConfig({ consentRequired: false }))); - const root = await renderGate(); - expect(posthogMock.init).toHaveBeenCalledTimes(1); - await act(async () => { - queryClient.setQueryData(queryKeys.auth.session, session(analyticsConfig({ consentRequired: true }))); - await vi.advanceTimersByTimeAsync(10); - }); - expect(banner()).not.toBeNull(); - expect(posthogMock.opt_out_capturing).toHaveBeenCalledTimes(1); act(() => root.unmount()); }); }); diff --git a/ui/src/components/ProductAnalyticsGate.tsx b/ui/src/components/ProductAnalyticsGate.tsx index 211fce89a2f..dfa5fa46fd2 100644 --- a/ui/src/components/ProductAnalyticsGate.tsx +++ b/ui/src/components/ProductAnalyticsGate.tsx @@ -4,19 +4,14 @@ import { authApi } from "@/api/auth"; import { queryKeys } from "@/lib/queryKeys"; import { whenPageSettles } from "@/lib/when-page-settles"; import { + cancelPendingProductAnalytics, PRODUCT_ANALYTICS_LOAD_DEADLINE_MS, setProductAnalyticsUser, - syncProductAnalytics, + startProductAnalytics, } from "@/lib/analytics/product-analytics"; -import { - analyticsChoiceMadeOnThisPage, - storeAnalyticsChoice, - useAnalyticsConsent, -} from "@/lib/analytics/consent"; -import { AnalyticsConsentBanner } from "./AnalyticsConsentBanner"; /** - * Browser product analytics for hosted Paperclip Cloud. + * Browser product analytics for hosted Paperclip Cloud. Renders nothing. * * It reads the signed-in session, like `SentryGate` (same query, so no extra * request). The server sends `browserAnalytics` only for a cloud-managed @@ -39,12 +34,10 @@ export function ProductAnalyticsGate() { const userId = session?.session.userId ?? null; const email = session?.user.email ?? null; const name = session?.user.name ?? null; - const consent = useAnalyticsConsent(config); useEffect(() => { - if (!config || !consent) return; - return syncProductAnalytics(config, consent, { - immediate: analyticsChoiceMadeOnThisPage(), + if (!config) return; + startProductAnalytics(config, { schedule: (start) => { const cancelSettle = whenPageSettles(queryClient, start); const deadline = window.setTimeout(start, PRODUCT_ANALYTICS_LOAD_DEADLINE_MS); @@ -54,19 +47,13 @@ export function ProductAnalyticsGate() { }; }, }); + return () => cancelPendingProductAnalytics(); // Keyed by value: the config object identity changes on every session refetch. - }, [configKey, consent, queryClient]); + }, [configKey, queryClient]); useEffect(() => { setProductAnalyticsUser(userId ? { id: userId, email, name } : null); }, [userId, email, name]); - if (!config || consent !== "ask") return null; - return ( - storeAnalyticsChoice("granted")} - onDecline={() => storeAnalyticsChoice("denied")} - /> - ); + return null; } diff --git a/ui/src/components/ProductAnalyticsSetting.test.tsx b/ui/src/components/ProductAnalyticsSetting.test.tsx deleted file mode 100644 index 272c7145f64..00000000000 --- a/ui/src/components/ProductAnalyticsSetting.test.tsx +++ /dev/null @@ -1,76 +0,0 @@ -// @vitest-environment jsdom - -import { act } from "react"; -import { createRoot } from "react-dom/client"; -import { afterEach, describe, expect, it } from "vitest"; -import type { BrowserAnalyticsConfig } from "@paperclipai/shared"; -import { ANALYTICS_CONSENT_STORAGE_KEY, resetAnalyticsConsentForTest } from "@/lib/analytics/consent"; -import { ProductAnalyticsSetting } from "./ProductAnalyticsSetting"; - -Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); - -const config: BrowserAnalyticsConfig = { - token: "phc_test", - apiHost: "/_ph", - uiHost: null, - environment: "production", - stackId: "stack-1", - replayEnabled: true, - consentRequired: false, -}; - -describe("ProductAnalyticsSetting", () => { - let container: HTMLDivElement; - - afterEach(() => { - container.remove(); - window.localStorage.clear(); - resetAnalyticsConsentForTest(); - }); - - function render(value: BrowserAnalyticsConfig | null) { - container = document.createElement("div"); - document.body.appendChild(container); - const root = createRoot(container); - act(() => root.render()); - return root; - } - - it("shows nothing when browser analytics is off for the instance", () => { - const root = render(null); - expect(container.innerHTML).toBe(""); - act(() => root.unmount()); - }); - - it("turns analytics off and on for this browser", () => { - const root = render(config); - const toggle = container.querySelector('[role="switch"]')!; - expect(document.getElementById(toggle.getAttribute("aria-labelledby")!)?.textContent).toBe("Product analytics"); - expect(toggle.getAttribute("aria-checked")).toBe("true"); - act(() => toggle.click()); - expect(window.localStorage.getItem(ANALYTICS_CONSENT_STORAGE_KEY)).toBe("denied"); - expect(toggle.getAttribute("aria-checked")).toBe("false"); - act(() => toggle.click()); - expect(window.localStorage.getItem(ANALYTICS_CONSENT_STORAGE_KEY)).toBe("granted"); - expect(toggle.getAttribute("aria-checked")).toBe("true"); - act(() => root.unmount()); - }); - - it("is off before a visitor who must consent has chosen", () => { - const root = render({ ...config, consentRequired: true }); - expect(container.querySelector('[role="switch"]')?.getAttribute("aria-checked")).toBe("false"); - act(() => root.unmount()); - }); - - it("stays off and cannot be turned on when the browser asks not to be tracked where consent is required", () => { - Object.defineProperty(navigator, "globalPrivacyControl", { value: true, configurable: true }); - window.localStorage.setItem(ANALYTICS_CONSENT_STORAGE_KEY, "granted"); - const root = render({ ...config, consentRequired: true }); - const toggle = container.querySelector('[role="switch"]')!; - expect(toggle.getAttribute("aria-checked")).toBe("false"); - expect(toggle.disabled).toBe(true); - expect(container.textContent).toContain("Your browser asks sites not to track you"); - Object.defineProperty(navigator, "globalPrivacyControl", { value: undefined, configurable: true }); - act(() => root.unmount()); - }); -}); diff --git a/ui/src/components/ProductAnalyticsSetting.tsx b/ui/src/components/ProductAnalyticsSetting.tsx deleted file mode 100644 index 943805fd5e2..00000000000 --- a/ui/src/components/ProductAnalyticsSetting.tsx +++ /dev/null @@ -1,47 +0,0 @@ -import { useId } from "react"; -import { ChartNoAxesColumn } from "lucide-react"; -import type { BrowserAnalyticsConfig } from "@paperclipai/shared"; -import { ToggleSwitch } from "@/components/ui/toggle-switch"; -import { browserBlocksAnalytics, storeAnalyticsChoice, useAnalyticsConsent } from "@/lib/analytics/consent"; -import { PRIVACY_POLICY_URL } from "./AnalyticsConsentBanner"; - -export function ProductAnalyticsSetting({ config }: { config: BrowserAnalyticsConfig | null | undefined }) { - const consent = useAnalyticsConsent(config ?? null); - const labelId = useId(); - const descriptionId = useId(); - if (!config || !consent) return null; - const blocked = browserBlocksAnalytics(config); - return ( -
-
-
-
- -

Product analytics

-
-

- {config.replayEnabled - ? "Share usage analytics and session recordings from this browser to help improve Paperclip. Recordings hide what you type and your messages, documents and connected accounts, but may show page names like task titles. " - : "Share usage analytics from this browser to help improve Paperclip. "} - {blocked ? "Your browser asks sites not to track you, so analytics stays off. " : null} - - Privacy policy - -

-
- storeAnalyticsChoice(checked ? "granted" : "denied")} - aria-labelledby={labelId} - aria-describedby={descriptionId} - /> -
-
- ); -} diff --git a/ui/src/lib/analytics/consent.test.tsx b/ui/src/lib/analytics/consent.test.tsx deleted file mode 100644 index 22a472d75f6..00000000000 --- a/ui/src/lib/analytics/consent.test.tsx +++ /dev/null @@ -1,134 +0,0 @@ -// @vitest-environment jsdom - -import { act } from "react"; -import { createRoot } from "react-dom/client"; -import { afterEach, describe, expect, it, vi } from "vitest"; -import type { BrowserAnalyticsConfig } from "@paperclipai/shared"; -import { - ANALYTICS_CONSENT_STORAGE_KEY, - resetAnalyticsConsentForTest, - resolveAnalyticsConsent, - storeAnalyticsChoice, - useAnalyticsConsent, -} from "./consent"; - -Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); - -const config: BrowserAnalyticsConfig = { - token: "phc_test", - apiHost: "/_ph", - uiHost: null, - environment: "production", - stackId: "stack-1", - replayEnabled: true, -}; - -function useTimeZone(timeZone: string) { - vi.spyOn(Intl.DateTimeFormat.prototype, "resolvedOptions").mockReturnValue({ - ...new Intl.DateTimeFormat("en-US", { timeZone: "UTC" }).resolvedOptions(), - timeZone, - }); -} - -function setNavigatorSignal(name: "doNotTrack" | "globalPrivacyControl", value: unknown) { - Object.defineProperty(navigator, name, { value, configurable: true }); -} - -afterEach(() => { - vi.restoreAllMocks(); - window.localStorage.clear(); - resetAnalyticsConsentForTest(); - setNavigatorSignal("doNotTrack", null); - setNavigatorSignal("globalPrivacyControl", undefined); -}); - -describe("resolveAnalyticsConsent", () => { - it("uses the server's decision when it has one", () => { - useTimeZone("Europe/Paris"); - expect(resolveAnalyticsConsent({ ...config, consentRequired: false })).toBe("granted"); - useTimeZone("America/Chicago"); - expect(resolveAnalyticsConsent({ ...config, consentRequired: true })).toBe("ask"); - }); - - it("falls back to the browser time zone when the server cannot tell", () => { - useTimeZone("Europe/Paris"); - expect(resolveAnalyticsConsent({ ...config, consentRequired: null })).toBe("ask"); - useTimeZone("America/Chicago"); - expect(resolveAnalyticsConsent(config)).toBe("granted"); - }); - - it("requires consent when the browser time zone cannot be read", () => { - vi.spyOn(Intl, "DateTimeFormat").mockImplementation(() => { - throw new Error("no Intl"); - }); - expect(resolveAnalyticsConsent(config)).toBe("ask"); - }); - - it("treats Do Not Track and Global Privacy Control as a decline only where consent is required", () => { - setNavigatorSignal("doNotTrack", "1"); - expect(resolveAnalyticsConsent({ ...config, consentRequired: true })).toBe("denied"); - expect(resolveAnalyticsConsent({ ...config, consentRequired: false })).toBe("granted"); - setNavigatorSignal("doNotTrack", null); - setNavigatorSignal("globalPrivacyControl", true); - expect(resolveAnalyticsConsent({ ...config, consentRequired: true })).toBe("denied"); - }); - - it("a stored choice wins over the region default", () => { - window.localStorage.setItem(ANALYTICS_CONSENT_STORAGE_KEY, "granted"); - expect(resolveAnalyticsConsent({ ...config, consentRequired: true })).toBe("granted"); - window.localStorage.setItem(ANALYTICS_CONSENT_STORAGE_KEY, "denied"); - expect(resolveAnalyticsConsent({ ...config, consentRequired: false })).toBe("denied"); - }); - - it("lets Global Privacy Control and Do Not Track win over a stored grant where consent is required", () => { - window.localStorage.setItem(ANALYTICS_CONSENT_STORAGE_KEY, "granted"); - setNavigatorSignal("globalPrivacyControl", true); - expect(resolveAnalyticsConsent({ ...config, consentRequired: true })).toBe("denied"); - storeAnalyticsChoice("granted"); - expect(resolveAnalyticsConsent({ ...config, consentRequired: true })).toBe("denied"); - expect(resolveAnalyticsConsent({ ...config, consentRequired: false })).toBe("granted"); - setNavigatorSignal("globalPrivacyControl", undefined); - setNavigatorSignal("doNotTrack", "1"); - expect(resolveAnalyticsConsent({ ...config, consentRequired: true })).toBe("denied"); - }); - - it("keeps the choice for this page when storage is unavailable", () => { - vi.spyOn(Storage.prototype, "getItem").mockImplementation(() => { - throw new Error("blocked"); - }); - vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => { - throw new Error("blocked"); - }); - expect(resolveAnalyticsConsent({ ...config, consentRequired: true })).toBe("ask"); - storeAnalyticsChoice("granted"); - expect(resolveAnalyticsConsent({ ...config, consentRequired: true })).toBe("granted"); - }); - - it("lets the latest choice on this page win when saving fails but reading still works", () => { - window.localStorage.setItem(ANALYTICS_CONSENT_STORAGE_KEY, "granted"); - vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => { - throw new Error("quota"); - }); - storeAnalyticsChoice("denied"); - expect(window.localStorage.getItem(ANALYTICS_CONSENT_STORAGE_KEY)).toBe("granted"); - expect(resolveAnalyticsConsent({ ...config, consentRequired: false })).toBe("denied"); - }); - - it("follows a choice that another tab changes", () => { - const seen: string[] = []; - const container = document.createElement("div"); - function Probe() { - seen.push(String(useAnalyticsConsent({ ...config, consentRequired: true }))); - return null; - } - const root = createRoot(container); - act(() => root.render()); - act(() => storeAnalyticsChoice("granted")); - act(() => { - window.localStorage.removeItem(ANALYTICS_CONSENT_STORAGE_KEY); - window.dispatchEvent(new StorageEvent("storage", { key: ANALYTICS_CONSENT_STORAGE_KEY })); - }); - expect(seen.at(-1)).toBe("ask"); - act(() => root.unmount()); - }); -}); diff --git a/ui/src/lib/analytics/consent.ts b/ui/src/lib/analytics/consent.ts deleted file mode 100644 index c75757cf60c..00000000000 --- a/ui/src/lib/analytics/consent.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { useSyncExternalStore } from "react"; -import { timeZoneRequiresAnalyticsConsent, type BrowserAnalyticsConfig } from "@paperclipai/shared"; - -export const ANALYTICS_CONSENT_STORAGE_KEY = "paperclip.analyticsConsent"; - -export type AnalyticsChoice = "granted" | "denied"; -export type AnalyticsConsent = AnalyticsChoice | "ask"; - -function browserTimeZone(): string | null { - try { - return Intl.DateTimeFormat().resolvedOptions().timeZone ?? null; - } catch { - return null; - } -} - -export function consentRequired(config: BrowserAnalyticsConfig): boolean { - if (typeof config.consentRequired === "boolean") return config.consentRequired; - return timeZoneRequiresAnalyticsConsent(browserTimeZone()); -} - -export function browserAsksNotToTrack(): boolean { - if (typeof navigator === "undefined") return false; - const nav = navigator as Navigator & { globalPrivacyControl?: boolean }; - return nav.globalPrivacyControl === true || nav.doNotTrack === "1"; -} - -export function readStoredAnalyticsChoice(): AnalyticsChoice | null { - try { - const value = window.localStorage.getItem(ANALYTICS_CONSENT_STORAGE_KEY); - return value === "granted" || value === "denied" ? value : null; - } catch { - return null; - } -} - -const listeners = new Set<() => void>(); -let pageChoice: AnalyticsChoice | null = null; - -function writeStoredAnalyticsChoice(choice: AnalyticsChoice): void { - try { - window.localStorage.setItem(ANALYTICS_CONSENT_STORAGE_KEY, choice); - } catch { - return; - } -} - -export function storeAnalyticsChoice(choice: AnalyticsChoice): void { - pageChoice = choice; - writeStoredAnalyticsChoice(choice); - for (const listener of listeners) listener(); -} - -export function analyticsChoiceMadeOnThisPage(): boolean { - return pageChoice !== null; -} - -export function browserBlocksAnalytics(config: BrowserAnalyticsConfig): boolean { - return consentRequired(config) && browserAsksNotToTrack(); -} - -export function resolveAnalyticsConsent(config: BrowserAnalyticsConfig): AnalyticsConsent { - if (browserBlocksAnalytics(config)) return "denied"; - const stored = pageChoice ?? readStoredAnalyticsChoice(); - if (stored) return stored; - return consentRequired(config) ? "ask" : "granted"; -} - -function subscribe(listener: () => void) { - listeners.add(listener); - const onStorage = (event: StorageEvent) => { - if (event.key !== null && event.key !== ANALYTICS_CONSENT_STORAGE_KEY) return; - pageChoice = null; - listener(); - }; - window.addEventListener("storage", onStorage); - return () => { - listeners.delete(listener); - window.removeEventListener("storage", onStorage); - }; -} - -export function useAnalyticsConsent(config: BrowserAnalyticsConfig | null): AnalyticsConsent | null { - return useSyncExternalStore( - subscribe, - () => (config ? resolveAnalyticsConsent(config) : null), - () => null, - ); -} - -export function resetAnalyticsConsentForTest(): void { - pageChoice = null; -} diff --git a/ui/src/lib/analytics/onboarding-analytics.test.tsx b/ui/src/lib/analytics/onboarding-analytics.test.tsx index 8e5b1084f17..b29ef640149 100644 --- a/ui/src/lib/analytics/onboarding-analytics.test.tsx +++ b/ui/src/lib/analytics/onboarding-analytics.test.tsx @@ -10,7 +10,7 @@ import { captureProductAnalyticsEvent, resetProductAnalyticsForTest, setProductAnalyticsUser, - syncProductAnalytics, + startProductAnalytics, type ProductAnalyticsClient, } from "./product-analytics"; import { @@ -82,7 +82,8 @@ const schedule = (start: () => void) => { }; async function startAnalytics() { - syncProductAnalytics(config, "granted", { load, schedule, immediate: true }); + startProductAnalytics(config, { load, schedule }); + scheduled?.(); await flush(); } @@ -107,17 +108,8 @@ describe("browser product events", () => { expect(client.capture).not.toHaveBeenCalled(); }); - it.each(["denied", "ask"] as const)("captures nothing when consent is %s", async (consent) => { - syncProductAnalytics(config, consent, { load, schedule, immediate: true }); - await flush(); - captureProductAnalyticsEvent("onboarding_opened", { step: "create_agent" }); - await flush(); - expect(client.init).not.toHaveBeenCalled(); - expect(client.capture).not.toHaveBeenCalled(); - }); - it("holds events from before posthog-js loads and sends them with their own time", async () => { - syncProductAnalytics(config, "granted", { load, schedule }); + startProductAnalytics(config, { load, schedule }); captureProductAnalyticsEvent("onboarding_opened", { step: "create_agent" }); expect(client.capture).not.toHaveBeenCalled(); scheduled!(); @@ -130,61 +122,25 @@ 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 }); + it("bounds the pre-load queue to 50 events", async () => { + startProductAnalytics(config, { load, schedule }); for (let index = 0; index < 50; index++) { captureProductAnalyticsEvent("onboarding_step_viewed", { step: "create_agent" }); } captureProductAnalyticsEvent("onboarding_step_viewed", { step: "review" }); - await startAnalytics(); + scheduled!(); + await flush(); 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 () => { + it("drops held events on a person change before posthog-js loads", 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" }); - scheduled!(); - syncProductAnalytics(config, "denied", { load, schedule }); - await flush(); - captureProductAnalyticsEvent("onboarding_dismissed", { step: "create_agent" }); - expect(client.capture).not.toHaveBeenCalled(); - }); - - 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, consent, { load, schedule }); + startProductAnalytics(config, { 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" }]]); @@ -193,20 +149,13 @@ describe("browser product events", () => { it("keeps held events when the same person is set again before posthog-js loads", async () => { setProductAnalyticsUser({ id: "user-1", email: null, name: null }); - syncProductAnalytics(config, "granted", { load, schedule }); + startProductAnalytics(config, { load, schedule }); captureProductAnalyticsEvent("onboarding_opened", { step: "create_agent" }); setProductAnalyticsUser({ id: "user-1", email: "jane@example.com", name: null }); scheduled!(); await flush(); expect(captured()).toEqual([["onboarding_opened", { step: "create_agent" }]]); }); - - it("stops capturing after consent is withdrawn", async () => { - await startAnalytics(); - syncProductAnalytics(config, "denied", { load, schedule }); - captureProductAnalyticsEvent("onboarding_opened", {}); - expect(client.capture).not.toHaveBeenCalled(); - }); }); describe("onboarding funnel events", () => { @@ -294,17 +243,17 @@ describe("onboarding funnel events", () => { ]); }); - it("sends queued wizard events after consent without reopening the wizard", async () => { - syncProductAnalytics(config, "ask", { load, schedule, immediate: true }); + it("sends queued wizard events once posthog-js loads without reopening the wizard", async () => { + startProductAnalytics(config, { load, schedule }); 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(); + scheduled!(); + await flush(); expect(captured()).toEqual([ ["onboarding_opened", { step: "create_agent" }], ["onboarding_step_viewed", { step: "create_agent" }], diff --git a/ui/src/lib/analytics/product-analytics.ts b/ui/src/lib/analytics/product-analytics.ts index d1c414099a0..95935a114ea 100644 --- a/ui/src/lib/analytics/product-analytics.ts +++ b/ui/src/lib/analytics/product-analytics.ts @@ -23,7 +23,6 @@ // 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, @@ -219,9 +218,7 @@ type State = { config: BrowserAnalyticsConfig; client: ProductAnalyticsClient | null; cancelSchedule: (() => void) | null; - pendingClient: ProductAnalyticsClient | null; loading: boolean; - consent: AnalyticsConsent; queued: QueuedProductEvent[]; }; @@ -237,14 +234,12 @@ let state: State | null = null; let wantedUser: ProductAnalyticsUser | null = null; let identifiedUserId: string | null = null; -function createAnalyticsState(config: BrowserAnalyticsConfig, consent: AnalyticsConsent): State { +function createAnalyticsState(config: BrowserAnalyticsConfig): State { return { config, client: null, - pendingClient: null, cancelSchedule: null, loading: false, - consent, queued: [], }; } @@ -281,20 +276,15 @@ function sendProductEvent(client: ProductAnalyticsClient, queued: QueuedProductE export function captureProductAnalyticsEvent(event: string, properties: Record = {}): void { const current = state; - if (!current || current.consent === "denied") return; + if (!current) return; const queued = { event, properties: { ...properties }, timestamp: new Date() }; - if (current.client && current.consent === "granted") { + if (current.client) { sendProductEvent(current.client, queued); return; } if (current.queued.length < MAX_QUEUED_PRODUCT_EVENTS) current.queued.push(queued); } -function optOut(client: ProductAnalyticsClient) { - client.opt_out_capturing?.(); - client.stopSessionRecording?.(); -} - function optIn(client: ProductAnalyticsClient, config: BrowserAnalyticsConfig) { client.opt_in_capturing?.(); if (config.replayEnabled) client.startSessionRecording?.(); @@ -325,23 +315,9 @@ export function startProductAnalytics( config: BrowserAnalyticsConfig, options: ProductAnalyticsOptions, ): void { - if (state?.consent === "granted") return; - const current = state ?? createAnalyticsState(config, "granted"); + if (state) return; + const current = createAnalyticsState(config); state = current; - current.consent = "granted"; - if (current.client) { - optIn(current.client, current.config); - applyIdentity(current.client, current.config); - flushQueuedProductEvents(current, current.client); - return; - } - 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). @@ -353,8 +329,7 @@ export function startProductAnalytics( load(current.config) .then((client) => { if (state !== current) return; - if (current.consent !== "granted") current.pendingClient = client; - else initialize(current, client); + initialize(current, client); }) .catch(() => { // Analytics must never break the board. A failed script load leaves it @@ -368,7 +343,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 && state.consent === "granted") applyIdentity(state.client, state.config); + if (state?.client) applyIdentity(state.client, state.config); } /** @@ -386,41 +361,11 @@ export function resetProductAnalyticsIdentity(): void { * through `setProductAnalyticsUser(null)`. */ export function cancelPendingProductAnalytics(): void { - if (!state || state.client || state.pendingClient || state.loading) return; + if (!state || state.client || state.loading) return; state.cancelSchedule?.(); state = null; } -function stopProductAnalytics(consent: "ask" | "denied"): void { - if (!state) return; - 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: AnalyticsConsent, - options: ProductAnalyticsOptions & { immediate?: boolean }, -): () => void { - if (consent !== "granted") { - if (!state && consent === "ask") state = createAnalyticsState(config, consent); - stopProductAnalytics(consent); - return () => undefined; - } - const schedule: ProductAnalyticsOptions["schedule"] = options.immediate - ? (start) => { - start(); - return () => undefined; - } - : options.schedule; - startProductAnalytics(config, { ...options, schedule }); - return cancelPendingProductAnalytics; -} - export function resetProductAnalyticsForTest(): void { state?.cancelSchedule?.(); state = null; diff --git a/ui/src/pages/ProfileSettings.tsx b/ui/src/pages/ProfileSettings.tsx index 393431863df..d7b3403041a 100644 --- a/ui/src/pages/ProfileSettings.tsx +++ b/ui/src/pages/ProfileSettings.tsx @@ -10,7 +10,6 @@ import { useBreadcrumbs } from "../context/BreadcrumbContext"; import { useCompany } from "../context/CompanyContext"; import { queryKeys } from "../lib/queryKeys"; import { InboxAgentPolicyControl } from "@/components/InboxAgentPolicyControl"; -import { ProductAnalyticsSetting } from "@/components/ProductAnalyticsSetting"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { Card } from "@/components/ui/card"; import { Button } from "@/components/ui/button"; @@ -290,8 +289,6 @@ export function ProfileSettings() { - - ); diff --git a/ui/src/pages/mobile-collections-responsive.test.tsx b/ui/src/pages/mobile-collections-responsive.test.tsx index ac72c56fb82..c8fd16e8ab5 100644 --- a/ui/src/pages/mobile-collections-responsive.test.tsx +++ b/ui/src/pages/mobile-collections-responsive.test.tsx @@ -201,10 +201,6 @@ vi.mock("@/components/SmokeLabDashboardCard", () => ({ SmokeLabDashboardCard: () => null, })); -vi.mock("@/components/ProductAnalyticsSetting", () => ({ - ProductAnalyticsSetting: () => null, -})); - vi.mock("@/components/primary-agent/PrimaryAgentPresentation", () => ({ PrimaryAgentIndicator: () => null, }));