Files
PaperClipAI/ui/src/components/CaseFieldsPanel.tsx
T
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

379 lines
13 KiB
TypeScript

import { Fragment, useCallback, useEffect, useRef, useState, type ReactNode } from "react";
import { Check } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Card } from "@/components/ui/card";
import { IssueReferencePill } from "@/components/IssueReferencePill";
import { Link, useCaseHref } from "@/lib/router";
import { copyTextToClipboard } from "@/lib/clipboard";
import { cn } from "@/lib/utils";
import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy";
// -----------------------------------------------------------------------------
// CaseFieldsPanel (PAP-12968 §3) — the generic key-value renderer for a case's
// `fields` JSON blob. The server stores arbitrary agent-authored JSON, so the UI
// renders by *value type* (Postel's law: never crash on unexpected shapes) and
// preserves the skill's key insertion order (does NOT alphabetize).
// -----------------------------------------------------------------------------
const URL_RE = /^https?:\/\/\S+$/i;
const CASE_ID_RE = /^[A-Z][A-Z0-9]*-C\d+$/;
const ISSUE_ID_RE = /^[A-Z][A-Z0-9]*-\d+$/;
const ISSUE_ID_IN_TEXT_RE = /\b[A-Z][A-Z0-9]*-\d+\b/g;
function isPlainObject(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
/** A muted em-dash for null / empty / missing values. */
function EmptyValue() {
return <span className="text-muted-foreground">—</span>;
}
function isIssueIdentifierField(fieldKey: string | undefined): boolean {
if (!fieldKey) return false;
const normalized = fieldKey.toLowerCase().replace(/[^a-z0-9]/g, "");
return normalized.includes("issueidentifier") || normalized.includes("taskidentifier");
}
function stringifyCopyValue(value: unknown): string {
if (typeof value === "string") return value;
if (typeof value === "number" || typeof value === "boolean") return String(value);
return JSON.stringify(value, null, 2);
}
function extractIssueIdentifiers(value: unknown, fieldKey?: string): string[] {
if (!isIssueIdentifierField(fieldKey)) {
return typeof value === "string" && ISSUE_ID_RE.test(value.trim()) ? [value.trim()] : [];
}
const identifiers: string[] = [];
const add = (candidate: unknown) => {
if (typeof candidate !== "string") return;
for (const match of candidate.matchAll(ISSUE_ID_IN_TEXT_RE)) identifiers.push(match[0]);
};
if (Array.isArray(value)) value.forEach(add);
else add(value);
return [...new Set(identifiers)];
}
function IssueIdentifierValue({ identifiers }: { identifiers: string[] }) {
return (
<span className="flex min-w-0 flex-wrap items-center gap-1.5">
{identifiers.map((identifier) => (
<IssueReferencePill
key={identifier}
issue={{ id: identifier, identifier, title: identifier }}
/>
))}
</span>
);
}
function CopyableCompactValue({
value,
children,
className,
}: {
value: unknown;
children: ReactNode;
className?: string;
}) {
const text = stringifyCopyValue(value);
const [copied, setCopied] = useState(false);
const timerRef = useRef<ReturnType<typeof setTimeout>>(undefined);
useEffect(() => () => clearTimeout(timerRef.current), []);
const handleCopy = useCallback(() => {
void copyTextToClipboard(text).then(() => {
setCopied(true);
clearTimeout(timerRef.current);
timerRef.current = setTimeout(() => setCopied(false), 1500);
});
}, [text]);
return (
<span className="relative inline-flex min-w-0 max-w-full">
<button
type="button"
className={cn("min-w-0 max-w-full cursor-copy truncate text-left transition-colors hover:text-foreground", className)}
title={text}
onClick={handleCopy}
>
{children}
</button>
{copied ? (
<span
role="status"
aria-live="polite"
className="pointer-events-none absolute bottom-full left-1/2 mb-1.5 inline-flex -translate-x-1/2 items-center gap-1 rounded-md bg-foreground px-2 py-1 text-xs whitespace-nowrap text-background"
>
<Check className="h-3 w-3 shrink-0" />
Copied
</span>
) : null}
</span>
);
}
function StringValue({ value, variant }: { value: string; variant: "compact" | "full" }) {
const caseHref = useCaseHref();
const trimmed = value.trim();
if (trimmed === "") return <EmptyValue />;
if (URL_RE.test(trimmed)) {
return (
<a
href={trimmed}
target="_blank"
rel="noreferrer"
className={cn(
"inline-flex max-w-full items-center gap-0.5 text-sm text-primary hover:underline",
variant === "compact" ? "truncate" : "break-all",
)}
title={trimmed}
>
<span className={variant === "compact" ? "truncate" : "break-all"}>{trimmed}</span>
<span aria-hidden>↗</span>
</a>
);
}
if (CASE_ID_RE.test(trimmed)) {
return (
<Link to={caseHref(trimmed)} className="font-mono text-sm text-primary hover:underline">
{trimmed}
</Link>
);
}
if (variant === "compact") {
return (
<CopyableCompactValue value={value} className="text-sm">
{value}
</CopyableCompactValue>
);
}
return <span className="text-sm break-words">{value}</span>;
}
export function CaseFieldValue({
value,
fieldKey,
variant = "full",
}: {
value: unknown;
fieldKey?: string;
variant?: "compact" | "full";
}) {
if (value === null || value === undefined) return <EmptyValue />;
const issueIdentifiers = extractIssueIdentifiers(value, fieldKey);
if (issueIdentifiers.length > 0) return <IssueIdentifierValue identifiers={issueIdentifiers} />;
if (typeof value === "string") return <StringValue value={value} variant={variant} />;
if (typeof value === "number") {
if (!Number.isFinite(value)) return <span className="text-sm">{String(value)}</span>;
if (variant === "compact") {
return (
<CopyableCompactValue value={value} className="text-sm tabular-nums">
{value.toLocaleString()}
</CopyableCompactValue>
);
}
return <span className="text-sm tabular-nums">{value.toLocaleString()}</span>;
}
if (typeof value === "boolean") {
return value ? (
<Check className="h-4 w-4 text-green-600 dark:text-green-400" aria-label="true" />
) : (
<EmptyValue />
);
}
if (Array.isArray(value)) {
if (value.length === 0) return <EmptyValue />;
if (variant === "compact") {
return (
<CopyableCompactValue value={value} className="text-sm text-muted-foreground">
{stringifyCopyValue(value)}
</CopyableCompactValue>
);
}
return (
<div className="flex flex-wrap justify-start gap-1">
{value.map((item, index) => (
<Badge key={index} variant="secondary" className="font-normal">
{typeof item === "string" || typeof item === "number" || typeof item === "boolean"
? String(item)
: JSON.stringify(item)}
</Badge>
))}
</div>
);
}
if (isPlainObject(value)) {
const snippet = JSON.stringify(value);
if (variant === "compact") {
return (
<CopyableCompactValue value={value} className="font-mono text-xs text-muted-foreground">
{snippet}
</CopyableCompactValue>
);
}
return (
<pre className={cn("max-w-full whitespace-pre-wrap break-words font-mono text-xs text-muted-foreground", ANALYTICS_MASK_CLASS)}>
{JSON.stringify(value, null, 2)}
</pre>
);
}
return <span className="text-sm">{String(value)}</span>;
}
type CaseFieldRow = {
id: string;
path: string;
value: unknown;
};
function flattenCaseFields(fields: Record<string, unknown>): CaseFieldRow[] {
const rows: CaseFieldRow[] = [];
const visit = (value: unknown, path: string, segments: (string | number)[]) => {
if (isPlainObject(value)) {
const entries = Object.entries(value);
if (entries.length > 0) {
entries.forEach(([key, child]) => visit(child, `${path}.${key}`, [...segments, key]));
return;
}
} else if (Array.isArray(value) && value.some((item) => typeof item === "object" && item !== null)) {
// A single record reads naturally as items.quantity. Keep indices for
// multiple records or mixed arrays so separate entries stay identifiable.
if (value.length === 1 && isPlainObject(value[0])) {
visit(value[0], path, [...segments, 0]);
} else {
value.forEach((child, index) => visit(child, `${path}[${index}]`, [...segments, index]));
}
return;
}
// Structural identity stays distinct even if literal keys contain dots or
// brackets that happen to look like another field's displayed path.
rows.push({ id: JSON.stringify(segments), path, value });
};
Object.entries(fields).forEach(([key, value]) => visit(value, key, [key]));
return rows;
}
function TableStringValue({
value,
fieldKey,
quoted = false,
}: {
value: string;
fieldKey: string;
quoted?: boolean;
}) {
const caseHref = useCaseHref();
const trimmed = value.trim();
const text = quoted ? JSON.stringify(value).slice(1, -1) : value;
const linkClass = "text-primary underline-offset-2 hover:underline";
let content: ReactNode = text;
if (URL_RE.test(trimmed)) {
content = <a href={trimmed} target="_blank" rel="noreferrer" className={linkClass}>{text}</a>;
} else if (CASE_ID_RE.test(trimmed)) {
content = <Link to={caseHref(trimmed)} className={linkClass}>{text}</Link>;
} else if (ISSUE_ID_RE.test(trimmed)) {
content = <Link to={`/issues/${trimmed}`} className={linkClass}>{text}</Link>;
} else if (isIssueIdentifierField(fieldKey)) {
// Keep prose around task references rather than replacing the entire value
// with only the identifiers extracted from it.
const identifiers = new Set(extractIssueIdentifiers(value, fieldKey));
content = text.split(/(\b[A-Z][A-Z0-9]*-\d+\b)/g).map((part, index) => (
identifiers.has(part)
? <Link key={index} to={`/issues/${part}`} className={linkClass}>{part}</Link>
: part
));
}
if (quoted) return <>{'"'}{content}{'"'}</>;
return value === "" ? '""' : content;
}
function TableFieldValue({ value, fieldKey }: { value: unknown; fieldKey: string }) {
if (value === null || value === undefined) return <EmptyValue />;
if (typeof value === "string") return <TableStringValue value={value} fieldKey={fieldKey} />;
if (Array.isArray(value)) {
return (
<>
{"["}
{value.map((item, index) => (
<Fragment key={index}>
{index > 0 ? "," : null}
{typeof item === "string"
? <TableStringValue value={item} fieldKey={fieldKey} quoted />
: JSON.stringify(item)}
</Fragment>
))}
{"]"}
</>
);
}
if (typeof value === "object") return JSON.stringify(value);
return String(value);
}
/** Compact read-only field rows for case detail, including nested JSON paths. */
export function CaseFieldsTable({ fields }: { fields: Record<string, unknown> }) {
const rows = flattenCaseFields(fields);
if (rows.length === 0) {
return <p className="text-sm text-muted-foreground">No fields set</p>;
}
return (
<table aria-label="Case fields" className={cn("w-full table-fixed border-collapse font-mono text-xs leading-5", ANALYTICS_MASK_CLASS)}>
<tbody>
{rows.map(({ id, path, value }) => (
<tr key={id} className="even:bg-muted/50">
<th scope="row" className="w-1/3 break-all px-2 py-1 text-left align-top font-normal text-muted-foreground md:w-1/4">
{path}
</th>
<td className="break-all whitespace-pre-wrap px-2 py-1 align-top">
<TableFieldValue value={value} fieldKey={path} />
</td>
</tr>
))}
</tbody>
</table>
);
}
export function CaseFieldsPanel({ fields }: { fields: Record<string, unknown> }) {
const entries = Object.entries(fields ?? {});
return (
<section className="space-y-2">
<div className="flex items-baseline gap-2">
<h2 className="text-sm font-semibold">Fields</h2>
<span className="text-xs text-muted-foreground">from the skill&apos;s schema — rendered generically</span>
</div>
<Card className="gap-0 py-0">
{entries.length === 0 ? (
<div className="px-4 py-3 text-sm text-muted-foreground">No fields set</div>
) : (
<dl className="divide-y divide-border">
{entries.map(([key, value]) => (
<div key={key} className="flex items-start justify-between gap-4 px-4 py-1.5">
<dt className="shrink-0 text-xs text-muted-foreground">{key}</dt>
<dd className="min-w-0 max-w-(--pct-70) text-right">
<CaseFieldValue value={value} fieldKey={key} />
</dd>
</div>
))}
</dl>
)}
</Card>
</section>
);
}