Commit Graph
6 Commits
Author SHA1 Message Date
DottaandClaude Opus 5.5 92dbf39e6f feat(analytics): attribute agent work and onboarding steps to a person on Cloud (#22260)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Paperclip Cloud sends product events straight to PostHog: server
events from `server/src/services/posthog-direct/` and browser events
from `ui/src/lib/analytics/`
> - A person-level funnel goes from sign-up to the first finished task
> - Agent-driven events (`agent.task_run`, `agent.task_completed`,
`agent.first_heartbeat`) used `workspace:<stackId>` as the distinct id,
so the funnel broke at those steps
> - The in-workspace onboarding wizard sent no step events, so we could
not see where people stop before their first agent
> - This pull request attributes agent work to the responsible person on
the Cloud direct path, and adds consent-gated onboarding step events in
the browser
> - The benefit is one PostHog person per customer across sign-up,
onboarding, agent runs, and task completion. Self-hosted output does not
change.

## Linked Issues or Issue Description

**Subsystem affected**
Cloud product analytics: Cloud direct PostHog delivery (server) and
browser product analytics (UI onboarding wizard).

**Problem or motivation**
A PostHog funnel from sign-up to the first finished task cannot follow
one person. Agent-driven events run in the background, with no signed-in
request, so they use the workspace id as the distinct id. The onboarding
wizard also sends no events, so we cannot see which step people leave.

**Proposed solution**
Give background emit sites a narrow scope that names the person
responsible for the work. Use the task creator first, then the task's
responsible user, then the run owner. Keep the signed-in request user
first. Add `attributed_via` to every Cloud direct event. Add four
browser events to the onboarding wizard. Send them through the existing
analytics module, so the consent rules stay the same.

**Alternatives considered**
A lookup in the transport at send time. We did not use it: it adds
database reads to the telemetry path and loses the emit site's context.
A new contract event for onboarding steps. We did not use it: the server
does not see the wizard steps, and the UI must never send
`PAPERCLIP_EVENTS` names.

**Additional context**
Self-hosted installs keep the collector path. The collector envelope
stays byte-identical (a test checks it).

## What Changed

- `server/src/telemetry-company-scope.ts`: add `withTelemetryActor({
companyId, person }, fn)`, `scopedTelemetryPerson()`, and
`resolveTelemetryPerson()`. The resolver picks the task creator, then
the task's responsible user, then the run owner. It ignores
`local-board`. `withTelemetryCompany` now calls `withTelemetryActor`.
- `server/src/services/posthog-direct/request-context.ts`: a signed-in
request user wins (`attributed_via: request`). Without one, the scoped
person is used.
- `server/src/services/posthog-direct/event-shape.ts`: every Cloud
direct event (including `cloud.workspace_started`) has `attributed_via`
(`request`, `task_creator`, `task_assigner`, `run_owner`, or `none`). An
event with a person keeps today's person-event shape (no
`$process_person_profile: false`).
- `server/src/services/agent-task-run-telemetry.ts`: `agent.task_run`
reads the task creator and responsible user in the existing agent query
(one left join, no new query), and the run's `responsibleUserId`.
- `server/src/routes/issues.ts`: `agent.task_completed` uses the issue
row that the route already has, and the agent actor's `onBehalfOfUserId`
as the run owner.
- `server/src/services/heartbeat/agent-status.ts`:
`agent.first_heartbeat` uses the agent's `createdByUserId` (already
loaded) as the run owner.
- `ui/src/lib/analytics/product-analytics.ts`: add
`captureProductAnalyticsEvent()`. It captures only with a browser
analytics config and granted consent. Events from before posthog-js
loads wait in a queue (at most 50) and keep their time. Withdrawn
consent or a change of signed-in person drops the queue.
- `ui/src/lib/analytics/onboarding-analytics.ts` and
`ui/src/components/OnboardingWizard.tsx`: capture `onboarding_opened`,
`onboarding_step_viewed`, `onboarding_step_completed` (with `step` and,
for `connect_model` and `launch`, `outcome`), and
`onboarding_dismissed`. `step` is `create_agent`, `connect_model`,
`review`, or `launch`. No event has free text.
- Docs: `packages/shared/src/telemetry/README.md` (Cloud Direct
Delivery) and `doc/cloud-browser-analytics.md` (new "Onboarding events"
section).

## Verification

