Files
PaperClipAI/ui/src/pages/apps/gateways/panels/TokensPanel.test.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

296 lines
12 KiB
TypeScript

// @vitest-environment jsdom
import { flushSync } from "react-dom";
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { ReactNode } from "react";
import type { ToolMcpGatewayToken, ToolMcpGatewayWithTokens } from "@paperclipai/shared";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { TokensPanel } from "./TokensPanel";
import { isBlockedFromReplay } from "@/lib/analytics/replay-recording.test-utils";
const createGatewayTokenMock = vi.hoisted(() => vi.fn());
const revokeGatewayTokenMock = vi.hoisted(() => vi.fn());
const revealGatewayTokenMock = vi.hoisted(() => vi.fn());
const pushToastMock = vi.hoisted(() => vi.fn());
vi.mock("@/api/tools", () => ({
toolsApi: {
createGatewayToken: (...args: unknown[]) => createGatewayTokenMock(...args),
revokeGatewayToken: (...args: unknown[]) => revokeGatewayTokenMock(...args),
revealGatewayToken: (...args: unknown[]) => revealGatewayTokenMock(...args),
},
}));
vi.mock("@/api/companies-query", () => ({
useAccountIdentity: () => ({ userId: "user-1", settled: true, failed: false, bootstrap: undefined, updatedAt: 0 }),
}));
vi.mock("@/context/ToastContext", () => ({
useToast: () => ({ pushToast: pushToastMock }),
}));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
async function act(callback: () => void | Promise<void>) {
let result: void | Promise<void> = undefined;
flushSync(() => {
result = callback();
});
await result;
}
async function flushReact() {
for (let i = 0; i < 3; i += 1) {
await act(async () => {
await Promise.resolve();
await new Promise((resolve) => window.setTimeout(resolve, 0));
});
}
}
function token(overrides: Partial<ToolMcpGatewayToken> = {}): ToolMcpGatewayToken {
return {
id: "token-1",
companyId: "company-1",
gatewayId: "gateway-1",
name: "cto-cursor",
tokenPrefix: "pcgw_live_8x4Pa",
subjectType: "gateway_client",
subjectId: null,
clientLabel: "Cursor",
ownerNote: "Local IDE",
allowedActions: ["tools/list", "tools/call"],
expiresAt: "2026-09-01T00:00:00.000Z",
expiryOverrideReason: null,
expiryOverrideByUserId: null,
expiryOverrideByAgentId: null,
expiryOverrideAt: null,
lastUsedAt: null,
revokedAt: null,
createdByAgentId: null,
createdByUserId: "user-1",
createdAt: "2026-06-01T00:00:00.000Z",
updatedAt: "2026-06-01T00:00:00.000Z",
...overrides,
};
}
function gateway(overrides: Partial<ToolMcpGatewayWithTokens> = {}): ToolMcpGatewayWithTokens {
return {
id: "gateway-1",
companyId: "company-1",
gatewayPublicId: "gw",
name: "CTO agents",
displaySlug: "cto-agents",
slug: "cto-agents",
description: null,
status: "active",
profileId: "profile-1",
defaultProfileMode: "gateway_only",
contextScopeType: "none",
contextScopeId: null,
agentId: null,
projectId: null,
issueId: null,
approvalIssueId: null,
endpointPath: "/g/cto-agents/mcp",
authConfig: {} as ToolMcpGatewayWithTokens["authConfig"],
headerPolicy: {} as ToolMcpGatewayWithTokens["headerPolicy"],
metadataPolicy: {} as ToolMcpGatewayWithTokens["metadataPolicy"],
onDemandToolsConfig: {} as ToolMcpGatewayWithTokens["onDemandToolsConfig"],
metadata: null,
createdByAgentId: null,
createdByUserId: "user-1",
archivedAt: null,
createdAt: new Date(),
updatedAt: new Date(),
tokens: [],
clientSnippets: [],
...overrides,
};
}
describe("TokensPanel", () => {
let container: HTMLDivElement;
let root: ReturnType<typeof createRoot>;
beforeEach(() => {
vi.spyOn(Date, "now").mockReturnValue(new Date("2026-06-16T12:00:00.000Z").getTime());
vi.clearAllMocks();
container = document.createElement("div");
document.body.appendChild(container);
});
afterEach(() => {
flushSync(() => root?.unmount());
container.remove();
vi.restoreAllMocks();
});
async function render(node: ReactNode) {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
root = createRoot(container);
await act(async () => {
root.render(<QueryClientProvider client={client}>{node}</QueryClientProvider>);
});
await flushReact();
}
function clickButton(label: string) {
const button = [...container.querySelectorAll("button")].find(
(el) => el.textContent?.trim() === label,
);
if (!button) throw new Error(`Button "${label}" not found`);
return act(async () => {
button.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
}
function clickButtonContaining(label: string) {
const button = [...container.querySelectorAll("button")].find(
(el) => el.textContent?.includes(label),
);
if (!button) throw new Error(`Button containing "${label}" not found`);
return act(async () => {
button.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
}
function setInput(selectorText: string, value: string) {
const input = container.querySelector<HTMLInputElement>(selectorText);
if (!input) throw new Error(`Input ${selectorText} not found`);
const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")?.set;
setter?.call(input, value);
return act(async () => {
input.dispatchEvent(new Event("input", { bubbles: true }));
});
}
it("masks existing tokens and never renders the full secret at rest", async () => {
await render(<TokensPanel companyId="company-1" gateway={gateway({ tokens: [token()] })} />);
expect(container.textContent).not.toContain("pcgw_live_8x4Pa•••");
expect(container.textContent).toContain("fresh one-hour runtime token");
expect(container.textContent).toContain("one run may leave two revoked rows");
await clickButtonContaining("Token history");
expect(container.textContent).toContain("pcgw_live_8x4Pa•••");
expect(container.textContent).toContain("Active");
});
it("autofills a token name, reuses it as the client label, and reveals the token once", async () => {
const created = { ...token({ id: "new-token" }), token: "pcgw_live_FULLSECRETVALUE" };
createGatewayTokenMock.mockResolvedValue(created);
const writeText = vi.fn().mockResolvedValue(undefined);
Object.assign(navigator, { clipboard: { writeText } });
await render(<TokensPanel companyId="company-1" gateway={gateway()} />);
await clickButton("Issue token");
const form = container.querySelector("form");
if (!form) throw new Error("token form not found");
const nameInput = form.querySelector<HTMLInputElement>('input:not([type="date"])');
if (!nameInput) throw new Error("token name input not found");
expect(nameInput.value).toMatch(/^cto-agents-\d{12}$/);
await act(async () => {
form.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
});
await flushReact();
expect(createGatewayTokenMock).toHaveBeenCalledTimes(1);
expect(createGatewayTokenMock).toHaveBeenCalledWith(
"company-1",
"gateway-1",
expect.objectContaining({
name: nameInput.value,
clientLabel: nameInput.value,
ownerNote: "",
}),
);
expect(container.textContent).toContain("New token — copy now");
// Reveal-once banner shows the full value immediately after creation.
expect(container.textContent).toContain("pcgw_live_FULLSECRETVALUE");
expect(isBlockedFromReplay("pcgw_live_FULLSECRETVALUE", document.body)).toBe(true);
await clickButton("Copy");
expect(writeText).toHaveBeenCalledWith("pcgw_live_FULLSECRETVALUE");
});
it("lets the person reveal an agent-created token value once, outside the folded history", async () => {
const pending = token({ id: "agent-token", name: "Replacement client", createdByAgentId: "agent-1", createdByUserId: null, responsibleUserId: "user-1", pendingReveal: true });
revealGatewayTokenMock.mockResolvedValue({ ...pending, pendingReveal: false, token: "pcgw_live_REVEALEDVALUE" });
await render(<TokensPanel companyId="company-1" gateway={gateway({ tokens: [pending] })} />);
expect(container.textContent).toContain("Waiting for you to reveal");
expect(container.textContent).toContain("Replacement client");
expect(container.textContent).not.toContain("pcgw_live_REVEALEDVALUE");
await clickButton("Reveal token");
await flushReact();
expect(revealGatewayTokenMock).toHaveBeenCalledWith("company-1", "agent-token");
expect(container.textContent).toContain("New token — copy now");
expect(container.textContent).toContain("pcgw_live_REVEALEDVALUE");
expect(isBlockedFromReplay("pcgw_live_REVEALEDVALUE", document.body)).toBe(true);
});
it("does not offer to reveal a token that expired before its reveal", async () => {
const pending = token({ id: "agent-token", name: "Expired client", createdByAgentId: "agent-1", createdByUserId: null, responsibleUserId: "user-1", pendingReveal: true, expiresAt: "2026-06-01T00:00:00.000Z" });
await render(<TokensPanel companyId="company-1" gateway={gateway({ tokens: [pending] })} />);
expect(container.textContent).not.toContain("Waiting for you to reveal");
});
it("does not offer to reveal a token that acts for another person", async () => {
const pending = token({ id: "agent-token", name: "Someone else's client", createdByAgentId: "agent-1", createdByUserId: null, responsibleUserId: "user-2", pendingReveal: true });
await render(<TokensPanel companyId="company-1" gateway={gateway({ tokens: [pending] })} />);
expect(container.textContent).not.toContain("Waiting for you to reveal");
expect([...container.querySelectorAll("button")].some((el) => el.textContent?.trim() === "Reveal token")).toBe(false);
});
it("gates revoke behind a typed confirmation matching the token name", async () => {
revokeGatewayTokenMock.mockResolvedValue(token({ revokedAt: "2026-06-16T12:00:00.000Z" }));
await render(<TokensPanel companyId="company-1" gateway={gateway({ tokens: [token()] })} />);
await clickButtonContaining("Token history");
await clickButton("Revoke");
const confirmButton = [...container.querySelectorAll("button")].find(
(el) => el.textContent?.trim() === "Revoke token",
) as HTMLButtonElement;
expect(confirmButton.disabled).toBe(true);
await setInput('input[aria-label="Type the token name to confirm"]', "cto-cursor");
expect(confirmButton.disabled).toBe(false);
await clickButton("Revoke token");
await flushReact();
expect(revokeGatewayTokenMock).toHaveBeenCalledWith("company-1", "token-1");
});
it("paginates the folded token log and labels past expiry as expired", async () => {
const tokens = Array.from({ length: 11 }, (_, index) => token({
id: `token-${index}`,
name: `client-${index}`,
tokenPrefix: `pcgw_${index}`,
expiresAt: index === 0 ? "2026-06-01T00:00:00.000Z" : "2026-09-01T00:00:00.000Z",
revokedAt: index === 0 ? "2026-06-10T00:00:00.000Z" : null,
createdAt: new Date(Date.UTC(2026, 5, index + 1)).toISOString(),
}));
await render(<TokensPanel companyId="company-1" gateway={gateway({ tokens })} />);
expect(container.textContent).not.toContain("client-10");
await clickButtonContaining("Token history");
expect(container.textContent).toContain("Page 1 of 2");
expect(container.textContent).toContain("client-10");
expect(container.textContent).not.toContain("client-0");
const next = container.querySelector<HTMLButtonElement>('button[aria-label="Next token page"]');
if (!next) throw new Error("next token page button not found");
await act(async () => next.click());
expect(container.textContent).toContain("Page 2 of 2");
expect(container.textContent).toContain("client-0");
expect(container.textContent).toContain("Expired");
expect(container.textContent).not.toContain("Expires 2 months ago");
});
});