Files
PaperClipAI/ui/src/components/ProductAnalyticsGate.test.tsx
T
DottaandPaperclip 1eae356c55 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>
2026-11-30 22:49:39 +00:00

185 lines
7.0 KiB
TypeScript

// @vitest-environment jsdom
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 { captureProductAnalyticsEvent, resetProductAnalyticsForTest } from "@/lib/analytics/product-analytics";
import { ProductAnalyticsGate } from "./ProductAnalyticsGate";
const getSessionMock = vi.hoisted(() => vi.fn());
const posthogMock = vi.hoisted(() => ({
init: vi.fn(),
register: vi.fn(),
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),
startSessionRecording: vi.fn(),
stopSessionRecording: vi.fn(),
}));
vi.mock("@/api/auth", () => ({
authApi: { getSession: () => getSessionMock() },
}));
const scriptDownload: { hold: boolean; pending: Array<() => void> } = { hold: false, pending: [] };
/** PostHog script elements the module adds to the page. */
function injectedScripts() {
return [...document.querySelectorAll("script")].filter((script) => script.src.includes("/static/array.js"));
}
// jsdom does not fetch scripts: when the module adds PostHog's script, act as
// the browser would after it loads (the script sets `window.posthog`).
const appendChild = document.head.appendChild.bind(document.head);
vi.spyOn(document.head, "appendChild").mockImplementation(<T extends Node>(node: T): T => {
const result = appendChild(node);
if (node instanceof HTMLScriptElement && node.src.includes("/static/array.js")) {
(window as unknown as { posthog: typeof posthogMock }).posthog = posthogMock;
const finish = () => node.onload?.(new Event("load"));
if (scriptDownload.hold) scriptDownload.pending.push(finish);
else queueMicrotask(finish);
}
return result;
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
const ACTOR_ID = "paperclip-id:uf2X8Ha4H9hNdAMnc1rOy91VIRos5pch";
const user = { id: ACTOR_ID, email: "jane@example.com", name: "Jane", image: null };
function analyticsConfig(overrides: Record<string, unknown> = {}) {
return {
token: "phc_test",
apiHost: "/_ph",
uiHost: null,
environment: "production",
stackId: "stack-1",
replayEnabled: false,
...overrides,
};
}
function session(browserAnalytics: unknown) {
return {
session: { id: `paperclip:session:${ACTOR_ID}`, userId: ACTOR_ID },
user,
sentryDsn: null,
browserAnalytics,
};
}
async function settle() {
await act(async () => {
await vi.advanceTimersByTimeAsync(20_000);
});
}
describe("ProductAnalyticsGate", () => {
let container: HTMLDivElement;
let queryClient: QueryClient;
beforeEach(() => {
vi.useFakeTimers();
container = document.createElement("div");
document.body.appendChild(container);
queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
});
afterEach(() => {
vi.useRealTimers();
container.remove();
resetProductAnalyticsForTest();
window.localStorage.clear();
scriptDownload.hold = false;
scriptDownload.pending = [];
Object.defineProperty(navigator, "globalPrivacyControl", { value: undefined, configurable: true });
for (const script of injectedScripts()) script.remove();
delete (window as unknown as { posthog?: unknown }).posthog;
vi.clearAllMocks();
});
async function renderGate(waitForSettle = true) {
const root = createRoot(container);
await act(async () => {
root.render(
<QueryClientProvider client={queryClient}>
<ProductAnalyticsGate />
</QueryClientProvider>,
);
});
if (waitForSettle) await settle();
return root;
}
it("loads nothing and does nothing when the session has no analytics config (self-hosted)", async () => {
getSessionMock.mockResolvedValue(session(null));
const root = await renderGate();
expect(injectedScripts()).toHaveLength(0);
expect(posthogMock.init).not.toHaveBeenCalled();
act(() => root.unmount());
});
it("loads nothing when signed out", async () => {
getSessionMock.mockResolvedValue(null);
const root = await renderGate();
expect(injectedScripts()).toHaveLength(0);
act(() => root.unmount());
});
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 }));
// Same id, same format, as the server's actor id (its events' distinct_id).
expect(posthogMock.identify).toHaveBeenCalledWith(ACTOR_ID, { email: "jane@example.com", name: "Jane" });
expect(posthogMock.group).toHaveBeenCalledWith("workspace", "stack-1");
expect(posthogMock.register).toHaveBeenCalledWith({ deployment_source: "cloud", environment: "production" });
act(() => root.unmount());
});
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);
});
const completedAt = new Date();
captureProductAnalyticsEvent("onboarding_step_completed", { step: "create_agent" });
expect(posthogMock.capture).not.toHaveBeenCalled();
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 }],
]);
act(() => root.unmount());
});
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();
expect(posthogMock.opt_in_capturing).toHaveBeenCalledTimes(1);
expect(posthogMock.startSessionRecording).toHaveBeenCalledTimes(1);
act(() => root.unmount());
});
});