- `server/src/__tests__/posthog-direct-telemetry.test.ts`: attribution
matrix (creator, assigner, run owner, none stays on
`workspace:<stackId>` with `$process_person_profile: false`), the
request user wins over the scope, and the self-hosted collector envelope
is byte-identical with a person scope.
- `server/src/__tests__/agent-task-run-telemetry.test.ts` (embedded
Postgres): `agent.task_run` scope for creator, assigner, run owner, and
nobody; another company's task is never read.
- `server/src/__tests__/issue-telemetry-routes.test.ts`:
`agent.task_completed` scope for creator and assigner.
- `server/src/__tests__/heartbeat-process-recovery.test.ts`:
`agent.first_heartbeat` scope is the agent owner.
- `ui/src/components/OnboardingWizard.test.tsx`: a launch for the old
company that settles after a switch to another company does not end the
new analytics session.
- `ui/src/lib/analytics/onboarding-analytics.test.tsx`: each transition
fires once, held events drop on a person change, a stale opening step is
not a view, dismissal fires once, nothing is captured when analytics is
off or consent is `denied` or `ask`, and queued events keep their time.
- `ui/src/lib/analytics/product-analytics-events.test.ts` still passes
(the UI never captures a `PAPERCLIP_EVENTS` name).
- Local Cloud-mode run: an isolated instance (own Postgres, trusted
Cloud tenant headers, `PAPERCLIP_POSTHOG_HOST` set to a local capture
server, never real PostHog). A stub stood in for posthog-js and sent
through the `/_ph` proxy.
- A user created a task and assigned it to the agent. `agent.task_run`
arrived with `distinct_id: paperclip-id:local-user-1`, `attributed_via:
task_creator`, the raw `task_id`, and no `$process_person_profile`. (The
run itself failed locally because the Cloud runner is not available. The
event still shows the attribution.)
- `agent.first_heartbeat` arrived with the same person and
`attributed_via: run_owner`. `server.started` kept
`workspace:stack-local` with `attributed_via: none`.
- Headless Chromium walked the wizard: `onboarding_opened`
(create_agent), `onboarding_step_viewed` (create_agent),
`onboarding_step_completed` (create_agent), `onboarding_step_viewed`
(connect_model), `onboarding_step_completed` (connect_model, `api_key`),
`onboarding_step_viewed` (review), `onboarding_step_completed` (review),
`onboarding_step_completed` (launch, `succeeded`). Each fired once, with
the signed-in user as the distinct id. Events from before posthog-js
loaded arrived with their original time.
- A second walk left the onboarding page on the connect step and sent
one `onboarding_dismissed` (connect_model).

## Risks

