Files
PaperClipAI/ui/src/components/ExecutionWorkspaceCloseDialog.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

333 lines
15 KiB
TypeScript

import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { ExecutionWorkspace } from "@paperclipai/shared";
import { Link } from "@/lib/router";
import { Loader2 } from "lucide-react";
import { executionWorkspacesApi } from "../api/execution-workspaces";
import { describeError } from "../api/errors";
import { useToastActions } from "../context/ToastContext";
import { queryKeys } from "../lib/queryKeys";
import { formatDateTime, issueUrl } from "../lib/utils";
import { Button } from "./ui/button";
import { QueryErrorState, useQueryView } from "./QueryView";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "./ui/dialog";
import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy";
import { cn } from "@/lib/utils";
type ExecutionWorkspaceCloseDialogProps = {
workspaceId: string;
workspaceName: string;
currentStatus: ExecutionWorkspace["status"];
open: boolean;
onOpenChange: (open: boolean) => void;
onClosed?: (workspace: ExecutionWorkspace) => void;
};
function readinessTone(state: "ready" | "ready_with_warnings" | "blocked") {
if (state === "blocked") {
return "border-destructive/30 bg-destructive/5 text-destructive";
}
if (state === "ready_with_warnings") {
return "border-amber-500/30 bg-amber-500/10 text-amber-800 dark:text-amber-300";
}
return "border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300";
}
export function ExecutionWorkspaceCloseDialog({
workspaceId,
workspaceName,
currentStatus,
open,
onOpenChange,
onClosed,
}: ExecutionWorkspaceCloseDialogProps) {
const queryClient = useQueryClient();
const { pushToast } = useToastActions();
const actionLabel = currentStatus === "cleanup_failed" ? "Retry close" : "Close workspace";
const readinessQuery = useQuery({
queryKey: queryKeys.executionWorkspaces.closeReadiness(workspaceId),
queryFn: () => executionWorkspacesApi.getCloseReadiness(workspaceId),
enabled: open,
});
// Read close readiness through the shared view: cached readiness stays
// usable during a transient refetch failure,and a no-data failure shows
// readable copy with Retry.
const readinessView = useQueryView(readinessQuery);
const closeWorkspace = useMutation({
mutationFn: () => executionWorkspacesApi.update(workspaceId, { status: "archived" }),
onSuccess: (workspace) => {
queryClient.setQueryData(queryKeys.executionWorkspaces.detail(workspace.id), workspace);
queryClient.invalidateQueries({ queryKey: queryKeys.executionWorkspaces.overview(workspace.companyId) });
queryClient.invalidateQueries({ queryKey: queryKeys.executionWorkspaces.closeReadiness(workspace.id) });
pushToast({
title: currentStatus === "cleanup_failed" ? "Workspace close retried" : "Workspace closed",
tone: "success",
});
onOpenChange(false);
onClosed?.(workspace);
},
onError: (error) => {
pushToast({
title: "Failed to close workspace",
body: describeError(error).body,
tone: "error",
});
},
});
const readiness = readinessQuery.data ?? null;
const blockingIssues = readiness?.linkedIssues.filter((issue) => !issue.isTerminal) ?? [];
const otherLinkedIssues = readiness?.linkedIssues.filter((issue) => issue.isTerminal) ?? [];
const confirmDisabled =
currentStatus === "archived" ||
closeWorkspace.isPending ||
readinessQuery.isLoading ||
readiness == null ||
readiness.state === "blocked";
return (
<Dialog open={open} onOpenChange={(nextOpen) => {
if (!closeWorkspace.isPending) onOpenChange(nextOpen);
}}>
<DialogContent className="max-h-(--sz-85vh) overflow-y-auto sm:max-w-2xl">
<DialogHeader>
<DialogTitle>{actionLabel}</DialogTitle>
<DialogDescription className="break-words">
Archive <span className="font-medium text-foreground">{workspaceName}</span> and clean up any owned workspace
artifacts. Paperclip keeps the workspace record and task history, but removes it from active workspace views.
</DialogDescription>
</DialogHeader>
{(readinessView.kind === "loading" || readinessView.kind === "reconnecting") ? (
<div className="flex items-center gap-2 rounded-xl border border-border bg-background px-4 py-3 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
Checking whether this workspace is safe to close...
</div>
) : readinessView.kind === "error" ? (
<QueryErrorState
error={readinessView.error}
action="inspect workspace close readiness"
onRetry={readinessView.retry}
retrying={readinessView.isFetching}
/>
) : readiness ? (
<div className="space-y-4">
<div className={`rounded-xl border px-4 py-3 text-sm ${readinessTone(readiness.state)}`}>
<div className="font-medium">
{readiness.state === "blocked"
? "Close is blocked"
: readiness.state === "ready_with_warnings"
? "Close is allowed with warnings"
: "Close is ready"}
</div>
<div className="mt-1 text-xs opacity-80">
{readiness.isSharedWorkspace
? "This is a shared workspace session. Archiving it removes this session record but keeps the underlying project workspace."
: readiness.git?.workspacePath && readiness.git.repoRoot && readiness.git.workspacePath !== readiness.git.repoRoot
? "This execution workspace has its own checkout path and can be archived independently."
: readiness.isProjectPrimaryWorkspace
? "This execution workspace currently points at the project's primary workspace path."
: "This workspace is disposable and can be archived."}
</div>
</div>
{blockingIssues.length > 0 ? (
<section className="space-y-2">
<h3 className="text-sm font-medium">Blocking tasks</h3>
<div className="space-y-2">
{blockingIssues.map((issue) => (
<div key={issue.id} className="rounded-xl border border-destructive/20 bg-destructive/5 px-4 py-3 text-sm">
<div className="flex min-w-0 flex-wrap items-center justify-between gap-2">
<Link to={issueUrl(issue)} className="min-w-0 break-words font-medium hover:underline">
{issue.identifier ?? issue.id} · {issue.title}
</Link>
<span className="text-xs text-muted-foreground">{issue.status}</span>
</div>
</div>
))}
</div>
</section>
) : null}
{readiness.blockingReasons.length > 0 ? (
<section className="space-y-2">
<h3 className="text-sm font-medium">Blocking reasons</h3>
<ul className="space-y-2 text-sm text-muted-foreground">
{readiness.blockingReasons.map((reason) => (
<li key={reason} className="break-words rounded-lg border border-destructive/20 bg-destructive/5 px-3 py-2 text-destructive">
{reason}
</li>
))}
</ul>
</section>
) : null}
{readiness.warnings.length > 0 ? (
<section className="space-y-2">
<h3 className="text-sm font-medium">Warnings</h3>
<ul className="space-y-2 text-sm text-muted-foreground">
{readiness.warnings.map((warning) => (
<li key={warning} className="break-words rounded-lg border border-amber-500/20 bg-amber-500/5 px-3 py-2">
{warning}
</li>
))}
</ul>
</section>
) : null}
{readiness.git ? (
<section className="space-y-2">
<h3 className="text-sm font-medium">Git status</h3>
<div className="rounded-xl border border-border bg-background px-4 py-3 text-sm">
<div className="grid gap-2 sm:grid-cols-2">
<div>
<div className="text-xs uppercase tracking-(--tracking-eyebrow) text-muted-foreground">Branch</div>
<div className="font-mono text-xs">{readiness.git.branchName ?? "Unknown"}</div>
</div>
<div>
<div className="text-xs uppercase tracking-(--tracking-eyebrow) text-muted-foreground">Base ref</div>
<div className="font-mono text-xs">{readiness.git.baseRef ?? "Not set"}</div>
</div>
<div>
<div className="text-xs uppercase tracking-(--tracking-eyebrow) text-muted-foreground">Merged into base</div>
<div>{readiness.git.isMergedIntoBase == null ? "Unknown" : readiness.git.isMergedIntoBase ? "Yes" : "No"}</div>
</div>
<div>
<div className="text-xs uppercase tracking-(--tracking-eyebrow) text-muted-foreground">Ahead / behind</div>
<div>
{(readiness.git.aheadCount ?? 0).toString()} / {(readiness.git.behindCount ?? 0).toString()}
</div>
</div>
<div>
<div className="text-xs uppercase tracking-(--tracking-eyebrow) text-muted-foreground">Dirty tracked files</div>
<div>{readiness.git.dirtyEntryCount}</div>
</div>
<div>
<div className="text-xs uppercase tracking-(--tracking-eyebrow) text-muted-foreground">Untracked files</div>
<div>{readiness.git.untrackedEntryCount}</div>
</div>
</div>
</div>
</section>
) : null}
{otherLinkedIssues.length > 0 ? (
<section className="space-y-2">
<h3 className="text-sm font-medium">Other linked tasks</h3>
<div className="space-y-2">
{otherLinkedIssues.map((issue) => (
<div key={issue.id} className="rounded-xl border border-border bg-background px-4 py-3 text-sm">
<div className="flex min-w-0 flex-wrap items-center justify-between gap-2">
<Link to={issueUrl(issue)} className="min-w-0 break-words font-medium hover:underline">
{issue.identifier ?? issue.id} · {issue.title}
</Link>
<span className="text-xs text-muted-foreground">{issue.status}</span>
</div>
</div>
))}
</div>
</section>
) : null}
{readiness.runtimeServices.length > 0 ? (
<section className="space-y-2">
<h3 className="text-sm font-medium">Attached runtime services</h3>
<div className="space-y-2">
{readiness.runtimeServices.map((service) => (
<div key={service.id} className="rounded-xl border border-border bg-background px-4 py-3 text-sm">
<div className="flex min-w-0 flex-wrap items-center justify-between gap-2">
<span className="font-medium">{service.serviceName}</span>
<span className="text-xs text-muted-foreground">{service.status} · {service.lifecycle}</span>
</div>
{/*
The last fallback used to print the service working
directory, a path on the execution host. The dialog has
no instance-policy context of its own, so it drops the
path outright and falls back to a neutral line.
*/}
<div className="mt-1 break-words text-xs text-muted-foreground">
{service.url ?? service.command ?? "No additional details"}
</div>
</div>
))}
</div>
</section>
) : null}
<section className="space-y-2">
<h3 className="text-sm font-medium">Cleanup actions</h3>
<div className="space-y-2">
{readiness.plannedActions.map((action, index) => (
<div key={`${action.kind}-${index}`} className="rounded-xl border border-border bg-background px-4 py-3 text-sm">
<div className="font-medium">{action.label}</div>
<div className="mt-1 break-words text-muted-foreground">{action.description}</div>
{action.command ? (
<pre className={cn("mt-2 whitespace-pre-wrap break-all rounded-lg bg-background px-3 py-2 font-mono text-xs text-foreground", ANALYTICS_MASK_CLASS)}>
{action.command}
</pre>
) : null}
</div>
))}
</div>
</section>
{currentStatus === "cleanup_failed" ? (
<div className="rounded-xl border border-amber-500/20 bg-amber-500/5 px-4 py-3 text-sm text-muted-foreground">
Cleanup previously failed on this workspace. Retrying close will rerun the cleanup flow and update the
workspace status if it succeeds.
</div>
) : null}
{currentStatus === "archived" ? (
<div className="rounded-xl border border-border bg-background px-4 py-3 text-sm text-muted-foreground">
This workspace is already archived.
</div>
) : null}
{readiness.git?.repoRoot ? (
<div className="break-words text-xs text-muted-foreground">
Repo root: <span className="font-mono break-all">{readiness.git.repoRoot}</span>
{readiness.git.workspacePath ? (
<>
{" · "}Workspace path: <span className="font-mono break-all">{readiness.git.workspacePath}</span>
</>
) : null}
</div>
) : null}
<div className="text-xs text-muted-foreground">
Last checked {formatDateTime(new Date(readinessQuery.dataUpdatedAt))}
</div>
</div>
) : null}
<DialogFooter>
<Button
variant="outline"
onClick={() => onOpenChange(false)}
disabled={closeWorkspace.isPending}
>
Cancel
</Button>
<Button
variant={currentStatus === "cleanup_failed" ? "default" : "destructive"}
onClick={() => closeWorkspace.mutate()}
disabled={confirmDisabled}
>
{closeWorkspace.isPending ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
{actionLabel}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}