mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-02 10:44:52 +01:00
fix(analytics): remove PostHog consent banner and opt-out gating for private beta (#23333)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Paperclip Cloud sends browser product analytics and session replays to PostHog when enabled for a hosted stack (self-hosted installs never load posthog-js) > - Previously, an EU/UK/Swiss consent banner and Profile settings opt-out toggle gated browser analytics and dropped metrics when visitors did not opt in > - During private beta, we want to stop showing the consent banner and opt-out prompt anywhere while continuing to send metrics (compliance will be handled separately later) > - This pull request removes the consent banner, Profile opt-out toggle, and client-side consent gating across the UI and sets `consentRequired: false` on the server response > - The benefit is zero banner friction during private beta and uninterrupted PostHog product metrics, while keeping all replay/autocapture privacy masking and pre-load event queuing intact ## Linked Issues or Issue Description **What existing behavior does this improve?** Paperclip Cloud browser product analytics initialization (`ProductAnalyticsGate`, `ui/src/lib/analytics`, `ProfileSettings`, `cloud-posthog-browser.ts`). **Subsystem affected** Cross-cutting (multiple of the above) — `ui/` and `server/`. **Current behavior** In EU/EEA/UK/Swiss regions (or unknown time zones), `ProductAnalyticsGate` renders `AnalyticsConsentBanner` and blocks loading `posthog-js` until the visitor clicks Accept. `ProfileSettings` also renders a `ProductAnalyticsSetting` opt-out switch. **Proposed behavior** Remove `AnalyticsConsentBanner`, `ProductAnalyticsSetting`, and client-side consent gating so `ProductAnalyticsGate` loads PostHog unconditionally when `browserAnalytics` is enabled for a Cloud stack. Return `consentRequired: false` from `resolveBrowserAnalyticsConfig` so cached older UI bundles also stop prompting during rollout, and keep `opt_in_capturing()` when `has_opted_out_capturing()` is true so previously opted-out browsers resume sending metrics. **Reason and benefit** During private beta, the EU/UK consent banner adds friction and drops PostHog product metrics. Removing the banner and opt-out gating restores full metric delivery while keeping all replay/autocapture privacy masking and pre-load event queuing intact. **Breaking changes** None — `browserAnalytics.consentRequired` remains on the session payload (as `false`), self-hosted installs still receive `browserAnalytics: null`, and per-stack env controls (`PAPERCLIP_POSTHOG_BROWSER_ENABLED`, `PAPERCLIP_POSTHOG_REPLAY_ENABLED=0`) continue to work. ## What Changed - Deleted `ui/src/components/AnalyticsConsentBanner.tsx`, `ui/src/components/ProductAnalyticsSetting.tsx`, `ui/src/lib/analytics/consent.ts`, and their unit tests. - Simplified `ui/src/components/ProductAnalyticsGate.tsx` to start PostHog unconditionally after the page settles and render `null`. - Simplified `ui/src/lib/analytics/product-analytics.ts` to remove consent-state gating while keeping pre-load event queuing (`MAX_QUEUED_PRODUCT_EVENTS`) and automatic opt-in for browsers with a prior PostHog opt-out. - Removed `ProductAnalyticsSetting` from `ui/src/pages/ProfileSettings.tsx` and its mock in `ui/src/pages/mobile-collections-responsive.test.tsx`. - Updated `server/src/services/cloud-posthog-browser.ts` to always return `consentRequired: false`. - Updated `ui/src/components/ProductAnalyticsGate.test.tsx`, `ui/src/lib/analytics/onboarding-analytics.test.tsx`, `server/src/__tests__/cloud-posthog-browser.test.ts`, `server/src/__tests__/auth-routes.test.ts`, and `doc/cloud-browser-analytics.md`. ## Verification - `pnpm vitest run ui/src/components/ProductAnalyticsGate.test.tsx ui/src/lib/analytics/onboarding-analytics.test.tsx ui/src/lib/analytics/product-analytics.test.ts ui/src/pages/mobile-collections-responsive.test.tsx server/src/__tests__/cloud-posthog-browser.test.ts server/src/__tests__/auth-routes.test.ts` — all passed. - `pnpm --filter @paperclipai/ui typecheck` — passed. - `pnpm --filter @paperclipai/server typecheck` — passed. ## Risks - Low risk: self-hosted installs remain unaffected (`browserAnalytics` is still `null`). All replay/autocapture privacy masking and `/_ph` proxy allowlists remain unchanged. Per-stack opt-out (`PAPERCLIP_POSTHOG_BROWSER_ENABLED` / `PAPERCLIP_POSTHOG_REPLAY_ENABLED=0`) continues to work. ## Model Used - Google Gemini (Antigravity agent with tool use and code execution) ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
adc4501689
commit
1eae356c55
16 files changed
+77
-849
No files matched your search
@@ -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<typeof AnalyticsConsentBanner>[0]) {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
act(() => root.render(<AnalyticsConsentBanner {...props} />));
|
||||
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());
|
||||
});
|
||||
});
|
||||
@@ -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 (
|
||||
<section
|
||||
aria-label="Analytics choice"
|
||||
aria-describedby={textId}
|
||||
className="fixed inset-x-4 bottom-(--sz-calc-14) z-40 mx-auto max-w-xl rounded-md border bg-popover text-popover-foreground shadow-lg md:bottom-4"
|
||||
>
|
||||
<div className="flex flex-col gap-3 p-4 sm:flex-row sm:items-center">
|
||||
<p id={textId} className="flex-1 text-sm text-muted-foreground">
|
||||
{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. "}
|
||||
<a
|
||||
href={PRIVACY_POLICY_URL}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="font-medium text-foreground underline underline-offset-4 hover:opacity-90"
|
||||
>
|
||||
Privacy policy
|
||||
</a>
|
||||
</p>
|
||||
<div className="flex shrink-0 gap-2">
|
||||
<Button type="button" variant="outline" size="sm" onClick={onDecline}>
|
||||
Decline
|
||||
</Button>
|
||||
<Button type="button" size="sm" onClick={onAccept}>
|
||||
Accept
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -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<string, unknown> = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
function banner() {
|
||||
return document.querySelector<HTMLElement>('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", () => {
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
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());
|
||||
});
|
||||
});
|
||||
@@ -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 (
|
||||
<AnalyticsConsentBanner
|
||||
recordings={config.replayEnabled}
|
||||
onAccept={() => storeAnalyticsChoice("granted")}
|
||||
onDecline={() => storeAnalyticsChoice("denied")}
|
||||
/>
|
||||
);
|
||||
return 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(<ProductAnalyticsSetting config={value} />));
|
||||
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<HTMLButtonElement>('[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<HTMLButtonElement>('[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());
|
||||
});
|
||||
});
|
||||
@@ -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 (
|
||||
<section className="space-y-4" aria-labelledby={labelId}>
|
||||
<div className="flex max-w-2xl items-start justify-between gap-4">
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<ChartNoAxesColumn className="h-5 w-5 text-muted-foreground" />
|
||||
<h2 id={labelId} className="text-base font-semibold">Product analytics</h2>
|
||||
</div>
|
||||
<p id={descriptionId} className="text-sm text-muted-foreground">
|
||||
{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}
|
||||
<a
|
||||
href={PRIVACY_POLICY_URL}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="font-medium text-foreground underline underline-offset-4 hover:opacity-90"
|
||||
>
|
||||
Privacy policy
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
<ToggleSwitch
|
||||
checked={consent === "granted"}
|
||||
disabled={blocked}
|
||||
onCheckedChange={(checked) => storeAnalyticsChoice(checked ? "granted" : "denied")}
|
||||
aria-labelledby={labelId}
|
||||
aria-describedby={descriptionId}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user