Files
PaperClipAI/ui/src/components/ProductAnalyticsGate.test.tsx
T
DottaandClaude Opus 5.5 3c460f20cc feat(analytics): ask EU, UK and Swiss visitors before Cloud browser analytics (#22186)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Paperclip Cloud can send browser product analytics and session
replays to PostHog. Self-hosted installs never do this.
> - Today, browser analytics starts for every Cloud visitor after the
page settles.
> - Visitors in the EU, the EEA, the UK and Switzerland must agree
before analytics cookies and session recordings start.
> - This pull request adds a consent step for these visitors and a
switch in the user's profile settings.
> - The benefit is that Cloud analytics follows the owner decision: ask
in Europe, keep the current behavior elsewhere, and let every user
change the choice.

## Linked Issues or Issue Description

**Subsystem affected**
Paperclip Cloud browser product analytics (`ui/src/lib/analytics`,
`ProductAnalyticsGate`, the session route, and Profile settings).

**Problem or motivation**
Browser analytics and session replay start for every Cloud visitor
without a choice. EU, EEA, UK and Swiss visitors must consent first. The
privacy policy draft also says that users can change the choice in
settings. No such setting exists.

**Proposed solution**
Ask visitors in the EU, the EEA, the UK and Switzerland with a small
bottom banner (Accept or Decline). Do not load posthog-js before they
accept. Treat Do Not Track and Global Privacy Control as a decline for
these visitors. Keep the choice in `localStorage`. Add a "Product
analytics" switch to Profile settings for every user when browser
analytics is on.

**Alternatives considered**
A server-side country from a trusted edge header. Paperclip Cloud has no
such header today: Cloudflare records are DNS-only, so no `CF-IPCountry`
arrives, and the Railway edge adds no country header. This PR supports
an optional header (`PAPERCLIP_POSTHOG_COUNTRY_HEADER`) for a future
edge, and uses the browser time zone until then.

## What Changed

- `packages/shared`: `browserAnalytics` has a new optional
`consentRequired: boolean | null`.
- `packages/shared/src/analytics-consent.ts` (new): the one region
policy. `countryRequiresAnalyticsConsent` (EU and EEA with outermost
regions and Svalbard, GB with the Crown Dependencies and Gibraltar, CH)
and `timeZoneRequiresAnalyticsConsent` (`Europe/*`, EU, EEA and UK zones
outside Europe, and unknown zones such as `UTC` or `Etc/*`). The server
and the UI both use it.
- `server`: `resolveBrowserAnalyticsConfig` sets `consentRequired` from
the header that `PAPERCLIP_POSTHOG_COUNTRY_HEADER` names. No header or
an unknown code (`XX`) gives `null`.
- `ui/src/lib/analytics/consent.ts` (new): decides `granted`, `denied`
or `ask`. Order: for a visitor who must consent, Do Not Track or Global
Privacy Control gives `denied` (also over a stored Accept); then the
choice made on this page; then the stored choice; then the region
(server value, else browser time zone). The choice is in `localStorage`
key `paperclip.analyticsConsent`. All storage access is in `try/catch`.
A cross-tab `storage` event updates the page.
- `ProductAnalyticsGate`: one effect calls `syncProductAnalytics(config,
consent)`. Shows `AnalyticsConsentBanner` when consent is `ask`. Accept
loads posthog-js at once, without a reload.
- `product-analytics.ts`: new `syncProductAnalytics`. It starts, opts
in, opts out (`opt_out_capturing()` and `stopSessionRecording()`) or
cancels a pending load. Any consent other than `granted` stops
analytics. If consent is withdrawn while the script downloads, `init()`
does not run until a later opt-in.
- `AnalyticsConsentBanner` (new): a labelled bottom region with plain
copy, a privacy policy link, and Decline and Accept buttons (shared
`Button`). The copy says that recordings hide what you type and your
messages, documents and connected accounts, but may show page names like
task titles. It does not block the page. On mobile it sits above the
bottom navigation.
- `ProductAnalyticsSetting` (new) in Profile settings: a "Product
analytics" switch (shared `ToggleSwitch`). It shows only when browser
analytics is on for the instance. When GPC or DNT blocks analytics, it
is off and disabled and says why.
- `doc/cloud-browser-analytics.md`: new Consent section (signal,
behavior table, storage key, how to reset) and the new variable.
- `tests/runner-e2e/source-sdk-public-inputs.json`: refreshed for the
changed shared validator.

## Verification

- Red/green: the 7 new `ProductAnalyticsGate` consent tests fail against
the master gate (7 failed, 3 passed). The 5 review-fix tests (failed
write with working read, cross-tab change, decline during script
download, granted -> ask from another tab, granted -> ask from a session
refresh) fail on the first commit (5 failed, 16 passed). All pass now.
- `cd ui && npx vitest run src/lib/analytics
src/components/ProductAnalyticsGate.test.tsx
src/components/AnalyticsConsentBanner.test.tsx
src/components/ProductAnalyticsSetting.test.tsx
src/pages/ProfileSettings.test.tsx`: 267 tests pass.
- `cd server && npx vitest run
src/__tests__/cloud-posthog-browser.test.ts
src/__tests__/auth-routes.test.ts
src/__tests__/auth-session-route.test.ts`: 87 tests pass.
`packages/shared` `analytics-consent.test.ts` passes. `tsc --noEmit` for
`ui`, `server` and `packages/shared` shows no new errors.
- `pnpm verify` exits 2 (a doc is a global CI input). Required CI gives
the broad coverage.
- Real check in headless Chromium. I ran a local Cloud-managed instance
(external local PostgreSQL, `PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN`,
`PAPERCLIP_POSTHOG_BROWSER_ENABLED=1`). `PAPERCLIP_POSTHOG_HOST` pointed
at a local capture server, not PostHog. The capture server served a
small stand-in for `array.js` that sets a `ph_*` cookie and
`localStorage` key and posts `/e/` events. I set the visitor region with
the browser time zone:

| Visitor | Result |
| --- | --- |
| `Europe/Berlin`, no choice, 18 s wait | Banner shows. 0 `/_ph`
requests. No `ph_*` cookie or storage key. |
| Then Accept (keyboard Enter) | Banner closes. `GET
/_ph/static/array.js` and `POST /_ph/e/` in 3 s. Key is `granted`. After
reload: no banner, events continue. |
| `Europe/London`, Decline, wait, reload, wait | No banner. 0 `/_ph`
requests. No `ph_*` cookie or storage key. Key is `denied`. |
| `Europe/Zurich` with Global Privacy Control | No banner. 0 `/_ph`
requests. No `ph_*` cookie or storage key. |
| `America/New_York` | No banner. posthog-js loads after the page
settles, as before. |
| Profile settings switch (US) | Shows on. Off: client is opted out at
once. On: opt-in, events continue. |

- I ran the browser check again after the review fixes, with the same
results.
- Screenshots (banner light, banner dark, mobile 375 px light and dark,
settings switch): see the PR comment.
- Cold load (local dev server, fresh browser context per run, median of
7, ms):

| Build | Time zone | FCP | DOMContentLoaded | load |
| --- | --- | --- | --- | --- |
| master | New York | 728 / 724 | 687 / 684 | 689 / 686 |
| this PR | New York | 748 / 724 | 708 / 684 | 710 / 686 |
| master | Berlin | 740 | 694 | 697 |
| this PR | Berlin | 756 / 724 | 716 / 684 | 718 / 686 |

The second round gives the same medians for master and this PR. The
first-round difference is noise. The consent code adds no request and no
load-time wait.

## Risks

- Region by time zone is approximate. It asks some visitors outside the
EU (for example `Europe/Istanbul`, or `UTC` browsers). This is the safe
direction.
- A forged country header (only when `PAPERCLIP_POSTHOG_COUNTRY_HEADER`
is set) changes only the default for that visitor's own browser.
- The choice is per browser. A user on a new browser sees the banner
again (in consent regions).
- Visitors in consent regions now send no browser analytics until they
accept. Expect fewer EU/UK sessions in PostHog.
- Self-hosted installs: no change. They get no `browserAnalytics`
config, so no banner, no switch and no load.

## Model Used

- Claude Opus 5.5 (claude-opus-5-5), Anthropic, used through Claude Code
with tool use (shell, file edits, headless browser).

## 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
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:52:20 -06:00

288 lines
12 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 { 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());
const posthogMock = vi.hoisted(() => ({
init: vi.fn(),
register: vi.fn(),
identify: vi.fn(),
group: vi.fn(),
reset: 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 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 },
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();
resetAnalyticsConsentForTest();
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() {
const root = createRoot(container);
await act(async () => {
root.render(
<QueryClientProvider client={queryClient}>
<ProductAnalyticsGate />
</QueryClientProvider>,
);
});
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 when the session carries a config", async () => {
getSessionMock.mockResolvedValue(session(analyticsConfig({ consentRequired: false })));
const root = await renderGate();
// 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("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("keeps analytics off when the visitor declines", async () => {
getSessionMock.mockResolvedValue(session(analyticsConfig({ consentRequired: 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());
});
});