Files
PaperClipAI/ui/src/components/ai-connections/AiConnectionField.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

257 lines
15 KiB
TypeScript

// @vitest-environment jsdom
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import type { ComponentProps } from "react";
import type { AiManagedConnectionSummary } from "@paperclipai/shared";
import { AiConnectionField, aiProviderForAdapter } from "./AiConnectionField";
import { ApiError } from "@/api/client";
import type { AiConnectionCredentialStep } from "./AiConnectionCredentialStep";
import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils";
const mocks = vi.hoisted(() => ({ list: vi.fn(), setDefault: vi.fn() }));
let credentialProps: ComponentProps<typeof AiConnectionCredentialStep> | undefined;
vi.mock("@/api/ai-connections", () => ({ aiConnectionsApi: mocks }));
vi.mock("./AiConnectionCredentialStep", () => ({
AiConnectionCredentialStep: (props: ComponentProps<typeof AiConnectionCredentialStep>) => {
credentialProps = props;
return <div>Provider sign-in</div>;
},
}));
vi.mock("./AiProviderSetup", () => ({ AiProviderSetup: () => <div>Advanced provider setup</div> }));
vi.mock("@/pages/apps/AppLogo", () => ({ AppLogo: () => null }));
let root: Root;
let container: HTMLDivElement;
let client: QueryClient;
const onChange = vi.fn();
const account = (overrides: Partial<AiManagedConnectionSummary> = {}): AiManagedConnectionSummary => ({
id: "old-connection", grantId: "old-grant", companyId: "company",
provider: "anthropic", method: "subscription", name: "My Claude",
ownership: "personal", ownerUserId: "owner", isDefault: true,
status: "needs_attention", ...overrides,
});
async function settle() {
for (let i = 0; i < 5; i++) {
await new Promise(resolve => setTimeout(resolve, 0));
flushSync(() => {});
}
}
async function mount(connections: AiManagedConnectionSummary[], canManageConnections = true, preferAdvanced = false) {
mocks.list.mockResolvedValue({ currentUserId: "owner", connections, canManageConnections });
flushSync(() => root.render(<QueryClientProvider client={client}>
<AiConnectionField companyId="company" agentId="agent" agentName="Nova" adapterType="claude_local"
preferAdvanced={preferAdvanced}
value={{ provider: "anthropic", method: "subscription", mode: "responsible_user" }} onChange={onChange} />
</QueryClientProvider>));
await settle();
}
async function click(label: string) {
if (label === "Connect another account") {
const trigger = document.querySelector('[role="combobox"][aria-label="Connection"]')!;
flushSync(() => trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })));
await settle();
const option = Array.from(document.querySelectorAll<HTMLElement>('[role="option"]')).find(item => item.textContent?.includes("Connect an account"));
expect(option).toBeDefined();
flushSync(() => option!.click());
await settle();
return;
}
const button = Array.from(document.querySelectorAll("button")).find(item => item.textContent === label);
expect(button, `Missing button: ${label}`).toBeDefined();
flushSync(() => button!.click());
}
beforeEach(() => {
vi.clearAllMocks();
credentialProps = undefined;
mocks.setDefault.mockResolvedValue({});
container = document.createElement("div");
document.body.append(container);
root = createRoot(container);
client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
});
afterEach(() => { flushSync(() => root.unmount()); client.clear(); container.remove(); });
it("reconnects the unavailable personal default in place", async () => {
await mount([account()]);
await click("Reconnect account");
expect(credentialProps).toMatchObject({ connectionId: "old-connection", initialMethod: "subscription", fixedMethod: true });
credentialProps!.onComplete({ connectionId: "old-connection", grantId: "old-grant", method: "subscription" });
await settle();
expect(mocks.setDefault).not.toHaveBeenCalled();
expect(onChange).toHaveBeenCalledWith({ provider: "anthropic", method: "subscription", mode: "responsible_user" });
});
it("identifies duplicate-named accounts before adopting the exact personal grant", async () => {
const personal = account({ id: "00000000-0000-4000-8000-000000000001", grantId: "00000000-0000-4000-8000-000000000002", provider: "openai", method: "api_key", name: "OpenAI", ownerName: "Avery", status: "connected", isDefault: false });
const shared = account({ id: "00000000-0000-4000-8000-000000000003", grantId: "00000000-0000-4000-8000-000000000004", provider: "openai", method: "subscription", name: "OpenAI", accountLabel: "engineering@example.test", ownership: "shared", ownerUserId: undefined, status: "connected", isDefault: false });
const sharedKey = account({ id: "00000000-0000-4000-8000-000000000005", grantId: "00000000-0000-4000-8000-000000000006", provider: "openai", method: "api_key", name: "OpenAI", ownerName: "Engineering", ownership: "shared", ownerUserId: undefined, status: "connected", isDefault: false });
const unavailable = account({ id: "expired-account", grantId: "expired-grant", provider: "openai", method: "api_key", name: "Expired account", ownerName: "Avery" });
mocks.list.mockResolvedValue({ currentUserId: "owner", connections: [shared, personal, sharedKey, unavailable], canManageConnections: true });
flushSync(() => root.render(<QueryClientProvider client={client}>
<AiConnectionField companyId="company" agentId="agent" agentName="Nova" adapterType="codex_local" legacy onChange={onChange} />
</QueryClientProvider>));
await settle();
await click("Choose a managed connection");
const trigger = container.querySelector('[role="combobox"][aria-label="Connection"]')!;
flushSync(() => trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })));
await settle();
const choices = [...document.querySelectorAll<HTMLElement>('[role="option"]')];
expect(choices.map(choice => choice.textContent)).toContain("OpenAI · API key · Personal · Avery");
expect(choices.map(choice => choice.textContent)).toContain("OpenAI · ChatGPT subscription · Company shared · engineering@example.test");
expect(choices.map(choice => choice.textContent)).toContain("OpenAI · API key · Company shared · Engineering");
expect(choices.find(choice => choice.textContent?.includes("Expired account"))?.getAttribute("aria-disabled")).toBe("true");
flushSync(() => choices.find(choice => choice.textContent === "OpenAI · API key · Personal · Avery")!.click());
await settle();
expect(document.querySelector('[role="dialog"]')?.textContent).toContain("OpenAI · API key · Personal · Avery");
expect(onChange).not.toHaveBeenCalled();
await click("Use this binding when saved");
expect(onChange).toHaveBeenCalledExactlyOnceWith({ provider: "openai", method: "api_key", mode: "delegated", connectionId: personal.id, grantId: personal.grantId });
});
it("opens provider setup directly when connecting from the advanced mode", async () => {
await mount([], true, true);
await click("Connect another account");
expect(document.body.textContent).toContain("Advanced provider setup");
expect(credentialProps).toBeUndefined();
});
it("selects the returned new grant and actual method before adopting the personal default", async () => {
await mount([account()]);
await click("Connect another account");
expect(document.body.textContent).toContain("default");
expect(credentialProps).toMatchObject({ connectionId: undefined, allAgents: true });
let resolveDefault!: () => void;
mocks.setDefault.mockImplementation(() => new Promise<void>(resolve => { resolveDefault = resolve; }));
credentialProps!.onComplete({ connectionId: "new-connection", grantId: "new-grant", method: "api_key" });
await settle();
expect(mocks.setDefault).toHaveBeenCalledWith("company", "new-grant");
expect(onChange).not.toHaveBeenCalled();
resolveDefault();
await settle();
expect(onChange).toHaveBeenCalledWith({ provider: "anthropic", method: "api_key", mode: "responsible_user" });
});
it("lets the owner limit a new personal connection to this agent", async () => {
await mount([]);
await click("Connect another account");
const checkbox = document.querySelector<HTMLButtonElement>('[role="checkbox"]')!;
expect(checkbox).not.toBeNull();
expect(checkbox.getAttribute("aria-checked")).toBe("true");
flushSync(() => checkbox.click());
expect(credentialProps).toMatchObject({ allAgents: false, agentIds: ["agent"] });
});
it("keeps default-update failures visible and retries without another provider login", async () => {
await mount([account()]);
await click("Connect another account");
mocks.setDefault.mockRejectedValueOnce(new Error("Default update failed"));
credentialProps!.onComplete({ connectionId: "new-connection", grantId: "new-grant", method: "api_key" });
await settle();
expect(document.body.textContent).toContain("Default update failed");
expect(onChange).not.toHaveBeenCalled();
await click("Retry default selection");
await settle();
expect(mocks.setDefault).toHaveBeenCalledTimes(2);
expect(onChange).toHaveBeenCalledWith({ provider: "anthropic", method: "api_key", mode: "responsible_user" });
});
it("does not offer reconnection for a healthy default or another owner's account", async () => {
await mount([account({ status: "connected" }), account({ id: "someone-else", ownerUserId: "other" })]);
expect(document.body.textContent).not.toContain("Reconnect account");
});
it("keeps an ordinary member's new connection scoped to the current agent by default", async () => {
await mount([], false);
expect(document.body.textContent).toContain("You have no default account");
await click("Connect another account");
expect(document.querySelector<HTMLButtonElement>('[role="checkbox"]')!.disabled).toBe(true);
expect(credentialProps).toMatchObject({ allAgents: false, agentIds: ["agent"] });
});
it("uses the server's connection-manager permission for company-wide access", async () => {
await mount([], true);
await click("Connect another account");
expect(credentialProps).toMatchObject({ allAgents: true });
});
it("offers Pi account selection before choosing its required model", async () => {
mocks.list.mockResolvedValue({ currentUserId: "owner", connections: [], canManageConnections: true });
expect(aiProviderForAdapter("pi_local")).toBe("openrouter");
flushSync(() => root.render(<QueryClientProvider client={client}>
<AiConnectionField companyId="company" agentId="agent" agentName="Pi" adapterType="pi_local" model=""
value={{ provider: "openrouter", method: "api_key", mode: "responsible_user" }} onChange={onChange} />
</QueryClientProvider>));
await settle();
expect(document.querySelector('[role="combobox"][aria-label="Connection"]')).not.toBeNull();
expect(container.textContent).not.toContain("does not support the current harness");
await click("Connect another account");
expect(document.body.textContent).toContain("Advanced provider setup");
});
it.each(["openai", "anthropic", "google", "openrouter"] as const)("keeps a matching saved Pi %s API-key account selectable", async provider => {
const saved = account({ provider, method: "api_key", name: "Pi provider account", accountLabel: "avery@example.test", status: "connected" });
mocks.list.mockResolvedValue({ currentUserId: "owner", connections: [saved], canManageConnections: true });
flushSync(() => root.render(<QueryClientProvider client={client}>
<AiConnectionField companyId="company" agentId="agent" agentName="Pi" adapterType="pi_local" model={`${provider}/provider-model`}
value={{ provider, method: "api_key", mode: "delegated", connectionId: saved.id, grantId: saved.grantId }} onChange={onChange} />
</QueryClientProvider>));
await settle();
expect(container.textContent).toContain("Pi provider account");
expect(container.textContent).not.toContain("incompatible");
expect(container.textContent).not.toContain("does not support");
const trigger = container.querySelector('[role="combobox"][aria-label="Connection"]')!;
expect(trigger.getAttribute("title")).toBe("Pi provider account · API key · Personal · avery@example.test");
flushSync(() => trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })));
await settle();
const choice = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find(node => node.textContent?.includes("Pi provider account"));
expect(choice).toBeDefined();
expect(choice?.getAttribute("aria-disabled")).not.toBe("true");
});
it("keeps loaded connections usable when a refetch fails during an outage", async () => {
await mount([account()]);
expect(document.body.textContent).toContain("Reconnect account");
mocks.list.mockRejectedValue(new ApiError("Paperclip is restarting.", 503, { error: "tenant_app_unavailable" }));
await client.invalidateQueries();
await settle();
expect(document.body.textContent).toContain("Reconnect account");
expect(document.body.textContent).not.toContain("Retry connections");
expect(document.body.textContent).not.toContain("Paperclip is restarting.");
expect(document.querySelector('[data-query-view="error"]')).toBeNull();
});
it("shows readable copy with a retry when connections cannot be loaded", async () => {
mocks.list.mockRejectedValueOnce(new ApiError("Request failed: 500", 500, { error: "internal_error" }));
await mount([account()]);
const alerts = Array.from(document.querySelectorAll('[role="alert"]')).map(node => node.textContent).join(" ");
expect(alerts).toContain("An unexpected error occurred");
expect(document.body.textContent).not.toContain("internal_error");
expect(document.body.textContent).not.toContain("Request failed: 500");
expect(document.body.textContent).not.toContain("Reconnect account");
await click("Retry connections");
await settle();
expect(mocks.list).toHaveBeenCalledTimes(2);
expect(document.body.textContent).toContain("Reconnect account");
expect(document.body.textContent).not.toContain("Retry connections");
});
it("masks the adoption dialog's account label in session replay", async () => {
const personal = account({ id: "00000000-0000-4000-8000-000000000011", grantId: "00000000-0000-4000-8000-000000000012", provider: "openai", method: "api_key", name: "OpenAI", accountLabel: "solenne.drake@example.test", status: "connected", isDefault: false });
mocks.list.mockResolvedValue({ currentUserId: "owner", connections: [personal], canManageConnections: true });
flushSync(() => root.render(<QueryClientProvider client={client}>
<AiConnectionField companyId="company" agentId="agent" agentName="Nova" adapterType="codex_local" legacy onChange={onChange} />
</QueryClientProvider>));
await settle();
await click("Choose a managed connection");
const trigger = container.querySelector('[role="combobox"][aria-label="Connection"]')!;
flushSync(() => trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })));
await settle();
flushSync(() => [...document.querySelectorAll<HTMLElement>('[role="option"]')].find(choice => choice.textContent?.includes("solenne.drake@example.test"))!.click());
await settle();
const dialog = document.querySelector('[role="dialog"]')!;
expect(replayLeaks("solenne.drake@example.test", dialog)).toEqual({ rendered: true, recorded: false });
expect(replayLeaks("Adopt Connections for Nova", dialog)).toEqual({ rendered: true, recorded: false });
});