mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-22 11:54:35 +01:00
## 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>
119 lines
12 KiB
TypeScript
119 lines
12 KiB
TypeScript
import { useState } from "react";
|
||
import { useMutation } from "@tanstack/react-query";
|
||
import { SUBSCRIPTION_CURRENCIES, centsToUsd, usdToCents, type SubscriptionAccountReport, type SubscriptionCostReport, type SubscriptionUsage } from "@paperclipai/shared";
|
||
import { subscriptionsApi } from "../api/subscriptions";
|
||
import { cn, formatCents, formatDateTime, formatTokens, providerDisplayName } from "../lib/utils";
|
||
import { Button } from "./ui/button";
|
||
import { Badge } from "./ui/badge";
|
||
import { Card } from "./ui/card";
|
||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "./ui/dialog";
|
||
import { Input } from "./ui/input";
|
||
import { Label } from "./ui/label";
|
||
import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy";
|
||
|
||
export function subscriptionMoney(cents: string, currency: string) {
|
||
return currency === "USD" ? formatCents(Number(cents))
|
||
: new Intl.NumberFormat(undefined, { style: "currency", currency, currencyDisplay: "code" }).format(Number(cents) / 100);
|
||
}
|
||
|
||
export function SubscriptionTokenUsage({ usage }: { usage: SubscriptionUsage }) {
|
||
return <span className="font-mono text-xs text-muted-foreground">
|
||
{formatTokens(usage.inputTokens + usage.cachedInputTokens)} in · {formatTokens(usage.outputTokens)} out
|
||
{usage.cachedInputTokens > 0 && <span className="block">{formatTokens(usage.cachedInputTokens)} input cached</span>}
|
||
</span>;
|
||
}
|
||
|
||
function SubscriptionEditor({ account, accounts, companyId, onDone }: {
|
||
account: SubscriptionAccountReport; accounts: SubscriptionAccountReport[]; companyId: string; onDone: () => void;
|
||
}) {
|
||
const [plan, setPlan] = useState(account.price.plan);
|
||
const [amount, setAmount] = useState(account.price.amountCents == null ? "" : centsToUsd(account.price.amountCents).replace(/\.?0+$/, ""));
|
||
const [currency, setCurrency] = useState(account.price.currency);
|
||
const [cadence, setCadence] = useState(account.price.cadence);
|
||
const [status, setStatus] = useState(account.price.status);
|
||
const [targetId, setTargetId] = useState("");
|
||
const save = useMutation({ mutationFn: () => subscriptionsApi.update(companyId, account.id, {
|
||
expectedRevision: account.price.revision, plan, amountCents: amount.trim() ? usdToCents(amount.trim()) : null,
|
||
currency: currency as typeof SUBSCRIPTION_CURRENCIES[number], cadence, status,
|
||
}), onSuccess: onDone });
|
||
const link = useMutation({ mutationFn: () => subscriptionsApi.link(companyId, account.id, targetId, account.price.revision,
|
||
accounts.find(row => row.id === targetId)!.price.revision), onSuccess: onDone });
|
||
const targets = accounts.filter(row => row.id !== account.id && row.provider === account.provider && row.canEdit);
|
||
const busy = save.isPending || link.isPending;
|
||
const selectClass = "h-9 rounded-md border border-input bg-background px-3 text-sm";
|
||
return <div className="space-y-5">
|
||
<form className="space-y-4" onSubmit={event => { event.preventDefault(); save.mutate(); }}>
|
||
<div className="space-y-2"><Label htmlFor="subscription-plan">Plan</Label><Input id="subscription-plan" value={plan} onChange={event => setPlan(event.target.value)} required maxLength={100} /></div>
|
||
<div className="grid gap-4 sm:grid-cols-2">
|
||
<div className="space-y-2"><Label htmlFor="subscription-price">Price per billing period</Label><Input id="subscription-price" type="number" min="0" step="any" value={amount} placeholder="Unknown" onChange={event => setAmount(event.target.value)} /></div>
|
||
<div className="space-y-2"><Label htmlFor="subscription-currency">Currency</Label><select id="subscription-currency" className={selectClass} value={currency} onChange={event => setCurrency(event.target.value)}>{SUBSCRIPTION_CURRENCIES.map(code => <option key={code}>{code}</option>)}</select></div>
|
||
<div className="space-y-2"><Label htmlFor="subscription-cadence">Billed</Label><select id="subscription-cadence" className={selectClass} value={cadence} onChange={event => setCadence(event.target.value as typeof cadence)}><option value="month">Monthly</option><option value="year">Annually</option></select></div>
|
||
<div className="space-y-2"><Label htmlFor="subscription-status">Tracking</Label><select id="subscription-status" className={selectClass} value={status} onChange={event => setStatus(event.target.value as typeof status)}><option value="active">Active</option><option value="ended">Subscription ended</option><option value="excluded">Exclude from this organization</option></select></div>
|
||
</div>
|
||
<p className="text-xs text-muted-foreground">Enter the full amount for one account or seat. Annual prices are divided by 12. Changes apply from now. Ending tracking here does not cancel your provider subscription.</p>
|
||
{save.error && <p role="alert" className="text-sm text-destructive">Could not save this price. Check the amount, or reopen the account if another person updated it.</p>}
|
||
<div className="flex items-center justify-between"><Button type="button" variant="ghost" disabled={busy} onClick={onDone}>Cancel</Button><Button type="submit" disabled={busy}>{save.isPending ? "Saving…" : "Save price"}</Button></div>
|
||
</form>
|
||
{targets.length > 0 && <div className="space-y-2 border-t border-border pt-4">
|
||
<Label htmlFor="subscription-link">Same subscription as another account?</Label>
|
||
<select id="subscription-link" className={cn(selectClass, ANALYTICS_MASK_CLASS)} value={targetId} onChange={event => setTargetId(event.target.value)}><option value="">Choose an account</option>{targets.map(row => <option key={row.id} value={row.id}>{row.name} · {row.price.plan}</option>)}</select>
|
||
<p className="text-xs text-muted-foreground">Linking counts these accounts once, combines their Paperclip usage, and keeps the selected account’s price. Only link the same subscription or paid seat.</p>
|
||
{link.error && <p role="alert" className="text-sm text-destructive">Could not link these accounts. Reopen their details and try again.</p>}
|
||
<Button type="button" variant="outline" disabled={!targetId || busy} onClick={() => link.mutate()}>Link accounts</Button>
|
||
</div>}
|
||
</div>;
|
||
}
|
||
|
||
export function SubscriptionCostCard({ companyId, report, error, onChanged }: {
|
||
companyId: string; report?: SubscriptionCostReport; error?: unknown; onChanged: () => void;
|
||
}) {
|
||
const [open, setOpen] = useState(false);
|
||
const [editing, setEditing] = useState<SubscriptionAccountReport | null>(null);
|
||
const closeEditor = () => { setEditing(null); onChanged(); };
|
||
const known = report?.monthlyTotals.length;
|
||
const estimatedCount = report?.monthlyTotals.reduce((sum, total) => sum + total.estimatedCount, 0) ?? 0;
|
||
return <>
|
||
<Card className="block p-4">
|
||
<div className="text-(length:--text-micro) uppercase tracking-(--tracking-eyebrow) text-muted-foreground">Subscriptions</div>
|
||
<div className="mt-2 font-mono text-2xl font-semibold tabular-nums">
|
||
{known ? report!.monthlyTotals.map(total => <div key={total.currency}>{subscriptionMoney(total.amountCents, total.currency)}<span className="text-sm font-normal">/month</span></div>) : report && report.activeCount === 0 && report.accounts.length > 0 ? "$0.00/month" : "—"}
|
||
</div>
|
||
<div className="mt-1 space-y-1 text-xs text-muted-foreground">
|
||
{report ? <>
|
||
{estimatedCount > 0 && <div><Badge variant="outline" className="font-normal text-muted-foreground">{estimatedCount < report.activeCount - report.unknownPriceCount ? "Partially estimated" : "Estimated"}</Badge></div>}
|
||
{report.unknownPriceCount > 0 && !!known && <div>Known monthly subtotal</div>}
|
||
<div>{report.accounts.length === 0 ? "No visible subscriptions" : <>{report.activeCount} active {report.activeCount === 1 ? "subscription" : "subscriptions"}{report.unknownPriceCount > 0 && ` · ${report.unknownPriceCount} ${report.unknownPriceCount === 1 ? "price" : "prices"} unknown`}</>}</div>
|
||
{report.accounts.length > 0 && <div>Monthly fees for accounts visible to you</div>}
|
||
{report.unidentifiedAccountCount > 0 && <div>{report.unidentifiedAccountCount} unconfirmed {report.unidentifiedAccountCount === 1 ? "account identity" : "account identities"}</div>}
|
||
<SubscriptionTokenUsage usage={report.subscription} />
|
||
</> : error ? <div>Subscription data is unavailable.</div> : <div>Loading subscriptions…</div>}
|
||
{report && error ? <div>Showing last loaded subscription data.</div> : null}
|
||
</div>
|
||
<Button variant="link" size="sm" className="h-auto p-0" onClick={() => setOpen(true)} disabled={!report}>View details</Button>
|
||
</Card>
|
||
<Dialog open={open} onOpenChange={value => { setOpen(value); if (!value) setEditing(null); }}>
|
||
<DialogContent className="max-h-(--sz-80vh) overflow-y-auto sm:max-w-3xl">
|
||
<DialogHeader><DialogTitle>{editing ? "Subscription price" : "Subscriptions"}</DialogTitle><DialogDescription>Current monthly costs for accounts visible to you. Token totals cover company work in the selected period.</DialogDescription></DialogHeader>
|
||
{editing ? <SubscriptionEditor key={editing.id} companyId={companyId} account={editing} accounts={report?.accounts ?? []} onDone={closeEditor} /> : <div className="space-y-4">
|
||
{report?.accounts.length === 0 && <p className="text-sm text-muted-foreground">No subscriptions are visible to you yet. Connect an AI account or run an agent with a connected subscription.</p>}
|
||
{report?.accounts.map(account => <div key={account.id} className="space-y-2 border-b border-border pb-4 last:border-0">
|
||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||
<div className={ANALYTICS_MASK_CLASS}><div className="font-medium">{account.name}</div><div className="text-xs text-muted-foreground">{account.shared ? "Shared" : account.ownerName ?? (account.ownerUserId ? "Account owner" : "Personal accounts")} · {providerDisplayName(account.provider)} · {account.price.plan}</div></div>
|
||
<div className="text-right"><div className="font-mono">{account.price.status !== "active" ? account.price.status === "ended" ? "Ended" : "Excluded" : account.price.monthlyCents == null ? "Price unknown" : `${subscriptionMoney(account.price.monthlyCents, account.price.currency)}/month`}</div><div className="text-xs text-muted-foreground">{account.price.source === "catalog" ? "Estimated · before tax" : account.price.source === "user" ? "User supplied" : ""}{account.price.cadence === "year" ? " · annual payment ÷ 12" : ""}</div></div>
|
||
</div>
|
||
<SubscriptionTokenUsage usage={account.usage} />
|
||
{Number(account.usage.costCents) > 0 && <div className="text-xs text-muted-foreground">{formatCents(Number(account.usage.costCents))} recorded usage charges in selected period, separate from the subscription fee.</div>}
|
||
{account.agents.length > 0 && <div className="text-xs text-muted-foreground">Used by {account.agents.map(agent => agent.name).join(", ")}</div>}
|
||
{!account.identityVerified && <p className="text-xs text-muted-foreground">Account identity is unconfirmed. Link duplicates if these connections use the same subscription.</p>}
|
||
{account.observedAt && <div className="text-xs text-muted-foreground">Plan checked {formatDateTime(account.observedAt)}{account.refreshStatus === "unavailable" ? " · latest check unavailable" : ""}</div>}
|
||
{account.refreshStatus === "unavailable" && !account.observedAt && <p className="text-xs text-muted-foreground">The provider did not make plan details available. You can enter the price yourself.</p>}
|
||
{account.canEdit && <div><Button variant="outline" size="sm" onClick={() => setEditing(account)}>Edit price</Button></div>}
|
||
</div>)}
|
||
{!!report?.unattributedSubscription.eventCount && <p className="text-xs text-muted-foreground">Some subscription usage has no recorded account. It is included in the subscription token total.</p>}
|
||
<p className="text-xs text-muted-foreground">Monthly fees cover the whole account, including use outside Paperclip. They are separate from recorded charges and agent budgets. Currencies are totaled separately.</p>
|
||
</div>}
|
||
</DialogContent>
|
||
</Dialog>
|
||
</>;
|
||
}
|