Files
PaperClipAI/ui/src/pages/ProfileSettings.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

299 lines
12 KiB
TypeScript

import { useEffect, useId, useRef, useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Camera, LoaderCircle, Save, Trash2, UserRoundPen } from "lucide-react";
import type { AuthSession, CurrentUserProfile, UpdateCurrentUserProfile } from "@paperclipai/shared";
import { authApi } from "@/api/auth";
import { useAccountBoundMutation } from "@/hooks/useAccountBoundMutation";
import { assetsApi } from "@/api/assets";
import { QueryErrorState, useQueryView } from "@/components/QueryView";
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";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { describeError } from "@/api/errors";
function deriveInitials(name: string) {
const parts = name.trim().split(/\s+/).filter(Boolean);
if (parts.length >= 2) return `${parts[0]?.[0] ?? ""}${parts[parts.length - 1]?.[0] ?? ""}`.toUpperCase();
return name.slice(0, 2).toUpperCase();
}
export function ProfileSettings() {
const { setBreadcrumbs } = useBreadcrumbs();
const { selectedCompanyId, selectedCompany } = useCompany();
const queryClient = useQueryClient();
const avatarInputId = useId();
const avatarInputRef = useRef<HTMLInputElement | null>(null);
// Unedited fields show the session's saved values from the first frame; a
// restored session must not render an empty name until an effect fills it.
const [nameDraft, setName] = useState<string | null>(null);
const [imageDraft, setImage] = useState<string | null>(null);
const [actionError, setActionError] = useState<string | null>(null);
const sessionQuery = useQuery({
queryKey: queryKeys.auth.session,
queryFn: () => authApi.getSession(),
});
const sessionView = useQueryView(sessionQuery);
const name = nameDraft ?? sessionQuery.data?.user.name ?? "";
const image = imageDraft ?? sessionQuery.data?.user.image ?? "";
useEffect(() => {
setBreadcrumbs([
{ label: "Settings", href: "/company/settings" },
{ label: "Profile" },
]);
}, [setBreadcrumbs]);
useEffect(() => {
setName(null);
setImage(null);
}, [sessionQuery.data]);
function syncSessionProfile(profile: CurrentUserProfile) {
queryClient.setQueryData<AuthSession | null>(queryKeys.auth.session, (current) => {
if (!current) return current;
return {
...current,
user: {
...current.user,
...profile,
},
};
});
}
// A restored session can show one account while the cookie belongs to
// another, and the server saves for the cookie's user. Account-bound
// mutations wait for a verified session and abort if the user changed.
async function persistProfile(input: UpdateCurrentUserProfile, assertCurrentAccount: () => void) {
assertCurrentAccount();
const profile = await authApi.updateProfile(input);
assertCurrentAccount();
syncSessionProfile(profile);
return profile;
}
function resolveProfileName() {
return name.trim() || sessionQuery.data?.user.name || "Board";
}
const updateMutation = useAccountBoundMutation({
mutationFn: (input: UpdateCurrentUserProfile, { assertCurrentAccount }) => persistProfile(input, assertCurrentAccount),
onSuccess: (profile) => {
setActionError(null);
setName(profile.name ?? "");
setImage(profile.image ?? "");
},
onError: (error) => {
setActionError(describeError(error).body);
},
});
const uploadAvatarMutation = useAccountBoundMutation({
mutationFn: async (file: File, { assertCurrentAccount }) => {
if (!selectedCompanyId) {
throw new Error("Select an organization before uploading a profile avatar.");
}
const asset = await assetsApi.uploadImage(
selectedCompanyId,
file,
`profiles/${sessionQuery.data?.user.id ?? "board-user"}`,
);
return persistProfile({ name: resolveProfileName(), image: asset.contentPath }, assertCurrentAccount);
},
onSuccess: (profile) => {
setActionError(null);
setName(profile.name ?? "");
setImage(profile.image ?? "");
},
onError: (error) => {
setActionError(describeError(error).body);
},
});
const removeAvatarMutation = useAccountBoundMutation({
mutationFn: (_input, { assertCurrentAccount }) => persistProfile({ name: resolveProfileName(), image: null }, assertCurrentAccount),
onSuccess: (profile) => {
setActionError(null);
setName(profile.name ?? "");
setImage(profile.image ?? "");
},
onError: (error) => {
setActionError(describeError(error).body);
},
});
if (sessionQuery.isLoading || sessionView.kind === "reconnecting") {
return <div className="text-sm text-muted-foreground">Loading profile...</div>;
}
if (sessionView.kind === "error") {
return (
<QueryErrorState
size="page"
error={sessionQuery.error}
action="load your profile"
onRetry={sessionView.retry}
retrying={sessionView.isFetching}
/>
);
}
if (!sessionQuery.data) {
return <div className="text-sm text-destructive">Failed to load profile.</div>;
}
const currentName = name.trim() || sessionQuery.data.user.name || "Board";
const currentImage = image.trim() || null;
const initials = deriveInitials(currentName);
const isSavingProfile = updateMutation.isPending || uploadAvatarMutation.isPending || removeAvatarMutation.isPending;
const uploadHint = selectedCompany
? `Stored in Paperclip file storage for ${selectedCompany.name}.`
: "Select an organization to upload an avatar into Paperclip storage.";
return (
<div className="max-w-6xl space-y-6">
<div className="space-y-2">
<div className="flex items-center gap-2">
<UserRoundPen className="h-5 w-5 text-muted-foreground" />
<h1 className="text-lg font-semibold">Profile</h1>
</div>
<p className="text-sm text-muted-foreground">
Control how your account appears in the sidebar and other board surfaces.
</p>
</div>
{actionError ? (
<div className="rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-sm text-destructive">
{actionError}
</div>
) : null}
<section className="space-y-8">
<Card className="block relative overflow-hidden rounded-(--rad-28) border-border/70">
<div className="absolute inset-x-0 top-0 h-32 bg-(image:--gradient-extract-26)" />
<div className="absolute inset-0 bg-(image:--gradient-extract-7)" />
<div className="relative p-6 pt-10">
<div className="flex flex-wrap items-end gap-5 rounded-(--rad-24) border border-border/70 bg-background/92 p-5 shadow-(--shadow-extract-18) backdrop-blur-sm">
<div className="space-y-3">
<label
htmlFor={avatarInputId}
className="group relative block cursor-pointer rounded-full focus-within:outline-none focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 focus-within:ring-offset-background"
>
<input
ref={avatarInputRef}
id={avatarInputId}
type="file"
accept="image/*"
className="sr-only"
disabled={!selectedCompanyId || isSavingProfile}
onChange={(event) => {
const file = event.target.files?.[0];
if (!file) return;
uploadAvatarMutation.mutate(file);
event.target.value = "";
}}
/>
<span className="absolute inset-0 z-10 rounded-full bg-black/0 transition-colors group-hover:bg-black/14 group-focus-within:bg-black/14" />
<span className="absolute bottom-1 right-1 z-20 flex size-9 items-center justify-center rounded-full border border-background bg-primary text-primary-foreground shadow-sm">
{uploadAvatarMutation.isPending ? <LoaderCircle className="size-4 animate-spin" /> : <Camera className="size-4" />}
</span>
<Avatar size="lg" className="data-[size=lg]:size-24 ring-4 ring-background shadow-xl">
{currentImage ? <AvatarImage src={currentImage} alt={currentName} /> : null}
<AvatarFallback>{initials}</AvatarFallback>
</Avatar>
</label>
<div className="flex flex-wrap items-center gap-2">
<Button
type="button"
variant="secondary"
onClick={() => avatarInputRef.current?.click()}
disabled={!selectedCompanyId || isSavingProfile}
>
{uploadAvatarMutation.isPending ? <LoaderCircle className="size-4 animate-spin" /> : <Camera className="size-4" />}
{currentImage ? "Change photo" : "Upload photo"}
</Button>
{currentImage ? (
<Button
type="button"
variant="outline"
onClick={() => removeAvatarMutation.mutate()}
disabled={isSavingProfile}
>
{removeAvatarMutation.isPending ? <LoaderCircle className="size-4 animate-spin" /> : <Trash2 className="size-4" />}
Remove
</Button>
) : null}
</div>
</div>
<div className="min-w-0 flex-1 space-y-2 pb-1">
<div>
<h2 className="truncate text-2xl font-semibold text-foreground">{currentName}</h2>
<p className="truncate text-sm text-muted-foreground">{sessionQuery.data.user.email ?? "No email"}</p>
</div>
<p className="max-w-2xl text-sm leading-6 text-muted-foreground">
Click the avatar to upload a new image. {uploadHint}
</p>
</div>
</div>
</div>
</Card>
<form
className="grid gap-6 md:grid-cols-2"
onSubmit={(event) => {
event.preventDefault();
updateMutation.mutate({ name: resolveProfileName(), image: image.trim() || null });
}}
>
<div className="space-y-2">
<Label htmlFor="profile-name">Display name</Label>
<Input
id="profile-name"
value={name}
onChange={(event) => setName(event.target.value)}
maxLength={120}
placeholder="Board"
/>
<p className="text-xs text-muted-foreground">
Shown in the sidebar account footer and comment author surfaces.
</p>
</div>
<div className="space-y-2">
<Label htmlFor="profile-email">Email</Label>
<Input
id="profile-email"
value={sessionQuery.data.user.email ?? ""}
readOnly
disabled
/>
<p className="text-xs text-muted-foreground">
Email is managed by your auth session and is read-only here.
</p>
</div>
<div className="md:col-span-2 flex justify-end">
<Button type="submit" disabled={isSavingProfile || !name.trim()}>
{updateMutation.isPending ? <LoaderCircle className="size-4 animate-spin" /> : <Save className="size-4" />}
{updateMutation.isPending ? "Saving..." : "Save profile"}
</Button>
</div>
</form>
<InboxAgentPolicyControl companyId={selectedCompanyId} />
<ProductAnalyticsSetting config={sessionQuery.data.browserAnalytics} />
</section>
</div>
);
}