- Low risk for self-hosted: the collector path never reads the new
scope, and a test checks the envelope bytes.
- Cloud: agent events move from the workspace person to a real person.
Insights that count `workspace:` distinct ids for these events will
change. `attributed_via` lets a query filter or split them.
- `task_assigner` uses the task's responsible user. Paperclip does not
store who assigned a task, so this is the person who owns or delegated
the task.
- Privacy: the new data is Cloud-only and uses ids that Cloud events
already carry. No new free text, email, or name goes on an event.
**Privacy review requested** for the Cloud attribution change (per
`rules/data-paths.mdc`). The generated contract does not change:
`attributed_via` is a Cloud-only property, like `stack_id` and
`user_id`.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## 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
- [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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 18:44:45 -06:00
DottaandClaude Opus 5.5 11d777b80f feat(server): fit PostHog proxy limits to busy Cloud stacks and make them configurable (#22243)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - On Paperclip Cloud, the board UI sends browser analytics to PostHog
through a same-origin proxy at `/_ph`
> - The proxy limits requests in flight: 16 per client address and 256
in total
> - Each open tab runs posthog-js, and one tab can have a few requests
in flight at once
> - On Railway without `TRUST_PROXY`, `req.ip` is the private edge hop,
so all visitors share one 16-request limit
> - This pull request raises the limits, makes them configurable, and
stops the per-client limit when `req.ip` is a shared private hop
> - The benefit is that busy stacks with many users and many tabs do not
lose analytics to 429 answers, and ops can see when a limit is hit

## Linked Issues or Issue Description

**Subsystem affected**
Server: the PostHog reverse proxy for Cloud browser analytics
(`server/src/routes/posthog-proxy.ts`).

**Problem or motivation**
The proxy limits are too low for busy Cloud stacks. One user with many
tabs can use 16 requests in flight. Behind the Railway edge without
`TRUST_PROXY`, `req.ip` is a private `100.64.x.x` hop, so all visitors
share one 16-request limit. The proxy then answers 429 and posthog-js
drops or delays events and replay uploads. Ops cannot change the limits
and cannot see when the proxy refuses requests.

**Proposed solution**
Raise the defaults to 128 per public client address and 1024 in total.
Read both limits from two environment variables with a strict parse and
a ceiling. When `req.ip` is not a public address, apply only the total
limit. Give each request a 60 second deadline. Log a warning at most
once a minute when the proxy refuses requests at a limit.

**Alternatives considered**
Find the visitor for the per-client limit from `X-Forwarded-For`. A
client can write that header, and an earlier security review asked the
proxy to keep `req.ip` as the key, so this change does not do that.
Scale the per-client limit for a shared hop. All visitors share the hop,
so a scaled limit is only a second total limit. The proxy applies the
total limit alone instead.

**Additional context**
Fleet operators can set the variables with an `env_config` campaign.
`doc/cloud-browser-analytics.md` tells how. Refs #22012 (the proxy) and
#22052 (visitor address behind a private hop).

## What Changed

- Raised `DEFAULT_POSTHOG_PROXY_LIMITS` to 128 requests in flight per
client address and 1024 in total. The 64 MiB body limit did not change.
- Added `PAPERCLIP_POSTHOG_PROXY_MAX_IN_FLIGHT` and
`PAPERCLIP_POSTHOG_PROXY_MAX_IN_FLIGHT_PER_CLIENT`.
`resolvePostHogProxyLimits` reads them where `resolvePostHogProxyMount`
builds the proxy. A value must be a whole number from 1 to 65536. An
invalid value logs a warning and uses the default. The server does not
stop.
- Added `posthogProxyClientKey`. It returns `req.ip` only when it is a
public address. For a private, carrier-grade NAT, loopback, link-local
or other reserved address, or no address, the proxy applies only the
total limit. The key never comes from a client header.
- Added `createPostHogProxyLimitReporter`. When the proxy answers 429,
it logs `PostHog proxy refused requests at its in-flight limit` at most
once a minute. The fields are the refusal counts per limit since the
last warning, the requests in flight, the limits and the time since the
last warning. The warning has no addresses. It uses no timer: it checks
the time when a refusal occurs.
- Added a request deadline of 60 seconds from the time the proxy accepts
a request. At the deadline, the proxy stops the request to PostHog and
closes the browser response, also when PostHog already finished and the
browser does not read the response. The slot is then free again. Before,
the 30 second upstream timeout was an idle timeout, so a slow body that
sent a byte at a time could hold a slot until the server request timeout
(300 seconds).
- The mount object now also returns the limits in use.
- Updated `doc/cloud-browser-analytics.md`: the limits, why these
defaults, the variables, the shared-hop behavior, the warning fields and
how to tune a fleet with an `env_config` campaign.

Why these defaults:

- 128 per address covers about 10 people behind one office network, each
with 4 tabs and 3 requests in flight per tab, with space left over.
- 1024 in total keeps memory bounded. The proxy streams bodies, so a
request holds two sockets and the stream buffers between them, not the
full body. In a local test on this branch, 1024 held requests added
about 96 MiB of resident memory with 4 KiB bodies and about 173 MiB with
256 KiB bodies (256 held requests with 4 KiB bodies: about 40 MiB).
These numbers include the test client and the test upstream in the same
process, so the proxy share is smaller. Operators can lower the limit
for small stacks.

## Verification

- `cd server && npx vitest run
src/__tests__/cloud-posthog-browser.test.ts`: 87 tests pass (5 runs in a
row).
- New tests:
- Defaults, values from the environment, an empty value, and invalid
values (`0`, `-5`, `1.5`, `1e3`, `12abc`, `abc`, `0x10`, `+8`, `65537`,
`1024000`, a value larger than a safe integer). `65536` is accepted.
Each invalid value keeps the default and warns once per variable.
  - The mount passes the configured limits to the proxy.
- Per-client limit for a public address (with `trust proxy` set): a
second request from the same address gets 429, a request from another
address gets 200.
- Shared private hop (no trusted proxy, peer is loopback): the
per-client limit does not apply, and the total limit still answers 429.
- A forged `X-Forwarded-For` does not select the bucket when no proxy is
trusted: three held requests with the same forged public address and a
per-client limit of 1 all get 200.
- Request deadline: an upstream that does not answer gives 502 at the
deadline and frees the slot, a body that trickles in is cut off at the
deadline, and a 16 MiB response that the browser does not read is closed
at the deadline.
- The tests wait until the held upstream receives each request, not for
a fixed time.
- Total limit across public addresses, and the reported reason (`total`
or `per_client`) for each 429.
- The warning rate limit: one warning for the first refusal, none in the
next 60 seconds, then one warning with the counts of the refusals in
between, and no addresses in any warning.
- Red/green: with the shared-hop rule removed (`posthogProxyClientKey`
returns `req.ip`), 9 of the new tests fail. With the deadline removed,
the 2 deadline tests fail. With both, all pass.
- `cd server && npx tsc --noEmit -p tsconfig.json`: passes.
- `pnpm verify`: exit 2, because `doc/cloud-browser-analytics.md` is a
global CI input. Required CI supplies the broad coverage.
- Memory numbers come from a local script that held 1024 requests
through the proxy against a local upstream (Node 26, macOS).

## Risks

- Higher limits let more requests use memory and sockets at once. The
worst case is bounded by the total limit, and operators can lower it
with `PAPERCLIP_POSTHOG_PROXY_MAX_IN_FLIGHT`.
- Behind a shared private hop, one client can use all of the total
limit, and other visitors then get 429. The request deadline frees each
slot after at most 60 seconds, but a client that sends again can keep
the limit full. Before this change, the same visitors shared a limit of
16, which one client could also fill. A separate limit for the hop would
not help the visitors behind it, because one client that fills it blocks
all of them. Setting `TRUST_PROXY` brings back the per-client limit.
- A PostHog request that takes longer than 60 seconds now fails with
502. posthog-js bodies are small and PostHog answers in well under a
second, so this does not affect normal traffic.
- If an operator sets `TRUST_PROXY` to trust every hop, `req.ip` comes
from the client's `X-Forwarded-For`. This was already true before this
change. The total limit still applies.
- The proxy is mounted only on Cloud with browser analytics on.
Self-hosted installs do not change.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

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

## 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 18:05:52 -06:00
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
DottaandClaude Opus 5.5 b56f240f45 feat(analytics): show session replay text by default, mask only customer content (#22057)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Hosted Paperclip Cloud records browser sessions with PostHog session
replay
> - Replay masked all text and showed only an allowlist of chrome, so
most replays showed only stars
> - The team cannot see how people use the board, and the allowlist
needed a review for each new label
> - The owner decided to show text by default and mask only marked
customer content, the way PostHog normally works
> - This pull request flips the default, removes the allowlist, and
marks every surface that can show connected-account content
> - The benefit is readable replays, while Google user data and Slack
data stay masked

## Linked Issues or Issue Description

**Subsystem affected**

Hosted Cloud browser analytics: PostHog session replay in the board UI
(`ui/src/lib/analytics/`).

**Problem or motivation**

Replay masked every text node. Only sidebar items and opt-in components
showed text. Replays were almost unreadable. Each new label needed an
`analyticsChrome` opt-in and an allowlist review.

**Proposed solution**

Record text as it is. Mask text only inside `ph-mask` (customer
content), `ph-no-capture` (secrets, blocked) and editable content. Add
`ANALYTICS_MASK_CLASS` to every surface that can show connected-account
content (Gmail, Calendar, Drive and Docs, Slack) or other free-form text
from agents or customers.

**Alternatives considered**

Keep "mask all" and grow the allowlist. This needs a review for each
label and still hides most of the board.

## What Changed

- `privacy.ts`: `ANALYTICS_MASK_TEXT_SELECTOR` is now `.ph-mask,
.ph-no-capture, [contenteditable]:not([contenteditable="false"])`. rrweb
masks a text node only when its parent or an ancestor matches the
selector. Removed `maskReplayText`, `isReplayTextRevealed`,
`ANALYTICS_UNMASK_ATTRIBUTE` and `ANALYTICS_UNMASK_PROPS`.
- `product-analytics.ts`: removed `maskTextFn`, so rrweb uses its
default star masking. `maskAllInputs`, `blockClass`, `maskAttributeFn`,
`mask_all_text` and `mask_all_element_attributes` do not change.
- Removed the `analyticsChrome` prop from `Button`, `Label`,
`TabsTrigger`, `EmptyState` and `SidebarNavItem`, and from all sidebar
call sites.
- Added `ANALYTICS_MASK_CLASS` to the content element (not the chrome)
of these surfaces:
- Link preview cards, task quicklook description, external object pills
and rows, related-work titles.
  - Email message cards and email send intents.
- Connected account names and email addresses (Browse, Connections, app
detail headers, app sidebar, connection choice list, connection access
and repair cards), GitHub login and repositories, Slack workspace names,
chat channel and linked user labels.
- Inbox and decision rows (subject and detail), obligation evidence,
Needs You notes and receipts, decision options and result summaries, and
the interaction card roots (questions, options, answers, tool action
requests, suggested tasks).
- Approval payloads, action card input and reason, recovery card
headline, evidence and options, run ledger retry detail, interrupt
handoff previews.
- Run transcripts, run failure details and run events on the agent page.
- Search result snippets, toast bodies, voice and call transcripts, case
summary, files and fields, attachment previews, artifact previews (text,
tables, patches and documents).
- Replaced `unmask-allowlist.test.ts` with `replay-masking.test.tsx`. It
checks that unmarked chrome records as it is, that each marker masks,
that a rendered voice transcript and run transcript mask, that each
surface above has the class, and that autocapture records no element
text. Updated `privacy.test.ts`, `shared-chrome.test.tsx` and
`product-analytics.test.ts`.
- Updated `doc/cloud-browser-analytics.md`: new default, marker classes,
masked surfaces, and residual risk.

## Verification

- `pnpm exec vitest run src/lib/analytics` in `ui/`: 83 tests pass.
- Vitest for the 48 test files next to the changed components: 994 tests
pass.
- `tsc --noEmit -p ui/tsconfig.json`: no new errors (only the existing
generated Storybook catalog errors).
- `pnpm verify` exits 2 because a doc is a global CI input. Required CI
supplies the broad coverage.
- Manual: I ran an isolated local instance with a Cloud-like browser
analytics config. `PAPERCLIP_POSTHOG_HOST` pointed to a local capture
server, not PostHog. I opened a task page in headless Chromium, hovered
a GitHub pull request link, and decoded the captured `/s/` replay
payloads:
- Clear text: sidebar (`New task`, `Chat`, `Tasks`, `Inbox`, `More`),
breadcrumb, task title `Quarterly launch checklist`, `REP-1`, the
Connectors promo heading and button.
- Masked (stars only): the markdown task body, the chat comment, the
link preview card (pull request title, author, URL, status), and the
company menu.
- Marker strings in the body, comment and preview never appeared in
clear text in any payload.
- The page `<title>` (task title and company name) is in the replay
head. This is accepted residual risk.

## Risks

- Text that is not marked is now recorded. Task titles, agent names,
project names, company names, routine names, artifact and document
titles, and activity rows are visible in replays. The owner accepted
this. An agent can copy email or Slack text into a task title.
- A new surface that shows connected-account content without
`ANALYTICS_MASK_CLASS` is recorded until somebody marks it.
`replay-masking.test.tsx` and the doc list the marked surfaces.
- The masking options in `posthog.init` take precedence over the PostHog
project masking settings (posthog-js 1.450), so a dashboard change
cannot unmask content. Keep the project settings empty to avoid a
console warning.
- Some masked areas also mask nearby fixed labels (for example the
interaction card buttons). This is safe.
- Analytics is off on self-hosted and local installs, so they see no
change.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude Opus 5.5 (claude-opus-5-5), Anthropic, with tool use and code
execution in Claude Code.

## 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-17 15:18:50 -06:00
DottaandClaude Opus 5.5 fa8bc78d2a fix(posthog-proxy): forward the visitor IP behind a private proxy hop (#22052)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Paperclip Cloud sends browser analytics to PostHog through a
same-origin proxy at `/_ph`
> - On Cloud, the server runs behind Railway's private proxy hop and
`TRUST_PROXY` is not set
> - So the proxy forwarded the hop address (100.64.x.x) to PostHog
instead of the visitor's IP
> - PostHog could not resolve a location, and every visitor shared one
per-client in-flight bucket
> - This pull request makes the proxy use the first `X-Forwarded-For`
entry when the socket peer is private
> - The benefit is correct visitor location in PostHog web analytics and
per-visitor limits that work on Cloud

## Linked Issues or Issue Description

**What happened?**
On Paperclip Cloud staging, every browser event that reaches PostHog
through the `/_ph` proxy has `$ip` set to a Railway private address
(100.64.0.5 to 100.64.0.21). PostHog shows no country or city. All
visitors also share a few per-client in-flight buckets.

**Expected behavior**
PostHog receives the visitor's own IP, so web analytics shows visitor
location. Each visitor gets its own in-flight bucket.

**Steps to reproduce**
1. Turn on browser analytics on a Cloud stack
(`PAPERCLIP_POSTHOG_BROWSER_ENABLED=1`) without `TRUST_PROXY`.
2. Load the board and navigate a few pages.
3. In PostHog, query `properties.$ip` for those `$pageview` events. The
value is a 100.64.x.x address and there is no geo data.

**Deployment mode**
Paperclip Cloud (authenticated, hosted on Railway).

## What Changed

- Add `posthogVisitorIp()` in `server/src/routes/posthog-proxy.ts`.
- Use it for the forwarded `X-Forwarded-For` header and for the
per-visitor in-flight limit.
- Add tests for the helper and for the forwarded header.

## Verification

- `npx vitest run src/__tests__/cloud-posthog-browser.test.ts` (server):
51 pass.
- Red check: with the old proxy code, the new tests fail (11 failures).
- Reproduced on paperclip.staging.paperclip.app: PostHog `$ip` values
were 100.64.0.5 to 100.64.0.21, with no location.

## Risks

- A client can set its own `X-Forwarded-For`. This only changes its own
analytics location and its per-visitor bucket. The global in-flight
limit still applies.
- The proxy is mounted only on Cloud with browser analytics on, so
self-hosted installs are not affected.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use.

## 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-17 14:18:45 -06:00
DottaandClaude Opus 5.5 8172d27089 feat(cloud): browser product analytics through a same-origin PostHog proxy (#22012)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Paperclip Cloud runs the same app for hosted customers, and the same
UI ships in the npm package.
> - The PostHog project for Cloud gets only server events today. It has
no page views, sessions, replays or people.
> - So the Product and Web analytics pages are empty, and we cannot see
how Cloud users move through the board.
> - This pull request adds browser analytics for Cloud only. It is off
until an operator sets two switches on a Cloud stack.
> - Self-hosted installs do not change: they never download posthog-js
and never serve the PostHog proxy.
> - The benefit is real page views, sessions, heatmaps, Web Vitals and
masked session replays for Cloud, linked to the user and the workspace.

## Linked Issues or Issue Description

**Subsystem affected**
Board UI (analytics bootstrap and privacy markers), server session
payload and a new same-origin proxy route, shared validators.

**Problem or motivation**
Cloud sends only server events to PostHog. There is no browser SDK, so
PostHog has no page views, sessions, replays or identified people for
Cloud. We cannot see where Cloud users get stuck.

**Proposed solution**
The signed-in session gives the UI a PostHog config only on a
Cloud-managed stack with `PAPERCLIP_POSTHOG_PROJECT_TOKEN` and
`PAPERCLIP_POSTHOG_BROWSER_ENABLED=1`. The UI loads posthog-js after the
page settles. Events go through a strict same-origin proxy at `/_ph`, so
ad blockers do not drop them. Replay masks all text and all inputs by
default.

**Alternatives considered**
Bake a key into the UI build: refused, because the same build ships to
self-hosted users. A generic reverse proxy: refused, because it would
forward any path. Mask only content areas: refused, because a missed
surface would leak; masking is deny by default.

**Additional context**
This is the browser part of the Cloud direct PostHog plan. The server
direct sender is already on master (#22006). Fleet configuration is a
separate change. PostHog person deletion on account deletion is a
follow-up.

## What Changed

- Uses the shared Cloud PostHog config (`resolveCloudPostHogConfig` in
`server/src/services/cloud-posthog-config.ts`, already on master from
the server direct-sending change). This PR does not change it.
- `server/src/services/cloud-posthog-browser.ts`:
`resolveBrowserAnalyticsConfig` returns `{ token, apiHost: "/_ph",
uiHost, environment, stackId, replayEnabled }` only when
`PAPERCLIP_POSTHOG_BROWSER_ENABLED=1`. `environment` is always set: the
explicit variable, else `staging` for a `*.staging.paperclip.app` host,
else `production`.
- `GET /api/auth/get-session` carries the new optional
`browserAnalytics` field (the existing signed-in bootstrap request, so
no new request on the cold path). `packages/shared` has
`browserAnalyticsConfigSchema` and the session schema field.
- `server/src/routes/posthog-proxy.ts`: a strict proxy, mounted before
the body parsers and only when browser analytics is on. It forwards only
these requests and answers 404 to all others without contacting PostHog:
- `POST /e/`, `/i/v0/e/`, `/batch/`, `/s/`, `/flags/`, `/decide/` to the
ingest host.
- `GET /array/<token>/config(.js)` and `GET
/static/[<version>/]<name>.js` to the assets host (derived from the
ingest host).
- `stream.pipeline` joins the streams, so an error on either side
(PostHog closes the connection partway through a response, or the
browser goes away) closes both and never goes unhandled. It builds a new
header set from an allowlist plus `X-Forwarded-For`. It never forwards
the inbound Host, Cookie or Authorization headers. It drops `Set-Cookie`
from responses. Bodies stream; nothing is buffered. It refuses bodies
over 64 MiB (413, also for chunked bodies that grow past the limit) and
limits requests in flight to 16 per client address and 256 in total
(429).
- `ui/src/lib/analytics/product-analytics.ts` (the only module that
talks to posthog-js) and `ui/src/components/ProductAnalyticsGate.tsx`:
- posthog-js loads after the page settles (or at a 15 s deadline), only
when the session has a config. It loads as PostHog's browser script
`/_ph/static/array.js` through the proxy, the same way posthog-js itself
loads its extensions (recorder, web vitals). It is not an npm dependency
and is in no bundle chunk.
- Init: page views on history change, page leave, autocapture, Web
Vitals, heatmaps, `person_profiles: "identified_only"`,
`tracing_headers` for our own host only, replay only when
`replayEnabled`. Surveys, product tours, web experiments and
conversations are off.
- Super properties on every event: `deployment_source: "cloud"` and
`environment`.
- After sign-in: `identify(session.userId, { email, name })` (person
properties only). `session.userId` is the authenticated actor's user id
verbatim (for example `paperclip-id:...`): `GET /api/auth/get-session`
copies `req.actor.userId` into it, and server events use that same actor
id as `distinct_id`, so browser and server events land on one person.
Tests: `auth-routes.test.ts` (the session returns the actor id verbatim)
and `ProductAnalyticsGate.test.tsx` (identify uses it) and
`group("workspace", stackId)`. On sign-out: `reset()`, then the super
properties again. `useSignOut` calls it before it leaves the page,
because Cloud sign-out navigates away while the session query is still
populated.
- Privacy (`ui/src/lib/analytics/privacy.ts`), deny by default:
- Replay masks every text node (`maskTextSelector: "*"` with
`maskTextFn`) and every input value (`maskAllInputs`).
- Only elements with `ANALYTICS_UNMASK_PROPS` show their text: sidebar
items whose label is a fixed string (`analyticsChrome`, added at the 99
call sites with literal labels), and a shared `Button`, `Label`,
`TabsTrigger` or `EmptyState` only when its caller passes
`analyticsChrome`. None of them opts in by default, because they also
render customer text (agent names, document titles). Sidebar items with
dynamic labels (recent tasks, agents, projects) stay masked.
- Replay masks attribute values too (`maskAttributeFn`, deny by
default). Only layout attributes (`class`, `style`, `role`,
`data-state`, SVG geometry), rrweb metadata and stylesheet links keep
their values. `title`, `aria-label`, `alt`, `placeholder`, `src`,
`href`, `data-*` and element references (`id`, `for`, `aria-labelledby`,
`aria-describedby`, `aria-controls`, which often embed names or slugs)
are always masked, even on unmasked chrome. So the organization
switcher's `aria-label`, task titles in `title` attributes, image
sources and download links with file paths never reach a replay.
- `before_send` (`scrubCapturedEvent`) drops the `title` property from
every event, because posthog-js copies `document.title` (task and
organization names) into page views. Every URL string in every event,
including replay meta events, keeps only its origin and path: query and
hash values never leave (they can hold tokens, `code`/`state`, file
paths or search text), and the token segment of `/board-claim/<token>`
and `/invite/<token>` is redacted. It recurses only into plain objects
and arrays, so the `Date` timestamp stays intact.
- `ANALYTICS_MASK_CLASS` keeps customer content masked even inside
unmasked chrome: `MarkdownBody` (task and issue bodies, comments, chat
messages, documents and artifact markdown), `MarkdownEditor`, the task
chat thread, the issue chat thread, the comment timeline, the file
viewer (source, markdown and CSV views) and the organization name in the
organization switcher. Text in any `contenteditable` editor is always
masked.
- `ANALYTICS_NO_CAPTURE_CLASS` (`ph-no-capture`, a blank box in replay)
on every password-type `Input` (about 40 secret, token and API key
fields), environment variable values and new secret values.
- Autocapture never records element text or attribute values
(`mask_all_text`, `mask_all_element_attributes`).
- Connected-account content (Google user data and Slack data: email
bodies, calendar events, Slack messages in tasks, chat, tool results,
previews) never appears unmasked in a replay. Replay masks all text by
default; nothing that renders connected-account content is in the unmask
allowlist; autocapture records no element text anywhere
(`mask_all_text`). `ui/src/lib/analytics/unmask-allowlist.test.ts` pins
the allowlist: only 7 files may spread the unmask attribute, sidebar
opt-ins need a literal label, and any `analyticsChrome` opt-in on
`Button`/`Label`/`TabsTrigger`/`EmptyState` fails until it is added to a
reviewed list (empty today). The same test renders Gmail, Calendar and
Slack-style tool results next to unmasked navigation and checks they are
masked.
- Guard test: UI code must never call `capture()` with a
`PAPERCLIP_EVENTS` name, so each event has one sender.
- Docs: `doc/cloud-browser-analytics.md` (switches, per-stack opt-out,
proxy allowlist, identity, privacy) and a link from
`doc/observability.md`.
- No new npm dependency and no lockfile change: posthog-js comes from
PostHog through the proxy at run time. (An earlier revision added
`posthog-js` to `ui/package.json`; the Runner support suite requires
every `ui` dependency in the reviewed lockfile, which a pull request
cannot update, so the script approach replaced it.)

## Verification

- `pnpm verify`: see the result below.
- Focused tests:
- `server/src/__tests__/cloud-posthog-browser.test.ts`: exposure matrix
(self-hosted with every switch set, Cloud without token, without stack
ID, without the browser switch, switch not `1`, enabled, replay off),
environment fallback, proxy mount only when enabled, allowed routes, 404
for disallowed methods and paths (including `//host` and `..` paths)
with no upstream contact, Host/Cookie/Authorization stripped,
`Set-Cookie` dropped, 502 when PostHog is down, and no unhandled error
when PostHog closes a response partway (red on the old `pipe()` code,
green now).
- `server/src/__tests__/auth-routes.test.ts`: the session carries
`browserAnalytics` only on Cloud with the token and the switch.
- `ui/src/lib/analytics/*.test.ts`,
`ui/src/components/ProductAnalyticsGate.test.tsx`: no import of
posthog-js without a config or when signed out; load after the page
settles, once; identify, group, reset with a mocked posthog; email and
name never become event properties; deny-by-default replay masking;
guard test.
- Real run (local, headless Chromium, production UI build, never the
real PostHog project):
- Self-hosted server, no env: 0 requests for PostHog's script and 0
requests to `/_ph` in 9 cold loads and in a 40 s session with
navigation. `browserAnalytics` is `null`. `/_ph/e/` falls through to the
UI.
- Cloud config: a full Cloud boot needs S3, a managed database and the
control plane. So a small local stand-in served the same production UI
build, mounted the real proxy from `server/src/routes/posthog-proxy.ts`,
added the real `resolveBrowserAnalyticsConfig()` output to the session,
and forwarded other API calls to the local server.
`PAPERCLIP_POSTHOG_HOST` pointed at a local capture server.
- Captured through `/_ph` only (0 requests to any posthog.com host):
`$pageview` on each client navigation (5), `$identify` with `$set: {
email, name }`, `$groupidentify`, `$groups: { workspace: <stack id> }`
on events, `environment` and `deployment_source` on every event,
`$web_vitals`, `$autocapture` with no `$el_text`, `$$heatmap`, and 10
`$snapshot` replay events. A search of every decoded `/e/` and `/s/`
payload (events, replay text and replay attributes) found the email only
in `$identify`'s `$set`, and found none of: the task body, the typed
comment, the task title, the organization name. No Cookie header reached
the capture server. 96 of 113 API requests carried
`X-POSTHOG-SESSION-ID` (the others ran before posthog-js loaded).
- Client-side visits to `/invite/INVITESECRET123` and
`/cli-auth/abc?token=CLISECRET456` reached PostHog as `/invite/REDACTED`
and `/cli-auth/abc` (no query); neither secret was in any payload.
- Disallowed proxy requests (`PUT /_ph/e/`, `GET /_ph/api/projects/`,
`POST /_ph/static/x.js`) answered 404.
- Sample replay payload (decoded rrweb text nodes from a captured `/s/`
request). The task body, the typed comment, the task title, the
organization name and the email were not in any replay payload:

```json
{"text_nodes": [
  {"parentTag": "title", "textContent": "****** ** * *********"},
  {"parentTag": "a",     "textContent": "**** ** **** *******"},
  {"parentTag": "span",  "textContent": "****** **"},
  {"parentTag": "span",  "textContent": "*** ****"},
  {"parentTag": "span",  "textContent": "Tasks"},
  {"parentTag": "span",  "textContent": "Inbox"},
  {"parentTag": "h2",    "textContent": "******* *******"},
  {"parentTag": "p",     "textContent": "****** *** * ******* ** ******"}
]}
```

- Cold load, 9 fresh-profile loads each, median, same stand-in with
analytics off and on:

| | DOMContentLoaded | Board content visible |
| --- | --- | --- |
| Analytics off | 128 ms | 336 ms |
| Analytics on | 126 ms | 334 ms |

Final head. The difference is inside run-to-run noise (earlier pairs:
332/335 ms and 335/348 ms). PostHog's script loads only after the
content is visible.

## Risks

- Inert by default. Without a Cloud-managed stack, a project token, a
stack ID and `PAPERCLIP_POSTHOG_BROWSER_ENABLED=1`, the session field is
`null`, the proxy is not mounted and no analytics code runs. The OSS
package does not change behavior.
- Per-stack opt-out: `PAPERCLIP_POSTHOG_REPLAY_ENABLED=0` turns replay
off; unsetting `PAPERCLIP_POSTHOG_BROWSER_ENABLED` turns all browser
analytics off. Both apply on the next restart.
- Replay text shown in the clear comes only from fixed sidebar labels
and from shared components whose caller opts in. Today no `Button`,
`Label`, `TabsTrigger` or `EmptyState` call site opts in, so replays
show layout, clicks and navigation with most copy masked. Opting in
fixed-label call sites is a follow-up. Review sample replays on staging
before production.
- Image `src` values are masked, so images record as empty boxes.
Sandboxed iframes (HTML artifacts, MCP apps) also record as empty boxes.
Replays therefore show layout and product copy, not customer media.
- PostHog's script is not version-pinned: the assets host serves its
current browser build, as for any PostHog snippet install, and
posthog-js already loads its extensions from that host at run time. It
runs only on Cloud stacks with the browser switch on.
- The proxy needs no sign-in, like PostHog's documented proxies:
posthog-js sends some events while a page unloads, and the proxy can
only reach the two PostHog hosts, on the listed paths, with the public
project token. Body size and in-flight limits bound the load one client
can add.
- posthog-js rejects bots (including headless browsers) on its own,
which is the wanted production behavior.
- `SidebarNavItem.production.tsx`, `Sidebar*.tsx` and the shared `ui/*`
components changed by one attribute each; no visual change.

## Model Used

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

## 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-17 11:23:03 -06:00