From b56f240f4599732ef58bfba8a47e6855d562751e Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:18:50 -0600 Subject: [PATCH] feat(analytics): show session replay text by default, mask only customer content (#22057) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 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 `` (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> --- doc/cloud-browser-analytics.md | 116 +++++- ui/src/components/AccountQuotaPanels.test.tsx | 16 + ui/src/components/AccountQuotaPanels.tsx | 4 +- ui/src/components/AdapterLoginChrome.test.tsx | 26 ++ ui/src/components/AdapterLoginChrome.tsx | 8 +- .../AgentConfigForm.render.test.tsx | 12 + ui/src/components/AgentConfigForm.tsx | 3 +- ui/src/components/AgentSetupPrompt.test.tsx | 32 ++ ui/src/components/AgentSetupPrompt.tsx | 3 +- ui/src/components/AppConnectionSidebar.tsx | 4 +- ui/src/components/ApprovalPayload.tsx | 12 +- ui/src/components/AppsSidebar.production.tsx | 6 +- ui/src/components/AppsSidebar.tsx | 4 +- .../AttentionObligationEvidence.tsx | 3 +- ui/src/components/AttentionQueueRow.tsx | 5 +- ui/src/components/CaseFieldsPanel.tsx | 5 +- ui/src/components/CaseRevisionRail.test.tsx | 15 + ui/src/components/CaseRevisionRail.tsx | 3 +- .../CompanySettingsSidebar.production.tsx | 28 +- ui/src/components/CompanySettingsSidebar.tsx | 26 +- ui/src/components/CoordinatorSidebar.tsx | 6 +- ui/src/components/DecisionCard.test.tsx | 13 + ui/src/components/DecisionCard.tsx | 2 + ui/src/components/DecisionResolver.test.tsx | 12 +- ui/src/components/DecisionResolver.tsx | 3 +- ui/src/components/DesignSidebar.tsx | 20 +- ui/src/components/DocumentDiffModal.tsx | 4 +- ui/src/components/EmailMessageCard.tsx | 4 +- ui/src/components/EmailTaskActivity.tsx | 4 +- ui/src/components/EmptyState.tsx | 6 +- .../ExecutionWorkspaceCloseDialog.tsx | 4 +- ui/src/components/ExternalObjectPill.tsx | 5 +- ui/src/components/FileViewerSheet.tsx | 2 +- ui/src/components/InstructionHistory.tsx | 6 +- ui/src/components/IssueLinkQuicklook.tsx | 3 +- ui/src/components/IssueRecoveryActionCard.tsx | 9 +- ui/src/components/IssueRelatedWorkPanel.tsx | 4 +- ui/src/components/IssueRunLedger.test.tsx | 2 + ui/src/components/IssueRunLedger.tsx | 3 +- .../components/IssueThreadInteractionCard.tsx | 19 +- ui/src/components/LinkPreview.tsx | 4 +- .../ProjectGitAuthorization.test.tsx | 39 ++ ui/src/components/ProjectGitAuthorization.tsx | 8 +- ui/src/components/RoutineActivityRow.tsx | 3 +- .../components/RoutineContextualSidebar.tsx | 4 +- ui/src/components/RoutineHistoryTab.tsx | 4 +- ui/src/components/RunnerInspector.test.tsx | 40 ++ ui/src/components/RunnerInspector.tsx | 7 +- ui/src/components/Sidebar.production.tsx | 42 +- ui/src/components/Sidebar.tsx | 54 +-- .../components/SidebarNavItem.production.tsx | 5 - ui/src/components/SidebarNavItem.tsx | 5 - ui/src/components/SkillsContextualSidebar.tsx | 8 +- .../components/SubscriptionCostCard.test.tsx | 11 + ui/src/components/SubscriptionCostCard.tsx | 7 +- ui/src/components/TailscaleSshMachine.tsx | 4 +- ui/src/components/TaskDecisionRecord.test.tsx | 11 + ui/src/components/TaskDecisionRecord.tsx | 4 +- ui/src/components/ToastViewport.test.tsx | 12 + ui/src/components/ToastViewport.tsx | 3 +- ui/src/components/actions/ActionCard.tsx | 5 +- .../AiConnectionAccountControls.test.tsx | 18 + .../AiConnectionAccountControls.tsx | 3 +- .../AiConnectionAccountDetails.test.tsx | 8 + .../AiConnectionAccountDetails.tsx | 6 +- .../AiConnectionCredentialStep.tsx | 9 +- .../ai-connections/AiConnectionDefault.tsx | 3 +- .../ai-connections/AiConnectionField.test.tsx | 19 + .../ai-connections/AiConnectionField.tsx | 12 +- .../AiConnectionIdentity.test.tsx | 17 + .../ai-connections/AiConnectionIdentity.tsx | 6 +- .../AiConnectionPicker.test.tsx | 25 ++ .../ai-connections/AiConnectionPicker.tsx | 5 +- .../AiConnectionPoolConnector.tsx | 18 +- .../AiConnectionPoolRunDetails.test.tsx | 16 + .../AiConnectionPoolRunDetails.tsx | 4 +- .../AiConnectionSelect.test.tsx | 39 ++ .../ai-connections/AiConnectionSelect.tsx | 8 +- .../ai-connections/AiProviderSetup.tsx | 10 +- ui/src/components/artifacts/ArtifactCard.tsx | 3 +- .../artifacts/RichArtifactCards.tsx | 10 +- ui/src/components/chat/AgentChannelsPanel.tsx | 4 +- .../ExternallyConnectedTaskBanner.test.tsx | 7 + .../chat/ExternallyConnectedTaskBanner.tsx | 3 +- .../CoordinatorDecisionReceipt.tsx | 4 +- .../coordinator/CoordinatorNeedsYou.tsx | 4 +- .../coordinator/NeedsYouCardKit.tsx | 3 +- .../coordinator/NeedsYouCardParts.tsx | 5 +- .../decision-models/DecisionHistory.tsx | 3 +- .../InterruptHandoffViews.tsx | 5 +- .../issue-properties/external-object-rows.tsx | 5 +- .../routine-triggers/WebhookFields.test.tsx | 16 + .../routine-triggers/WebhookFields.tsx | 3 +- ui/src/components/run-log/LogViewer.tsx | 11 +- ui/src/components/run-log/RunDetails.tsx | 15 +- ui/src/components/search/SearchResultRow.tsx | 3 +- .../SkillSourceConnectionRepair.tsx | 3 +- .../components/skills/ConnectedAppSkills.tsx | 4 +- .../TaskChatCompactInteractionCard.tsx | 5 +- .../task-chat/TaskChatProtocolActivityRow.tsx | 5 +- .../task-chat/TaskChatProtocolCard.tsx | 5 +- .../task-chat/TaskChatRunnerActivityGroup.tsx | 3 +- .../components/task-chat/TaskChatToolCard.tsx | 3 +- .../task-side-panel/TaskAttachmentPanel.tsx | 8 +- .../transcript/RunTranscriptView.tsx | 31 +- ui/src/components/ui/button.tsx | 5 - ui/src/components/ui/label.tsx | 8 +- ui/src/components/ui/tabs.tsx | 8 +- ui/src/components/voice/SpekoCallHistory.tsx | 4 +- ui/src/components/voice/VoiceTranscript.tsx | 4 +- .../connections/ConnectionChoiceList.tsx | 4 +- .../connections/ConnectionInstructions.tsx | 8 +- .../ConnectionIntentInteractionBody.tsx | 12 +- .../GenericMcpConnectStep.machine.test.tsx | 23 + .../connections/GenericMcpConnectStep.tsx | 4 +- .../connections/GoogleWorkspaceServices.tsx | 6 +- .../remote-mcp/RemoteMcpConnectionSetup.tsx | 4 +- .../remote-mcp/RemoteMcpManagement.tsx | 3 +- ui/src/lib/analytics/privacy.test.ts | 44 +- ui/src/lib/analytics/privacy.ts | 53 +-- .../lib/analytics/product-analytics.test.ts | 6 +- ui/src/lib/analytics/product-analytics.ts | 5 +- ui/src/lib/analytics/replay-masking.test.tsx | 393 ++++++++++++++++++ .../analytics/replay-recording.test-utils.ts | 38 ++ ui/src/lib/analytics/shared-chrome.test.tsx | 35 +- ui/src/lib/analytics/unmask-allowlist.test.ts | 102 ----- ui/src/pages/AgentDetail.production.tsx | 11 +- ui/src/pages/AgentDetail.tsx | 21 +- ui/src/pages/AgentToolsTab.tsx | 5 +- ui/src/pages/ApprovalDetail.tsx | 4 +- ui/src/pages/CaseDetail.tsx | 6 +- ui/src/pages/CompanyEnvironments.tsx | 4 +- ui/src/pages/CompanyExport.tsx | 3 +- ui/src/pages/CompanyImport.tsx | 3 +- ui/src/pages/CompanySkills.production.tsx | 9 +- ui/src/pages/CompanySkills.tsx | 9 +- ui/src/pages/ExecutionWorkspaceDetail.tsx | 5 +- ui/src/pages/InviteLanding.test.tsx | 35 ++ ui/src/pages/InviteLanding.tsx | 7 +- ui/src/pages/McpConnect.test.tsx | 9 + ui/src/pages/McpConnect.tsx | 4 +- ui/src/pages/PluginManager.tsx | 3 +- ui/src/pages/Secrets.tsx | 5 +- ui/src/pages/SkillStudio.tsx | 5 +- .../StatusCards/StatusCardDetailDrawer.tsx | 3 +- ui/src/pages/TeamCatalog.tsx | 3 +- ui/src/pages/apps/AggregatorAppManager.tsx | 10 +- ui/src/pages/apps/AggregatorConnectDialog.tsx | 6 +- ui/src/pages/apps/AppDetail.tsx | 7 +- ui/src/pages/apps/ArcadeDiscoverySetup.tsx | 5 +- ui/src/pages/apps/AssistantConnection.tsx | 4 +- ui/src/pages/apps/Browse.test.tsx | 10 +- ui/src/pages/apps/Browse.tsx | 20 +- ui/src/pages/apps/ComposioAppManager.tsx | 10 +- ui/src/pages/apps/ComposioAppSetup.tsx | 4 +- ui/src/pages/apps/Connections.tsx | 7 +- ui/src/pages/apps/ExecutorManagementSetup.tsx | 5 +- ui/src/pages/apps/TailscaleConnector.test.tsx | 2 + ui/src/pages/apps/TailscaleConnector.tsx | 12 +- .../apps/app-detail/ActionTestDialog.test.tsx | 4 + .../apps/app-detail/ActionTestDialog.tsx | 15 +- .../app-detail/ConnectedAggregatorApps.tsx | 3 +- .../apps/app-detail/IdentitiesSection.tsx | 19 +- .../apps/app-detail/PermissionsPanel.tsx | 3 +- .../apps/app-detail/StoredContentDeletion.tsx | 3 +- .../pages/apps/chat/ChatConversationList.tsx | 6 +- .../chat/ChatEndpointDetail.replay.test.tsx | 59 +++ ui/src/pages/apps/chat/ChatEndpointDetail.tsx | 20 +- ui/src/pages/apps/chat/ChatEndpointSetup.tsx | 4 +- .../pages/apps/chat/ChatIdentityConfirm.tsx | 8 +- ui/src/pages/apps/chat/EmailEndpointSetup.tsx | 8 +- .../apps/chat/GitHubBotConfiguration.tsx | 12 +- .../pages/apps/chat/GitHubBotManagement.tsx | 3 +- .../pages/apps/chat/GitHubChatSetup.test.tsx | 2 + ui/src/pages/apps/chat/GitHubChatSetup.tsx | 14 +- .../apps/chat/GitHubConnectionComplete.tsx | 6 +- .../apps/chat/GitHubConnectionRecovery.tsx | 4 +- ui/src/pages/apps/chat/SlackAppDetails.tsx | 4 +- ui/src/pages/apps/chat/SlackIdentityStep.tsx | 4 +- .../apps/chat/SlackTestMessageButton.test.tsx | 37 ++ .../apps/chat/SlackTestMessageButton.tsx | 5 +- .../chat/slack/ManagedSlackSetup.test.tsx | 15 + .../apps/chat/slack/ManagedSlackSetup.tsx | 8 +- .../apps/gateways/ConnectClientDialog.tsx | 5 +- .../pages/apps/gateways/EditGatewayDialog.tsx | 4 +- .../pages/apps/gateways/NewGatewayDialog.tsx | 4 +- .../gateways/panels/GatewayActivityPanel.tsx | 6 +- .../gateways/panels/GatewayAdvancedPanel.tsx | 4 +- .../apps/gateways/panels/TokensPanel.test.tsx | 3 + .../apps/gateways/panels/TokensPanel.tsx | 3 +- ui/src/pages/skills/SkillPackagePreview.tsx | 4 +- ui/src/pages/tools/AuditTab.tsx | 5 +- ui/src/pages/tools/GatewaysTab.test.tsx | 45 +- ui/src/pages/tools/GatewaysTab.tsx | 6 +- ui/src/pages/tools/connection-dialogs.tsx | 3 +- ui/src/pages/tools/profiles/ProfileDetail.tsx | 3 +- 196 files changed, 1848 insertions(+), 677 deletions(-) create mode 100644 ui/src/components/AccountQuotaPanels.test.tsx create mode 100644 ui/src/components/AgentSetupPrompt.test.tsx create mode 100644 ui/src/components/ai-connections/AiConnectionAccountControls.test.tsx create mode 100644 ui/src/components/ai-connections/AiConnectionIdentity.test.tsx create mode 100644 ui/src/components/ai-connections/AiConnectionPicker.test.tsx create mode 100644 ui/src/components/ai-connections/AiConnectionPoolRunDetails.test.tsx create mode 100644 ui/src/components/ai-connections/AiConnectionSelect.test.tsx create mode 100644 ui/src/components/routine-triggers/WebhookFields.test.tsx create mode 100644 ui/src/lib/analytics/replay-masking.test.tsx create mode 100644 ui/src/lib/analytics/replay-recording.test-utils.ts delete mode 100644 ui/src/lib/analytics/unmask-allowlist.test.ts create mode 100644 ui/src/pages/apps/chat/ChatEndpointDetail.replay.test.tsx create mode 100644 ui/src/pages/apps/chat/SlackTestMessageButton.test.tsx diff --git a/doc/cloud-browser-analytics.md b/doc/cloud-browser-analytics.md index b52a6dc4805..e9cd8427eca 100644 --- a/doc/cloud-browser-analytics.md +++ b/doc/cloud-browser-analytics.md @@ -93,27 +93,40 @@ This value is used only for location, never for limits. ## Privacy -Masking is deny by default. A surface that nobody marked stays masked. +Session replay shows text by default, the way PostHog normally works. Text is +masked only inside marked customer content. Input values and attribute values +are always masked. -- Session replay masks every input value and every text node. - `maskReplayText` in `ui/src/lib/analytics/privacy.ts` shows text only inside - elements with `ANALYTICS_UNMASK_PROPS`: sidebar items whose label is a fixed - string, and a shared `Button`, `Label`, `TabsTrigger` or `EmptyState` only - when its caller passes `analyticsChrome`. None of them opts in by default, - because they also render customer text such as agent names and titles. +- Session replay masks every input value (`maskAllInputs`). +- Replay masks text only inside these markers (`ANALYTICS_MASK_TEXT_SELECTOR` + in `ui/src/lib/analytics/privacy.ts`, passed as rrweb `maskTextSelector`): + - `ANALYTICS_MASK_CLASS` (`ph-mask ph-sensitive`): customer content. + - `ANALYTICS_NO_CAPTURE_CLASS` (`ph-no-capture`): secrets. Replay blocks + these elements entirely. + - `contenteditable` editors (not `contenteditable="false"`). + + rrweb masks a text node only when its parent matches the selector or has an + ancestor that matches it. All other text, for example navigation, headings, + buttons, task titles, agent names, project names and company names, is + recorded as it is. - Replay also masks attribute values (`maskReplayAttribute`): only layout attributes (`class`, `style`, `role`, `data-state`, SVG geometry and similar), rrweb metadata and stylesheet links keep their values. `title`, `aria-label`, `alt`, `placeholder`, `src`, `href`, `data-*` values and - element references (`id`, `for`, `aria-labelledby`) are always masked, even on unmasked chrome, so images record as empty boxes and - link targets (for example download links with file paths) never leave. -- `ANALYTICS_MASK_CLASS` keeps customer content masked even inside unmasked - chrome: rendered markdown (task bodies, comments, chat messages, documents), - task and issue chat threads, the comment timeline, the rich editor and the - file viewer. Text in a `contenteditable` editor is always masked. + element references (`id`, `for`, `aria-labelledby`) are always masked, so + images record as empty boxes and link targets (for example download links + with file paths) never leave. +- The masking options in `posthog.init` take precedence over the PostHog + project's "Privacy and masking" settings (posthog-js 1.450). posthog-js + ignores the project setting and logs a warning when the two differ. Keep the + project masking settings empty, and change masking only in `privacy.ts`. The + `ph-mask` class is also the posthog-js default `maskTextClass`. - `ANALYTICS_NO_CAPTURE_CLASS` replaces secrets with a blank box in replays: - every password-type `Input`, environment variable values and new secret - values. + every password-type `Input`, environment variable values, new secret + values, and secrets shown as text: one-time sign-in and device codes, + pairing and setup prompts, identity confirmation links, newly issued API + keys and gateway tokens, gateway client snippets, webhook URLs and secrets, + invite claim secrets, raw provider frames and SSH fallback commands. - Every event and replay meta event goes through `scrubCapturedEvent` (`before_send`). Every URL keeps only its origin and path: query and hash values never leave, because they can hold credentials, file paths or search @@ -125,11 +138,72 @@ Masking is deny by default. A surface that nobody marked stays masked. - Autocapture never records element text or attribute values (`mask_all_text`, `mask_all_element_attributes`). It keeps the click, the element tree and the page. -- Connected-account content (Gmail bodies, Calendar events, Slack messages - in tasks, chat, tool results and previews) is Google user data or Slack - data. No human may read it in a replay (Google API Limited Use). It is never - inside the unmask allowlist, and autocapture records no element text at all. - `ui/src/lib/analytics/unmask-allowlist.test.ts` pins the allowlist: a new - unmask needs a reviewed entry there. +- Connected-account content is Google user data or Slack data. No human may + read it in a replay (privacy policy and Google API Limited Use). The + surfaces below, and other free-form text that agents or customers write, + carry `ANALYTICS_MASK_CLASS` on their content element (not on the chrome + around it): + - Rendered markdown (task bodies, comments, chat messages, documents), the + rich editor, task and issue chat threads (messages, tool calls, tool + results, interaction cards), the comment timeline and the file viewer. + - Link preview cards, task quicklook descriptions, external object pills and + rows, and related-work titles. + - Email message cards and email send intents. + - Connection names, connected account names, aliases and email addresses + (Browse rows and the remove dialog, Connections, app detail headers, the + app sidebar, connection choice lists and instructions, aggregator and + Composio account dialogs, Tailscale networks, agent tool and audit + tables, AI connection names, pickers, selects, account details and + controls, pool run details, subscription and quota panels, adapter + sign-in status, connection access and repair cards), GitHub logins + (identity rows, bot people, chat setup, run identity history) and + repositories, Slack workspace names (list and selected value), Slack + account pickers, chat channels, linked user labels, the external task + banner and chat identity pages. + - Connection and account management surfaces are masked by section, not + label by label: the Browse connector list, the App detail body below its + header, the Connections table, Tailscale networks, the chat connection + detail body and its account subtitle, GitHub chat setup, the AI + connection pool editor and the chat identity confirmation. Every dialog, + alert dialog, select (trigger and list), popover, dropdown, sheet and + tooltip under `pages/apps`, `features/connections` and + `components/ai-connections` carries its own mask, because portals escape + the page's masked container; `replay-masking.test.tsx` fails when one + does not. + - App action test results (parsed preview and raw response). + - Inbox and decision rows (subject and detail line), obligation evidence, + Needs You notes and receipts, decision cards and compact decisions, + decision records, and interaction cards (questions, options, answers, + tool action requests, suggested tasks) wherever they render. + - Approval payloads, action card input and reason, recovery card headline, + evidence and options, run ledger retry details and interrupt handoff + previews. + - Run transcripts, run failure details, run events, run stdout and stderr + excerpts (agent page and execution workspace operations), the run + invocation command, notes, prompt, context and environment, Runner + inspector frames, and every preformatted block that shows run output, + tool or webhook payloads, request or response bodies, instructions, + skills or package files. + - Saved connection instructions for agents. + - Document and case revision diffs. + - Search result snippets, toasts (title and body), voice and call + transcripts, case summaries, files and fields, attachment previews and + artifact previews (text, tables, patches and documents). + + Component tests render these surfaces with distinctive fixture text and + assert, through `ui/src/lib/analytics/replay-recording.test-utils.ts`, that + the text is rendered but not recorded (or is blocked, for secrets), + including alternate branches, dialog portals and selected values in + closed pickers. `ui/src/lib/analytics/replay-masking.test.tsx` also pins + the remaining surfaces at source level. A new surface that shows + connected-account content needs the class and a test. +- Residual risk: text that the owner accepted as visible can still hold + customer words. Task titles, agent names, project names, company names, + routine names, artifact and document titles, and activity rows (which name + the task or entity) are recorded as they are. Paperclip member names and + email addresses on member, access and profile pages are recorded too. An + agent can copy email or Slack text into a task title. Masking is opt-in per + surface, so a new surface that renders connected-account content without + the class is recorded until somebody marks it. - The UI never captures an event that the server already sends (`PAPERCLIP_EVENTS`); `product-analytics-events.test.ts` enforces this. diff --git a/ui/src/components/AccountQuotaPanels.test.tsx b/ui/src/components/AccountQuotaPanels.test.tsx new file mode 100644 index 00000000000..b3b77d33fb1 --- /dev/null +++ b/ui/src/components/AccountQuotaPanels.test.tsx @@ -0,0 +1,16 @@ +// @vitest-environment jsdom +import { renderToStaticMarkup } from "react-dom/server"; +import { afterEach, expect, it } from "vitest"; +import { AccountQuotaPanels } from "./AccountQuotaPanels"; +import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils"; + +afterEach(() => { document.body.innerHTML = ""; }); + +it("masks the subscription account label in session replay", () => { + document.body.innerHTML = renderToStaticMarkup(<AccountQuotaPanels accounts={[{ + provider: "anthropic", accountKey: "key", accountLabel: "fenwick.oriel@example.test", ok: true, + windows: [{ label: "Weekly limit", usedPercent: 40, valueLabel: null, resetsAt: null, detail: null }], + }]} />); + expect(replayLeaks("fenwick.oriel@example.test")).toEqual({ rendered: true, recorded: false }); + expect(replayLeaks("Weekly limit")).toEqual({ rendered: true, recorded: true }); +}); diff --git a/ui/src/components/AccountQuotaPanels.tsx b/ui/src/components/AccountQuotaPanels.tsx index 6bea5dcd88e..b36d1a59a5d 100644 --- a/ui/src/components/AccountQuotaPanels.tsx +++ b/ui/src/components/AccountQuotaPanels.tsx @@ -2,6 +2,8 @@ import type { ProviderQuotaResult } from "@paperclipai/shared"; import { formatDateTime } from "../lib/utils"; import { QuotaBar } from "./QuotaBar"; import { quotaUnavailableMessage } from "../lib/quota-refresh"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; export function AccountQuotaPanels({ accounts, @@ -17,7 +19,7 @@ export function AccountQuotaPanels({ className="space-y-2" key={account.accountKey ?? account.provider} > - <p className="text-sm font-medium"> + <p className={cn("text-sm font-medium", ANALYTICS_MASK_CLASS)}> {account.accountLabel ?? "Subscription account"} </p> {(failed || !account.ok) && ( diff --git a/ui/src/components/AdapterLoginChrome.test.tsx b/ui/src/components/AdapterLoginChrome.test.tsx index 8a2008e7f1f..4bde12d3ac1 100644 --- a/ui/src/components/AdapterLoginChrome.test.tsx +++ b/ui/src/components/AdapterLoginChrome.test.tsx @@ -6,11 +6,13 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import type React from "react"; import { + LocalProviderLoginInstructions, OnboardingLoginCard, OnboardingCardField, OnboardingLoginCodeRow, onboardingCardInputClass, } from "./AdapterLoginChrome"; +import { isBlockedFromReplay, replayLeaks } from "@/lib/analytics/replay-recording.test-utils"; /** * The connect step's canvas holds one of two cards, and the credential switch @@ -253,3 +255,27 @@ describe("the displayed code's auto-copy", () => { } }); }); + +describe("session replay", () => { + const login = { preparing: false, error: null, retry: vi.fn() }; + + it("blocks the one-time login code", async () => { + await render(<OnboardingLoginCodeRow code="QZRT-77XKV" />); + expect(isBlockedFromReplay("QZRT-77XKV", document.body)).toBe(true); + }); + + it("blocks the displayed device code in the provider sign-in card", async () => { + await render(<LocalProviderLoginInstructions adapterType="codex_local" login={{ ...login, authorizationUrl: "https://auth.example.test/device", code: "MNPL-48WQD" }} />); + expect(isBlockedFromReplay("MNPL-48WQD", document.body)).toBe(true); + }); + + it("blocks the terminal sign-in command", async () => { + await render(<LocalProviderLoginInstructions adapterType="grok_local" login={{ ...login, command: "grok login --token-hint vexmoor-9182" }} />); + expect(isBlockedFromReplay("grok login --token-hint vexmoor-9182", document.body)).toBe(true); + }); + + it("masks the signed-in account label", async () => { + await render(<LocalProviderLoginInstructions adapterType="claude_local" login={{ ...login, status: "ready", accountLabel: "hollis.brennan@example.test" }} />); + expect(replayLeaks("hollis.brennan@example.test", document.body)).toEqual({ rendered: true, recorded: false }); + }); +}); diff --git a/ui/src/components/AdapterLoginChrome.tsx b/ui/src/components/AdapterLoginChrome.tsx index a1d9031a126..5d0d7e55d9f 100644 --- a/ui/src/components/AdapterLoginChrome.tsx +++ b/ui/src/components/AdapterLoginChrome.tsx @@ -12,6 +12,8 @@ import { COPIED_REVEAL_DELAY_MS, COPIED_REVEAL_TRAVEL, } from "./onboarding/onboarding-motion"; +import { ANALYTICS_MASK_CLASS, ANALYTICS_NO_CAPTURE_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; /** * Which shell a login panel draws itself in. @@ -293,7 +295,7 @@ export function OnboardingLoginCodeRow({ return ( <div className="flex h-(--sz-44px) items-center gap-2 rounded-lg bg-muted px-4"> - <span className="min-w-0 flex-1 truncate text-sm text-foreground"> + <span className={cn("min-w-0 flex-1 truncate text-sm text-foreground", ANALYTICS_NO_CAPTURE_CLASS)}> {code} </span> <AnimatePresence initial={false}> @@ -515,7 +517,7 @@ export function LocalProviderLoginInstructions({ adapterType, login }: { const ready = login?.status === "ready"; return <div className="min-w-0 max-w-full space-y-3 text-sm text-muted-foreground"> {ready ? <> - <p role="status" className="flex items-center gap-2 text-foreground"><Check className="size-4 shrink-0 text-(--status-task-icon-done)" />{login?.accountLabel ?? provider} is signed in. Click Connect to use this account.</p> + <p role="status" className={cn("flex items-center gap-2 text-foreground", ANALYTICS_MASK_CLASS)}><Check className="size-4 shrink-0 text-(--status-task-icon-done)" />{login?.accountLabel ?? provider} is signed in. Click Connect to use this account.</p> {!showCommand && <button type="button" className="underline underline-offset-4" onClick={() => browserLogin ? login?.retry() : setShowCommand(true)}>Use a different account</button>} </> : !browserLogin && <p>{isolated ? `Sign in to ${provider} for this connection on the machine running Paperclip. Your existing terminal login stays separate.` : `Connect uses your local ${provider} account on the machine running Paperclip.`}</p>} {browserLogin && !ready && !login?.authorizationUrl && !login?.error && <p role="status">Preparing browser sign-in…</p>} @@ -537,7 +539,7 @@ export function LocalProviderLoginInstructions({ adapterType, login }: { {!browserLogin && (!ready || showCommand) && !login?.error && <> <p>Run this in a terminal on that machine and finish signing in in your browser. We’ll check automatically when you return.</p> {command && <div className="flex min-w-0 max-w-full items-start gap-2 rounded-md border bg-muted p-3 text-foreground"> - <pre className="min-w-0 flex-1 whitespace-pre-wrap break-all font-mono text-xs"><code>{command}</code></pre> + <pre className={cn("min-w-0 flex-1 whitespace-pre-wrap break-all font-mono text-xs", ANALYTICS_NO_CAPTURE_CLASS)}><code>{command}</code></pre> <LoginCardCopyButton value={command} label="Copy sign-in command" /> </div>} </>} diff --git a/ui/src/components/AgentConfigForm.render.test.tsx b/ui/src/components/AgentConfigForm.render.test.tsx index c6954b204b9..7a617f27211 100644 --- a/ui/src/components/AgentConfigForm.render.test.tsx +++ b/ui/src/components/AgentConfigForm.render.test.tsx @@ -13,6 +13,7 @@ import { ToastProvider } from "../context/ToastContext"; import { AgentConfigForm, AdapterLoginPanel, ModelDropdown, subtractPersistedOverlay, type AdapterLoginDescriptor } from "./AgentConfigForm"; import { AgentLifecycleStatus, useAgentLifecycleStatus } from "./AgentLifecycleStatus"; import { queryKeys } from "../lib/queryKeys"; +import { isBlockedFromReplay } from "@/lib/analytics/replay-recording.test-utils"; import { defaultCreateValues } from "./agent-config-defaults"; import { buildNewAgentHirePayload } from "../lib/new-agent-hire-payload"; import { ApiError } from "../api/client"; @@ -2439,6 +2440,17 @@ describe("AgentConfigForm environment selector", () => { expect(urlIndex).toBeGreaterThan(codeIndex); }); + it("blocks the displayed login code from session replay", async () => { + mockAgentsApi.testEnvironment.mockResolvedValue(AUTH_MISSING_RESULT); + const result = await renderCodexSandbox(); + roots.push(result.root); + + await runTest(result.container); + await startLogin(result.container); + + expect(isBlockedFromReplay("WXYZ-1234", document.body)).toBe(true); + }); + it("keeps the code and URL visible after a later poll returns no prompt", async () => { mockAgentsApi.testEnvironment.mockResolvedValue(AUTH_MISSING_RESULT); // The server delivers the one-time prompt on the first owner read only. The diff --git a/ui/src/components/AgentConfigForm.tsx b/ui/src/components/AgentConfigForm.tsx index 776423e864d..867bbaf209e 100644 --- a/ui/src/components/AgentConfigForm.tsx +++ b/ui/src/components/AgentConfigForm.tsx @@ -113,6 +113,7 @@ import { type CreateConfigValues, } from "@paperclipai/adapter-utils"; import { Badge } from "@/components/ui/badge"; +import { ANALYTICS_NO_CAPTURE_CLASS } from "@/lib/analytics/privacy"; /* ---- Props ---- */ @@ -3053,7 +3054,7 @@ function DisplayedCodeLoginPanel({ <div className="text-(length:--text-micro) uppercase tracking-wide text-muted-foreground"> 1. Code </div> - <span className="font-mono text-xs text-foreground break-all">{prompt.code}</span> + <span className={cn("font-mono text-xs text-foreground break-all", ANALYTICS_NO_CAPTURE_CLASS)}>{prompt.code}</span> </div> <AdapterLoginCopyButton value={prompt.code} label="Copy code" /> </div> diff --git a/ui/src/components/AgentSetupPrompt.test.tsx b/ui/src/components/AgentSetupPrompt.test.tsx new file mode 100644 index 00000000000..66327160a0a --- /dev/null +++ b/ui/src/components/AgentSetupPrompt.test.tsx @@ -0,0 +1,32 @@ +// @vitest-environment jsdom +import { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { AgentSetupPrompt } from "./AgentSetupPrompt"; +import { isBlockedFromReplay } from "@/lib/analytics/replay-recording.test-utils"; + +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +let root: Root; +let container: HTMLDivElement; +beforeEach(() => { + vi.stubGlobal("matchMedia", (query: string) => ({ matches: query.includes("reduce"), media: query, addEventListener: vi.fn(), removeEventListener: vi.fn(), addListener: vi.fn(), removeListener: vi.fn() })); + Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText: vi.fn(async () => {}) } }); + container = document.createElement("div"); + document.body.append(container); + root = createRoot(container); +}); +afterEach(async () => { + await act(async () => root.unmount()); + container.remove(); + vi.unstubAllGlobals(); + Reflect.deleteProperty(navigator, "clipboard"); +}); + +it("blocks the setup prompt preview, which carries pairing tokens, from session replay", async () => { + const prompt = "Run: paperclipai pair --token pcp_pair_8f3kQz2LmWv"; + await act(async () => root.render(<AgentSetupPrompt prompt={prompt} />)); + await act(async () => container.querySelector<HTMLButtonElement>("button")!.click()); + expect(document.querySelector("pre[aria-label='Setup prompt']")).not.toBeNull(); + expect(isBlockedFromReplay("pcp_pair_8f3kQz2LmWv", document.body)).toBe(true); +}); diff --git a/ui/src/components/AgentSetupPrompt.tsx b/ui/src/components/AgentSetupPrompt.tsx index 2119b53ae26..71b15077cb9 100644 --- a/ui/src/components/AgentSetupPrompt.tsx +++ b/ui/src/components/AgentSetupPrompt.tsx @@ -8,6 +8,7 @@ import { usePrefersReducedMotion } from "@/hooks/usePrefersReducedMotion"; import { copyTextToClipboard } from "@/lib/clipboard"; import { motionMilliseconds, motionNumber } from "@/lib/onboarding-motion-tokens"; import { cn } from "@/lib/utils"; +import { ANALYTICS_NO_CAPTURE_CLASS } from "@/lib/analytics/privacy"; export interface AgentSetupPromptProps { /** The complete text to preview and copy; never truncated on the clipboard. */ @@ -244,7 +245,7 @@ export function AgentSetupPrompt({ className="agent-setup-preview resize-none rounded-lg bg-muted/50 p-3 pt-5 font-mono text-xs leading-relaxed" /> ) : ( - <pre tabIndex={0} aria-label="Setup prompt" className="agent-setup-preview m-0 overflow-auto whitespace-pre-wrap break-words rounded-lg border border-border/60 bg-muted/50 p-3 pt-5 font-mono text-xs leading-relaxed text-muted-foreground">{prompt}</pre> + <pre tabIndex={0} aria-label="Setup prompt" className={cn("agent-setup-preview m-0 overflow-auto whitespace-pre-wrap break-words rounded-lg border border-border/60 bg-muted/50 p-3 pt-5 font-mono text-xs leading-relaxed text-muted-foreground", ANALYTICS_NO_CAPTURE_CLASS)}>{prompt}</pre> )} </div> diff --git a/ui/src/components/AppConnectionSidebar.tsx b/ui/src/components/AppConnectionSidebar.tsx index 7b47c716622..e146ebb930b 100644 --- a/ui/src/components/AppConnectionSidebar.tsx +++ b/ui/src/components/AppConnectionSidebar.tsx @@ -24,6 +24,8 @@ import { type AppGalleryDisplayEntry, } from "@/pages/apps/app-definition-display"; import { SidebarNavItem } from "./SidebarNavItem"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; type AppDetailSidebarProps = | { kind: "connection"; connectionId: string } @@ -103,7 +105,7 @@ export function AppDetailSidebar(props: AppDetailSidebarProps) { darkLogoUrl={appDefinitionDarkLogoUrl(logoEntry)} size={28} /> - <span className="flex-1 truncate text-sm font-bold text-foreground">{appName}</span> + <span className={cn("flex-1 truncate text-sm font-bold text-foreground", ANALYTICS_MASK_CLASS)}>{appName}</span> </div> </div> diff --git a/ui/src/components/ApprovalPayload.tsx b/ui/src/components/ApprovalPayload.tsx index 6f8f9752d84..846c628607c 100644 --- a/ui/src/components/ApprovalPayload.tsx +++ b/ui/src/components/ApprovalPayload.tsx @@ -1,6 +1,8 @@ import { UserPlus, Lightbulb, ShieldAlert, ShieldCheck } from "lucide-react"; import { MarkdownBody } from "./MarkdownBody"; import { formatCents } from "../lib/utils"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; export const typeLabel: Record<string, string> = { hire_agent: "Hire Agent", @@ -51,7 +53,7 @@ function PayloadField({ label, value }: { label: string; value: unknown }) { return ( <div className="flex items-center gap-2"> <span className="text-muted-foreground w-20 sm:w-24 shrink-0 text-xs">{label}</span> - <span>{String(value)}</span> + <span className={ANALYTICS_MASK_CLASS}>{String(value)}</span> </div> ); } @@ -116,12 +118,12 @@ export function CeoStrategyPayload({ payload }: { payload: Record<string, unknow <div className="mt-3 space-y-1.5 text-sm"> <PayloadField label="Title" value={payload.title} /> {!!plan && ( - <div className="mt-2 rounded-md bg-muted/40 px-3 py-2 text-sm text-muted-foreground whitespace-pre-wrap font-mono text-xs max-h-48 overflow-y-auto"> + <div className={cn("mt-2 rounded-md bg-muted/40 px-3 py-2 text-sm text-muted-foreground whitespace-pre-wrap font-mono text-xs max-h-48 overflow-y-auto", ANALYTICS_MASK_CLASS)}> {String(plan)} </div> )} {!plan && ( - <pre className="mt-2 rounded-md bg-muted/40 px-3 py-2 text-xs text-muted-foreground overflow-x-auto max-h-48"> + <pre className={cn("mt-2 rounded-md bg-muted/40 px-3 py-2 text-xs text-muted-foreground overflow-x-auto max-h-48", ANALYTICS_MASK_CLASS)}> {JSON.stringify(payload, null, 2)} </pre> )} @@ -143,7 +145,7 @@ export function BudgetOverridePayload({ payload }: { payload: Record<string, unk </div> ) : null} {!!payload.guidance && ( - <p className="text-muted-foreground">{String(payload.guidance)}</p> + <p className={cn("text-muted-foreground", ANALYTICS_MASK_CLASS)}>{String(payload.guidance)}</p> )} </div> ); @@ -229,7 +231,7 @@ function BoardApprovalPayloadContent({ payload }: { payload: Record<string, unkn <p className="text-(length:--text-micro) font-medium uppercase tracking-(--tracking-label) text-muted-foreground"> Proposed comment </p> - <pre className="max-h-48 overflow-auto rounded-lg border border-border/60 bg-muted/50 px-3.5 py-3 font-mono text-xs leading-5 text-muted-foreground whitespace-pre-wrap"> + <pre className={cn("max-h-48 overflow-auto rounded-lg border border-border/60 bg-muted/50 px-3.5 py-3 font-mono text-xs leading-5 text-muted-foreground whitespace-pre-wrap", ANALYTICS_MASK_CLASS)}> {proposedComment} </pre> </div> diff --git a/ui/src/components/AppsSidebar.production.tsx b/ui/src/components/AppsSidebar.production.tsx index cc5153b7f85..bf50e5d4b2c 100644 --- a/ui/src/components/AppsSidebar.production.tsx +++ b/ui/src/components/AppsSidebar.production.tsx @@ -66,8 +66,8 @@ export function AppsSidebar() { Connectors </div> <div className="flex flex-col gap-0.5"> - <SidebarNavItem analyticsChrome to="/apps" label="Browse" icon={Store} end /> - <SidebarNavItem analyticsChrome + <SidebarNavItem to="/apps" label="Browse" icon={Store} end /> + <SidebarNavItem to="/apps/review" label="Review" icon={ShieldQuestion} @@ -83,7 +83,7 @@ export function AppsSidebar() { Advanced setup for developers. Most teams never open this. </p> <div className="flex flex-col gap-0.5"> - <SidebarNavItem analyticsChrome to="/apps/connections" label="Connections" icon={AppWindow} end /> + <SidebarNavItem to="/apps/connections" label="Connections" icon={AppWindow} end /> {developerTabs.map((tab) => ( <SidebarNavItem key={tab.key} diff --git a/ui/src/components/AppsSidebar.tsx b/ui/src/components/AppsSidebar.tsx index 135ab887882..d6bcf310691 100644 --- a/ui/src/components/AppsSidebar.tsx +++ b/ui/src/components/AppsSidebar.tsx @@ -38,8 +38,8 @@ export function AppsSidebar() { className={contextualSidebarStyles.nav} > <div data-slot="contextual-sidebar-group" className={contextualSidebarStyles.group}> - <SidebarNavItem analyticsChrome to="/apps" label="Browse" icon={Store} end /> - <SidebarNavItem analyticsChrome + <SidebarNavItem to="/apps" label="Browse" icon={Store} end /> + <SidebarNavItem to="/apps/review" label="Review" icon={ShieldQuestion} diff --git a/ui/src/components/AttentionObligationEvidence.tsx b/ui/src/components/AttentionObligationEvidence.tsx index 68ed5cac30f..bd935573515 100644 --- a/ui/src/components/AttentionObligationEvidence.tsx +++ b/ui/src/components/AttentionObligationEvidence.tsx @@ -3,6 +3,7 @@ import type { AttentionItem } from "@paperclipai/shared"; import { Link } from "@/lib/router"; import { attentionEvidenceLabel, attentionEvidenceText } from "@/lib/attention-obligations"; import { cn } from "@/lib/utils"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; /** * The rest of one obligation, folded into its lead card (PAP-749 plan §2, @@ -28,7 +29,7 @@ export function AttentionObligationEvidence({ {evidence.map((entry) => { const { title, detail } = attentionEvidenceText(entry); return ( - <li key={entry.id} data-attention-evidence={entry.id} data-attention-evidence-source={entry.sourceKind}> + <li className={ANALYTICS_MASK_CLASS} key={entry.id} data-attention-evidence={entry.id} data-attention-evidence-source={entry.sourceKind}> <span className="font-medium text-foreground">{attentionEvidenceLabel(item, entry)}: </span> {entry.subject.href ? ( <Link to={entry.subject.href} className="inline-flex items-center gap-1 hover:text-foreground"> diff --git a/ui/src/components/AttentionQueueRow.tsx b/ui/src/components/AttentionQueueRow.tsx index 49502a5ccf5..fd92a447bae 100644 --- a/ui/src/components/AttentionQueueRow.tsx +++ b/ui/src/components/AttentionQueueRow.tsx @@ -51,6 +51,7 @@ import { DecisionResolver } from "./DecisionResolver"; import { StalledReviewActions } from "./StalledReviewActions"; import { readIssueReviewPolicyMetadata } from "../lib/review-policy"; import { attentionOtherAudienceUserId } from "../lib/attention-close"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; // Decision-action buttons: a comfortable tap target when the row is narrow // (h-9 / text-sm), shrinking back to the dense pill (h-6 / text-xs) once the @@ -334,10 +335,10 @@ export const AttentionQueueRow = memo(function AttentionQueueRow({ } : {})} > - <span className="line-clamp-2 text-sm font-medium text-foreground" title={item.subject.title ?? undefined}> + <span className={cn("line-clamp-2 text-sm font-medium text-foreground", ANALYTICS_MASK_CLASS)} title={item.subject.title ?? undefined}> {item.subject.title ?? meta.label} </span> - <p className="mt-0.5 line-clamp-2 text-xs text-muted-foreground">{detailLine}</p> + <p className={cn("mt-0.5 line-clamp-2 text-xs text-muted-foreground", ANALYTICS_MASK_CLASS)}>{detailLine}</p> </div> {/* Why this card is here (PAP-749 plan §1, Rule 4): "Why me?", "For diff --git a/ui/src/components/CaseFieldsPanel.tsx b/ui/src/components/CaseFieldsPanel.tsx index e7f2ace84f5..77745886087 100644 --- a/ui/src/components/CaseFieldsPanel.tsx +++ b/ui/src/components/CaseFieldsPanel.tsx @@ -6,6 +6,7 @@ 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 @@ -223,7 +224,7 @@ export function CaseFieldValue({ ); } return ( - <pre className="max-w-full whitespace-pre-wrap break-words font-mono text-xs text-muted-foreground"> + <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> ); @@ -330,7 +331,7 @@ export function CaseFieldsTable({ fields }: { fields: Record<string, unknown> }) return <p className="text-sm text-muted-foreground">No fields set</p>; } return ( - <table aria-label="Case fields" className="w-full table-fixed border-collapse font-mono text-xs leading-5"> + <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"> diff --git a/ui/src/components/CaseRevisionRail.test.tsx b/ui/src/components/CaseRevisionRail.test.tsx index b8cd879771a..20cd3735556 100644 --- a/ui/src/components/CaseRevisionRail.test.tsx +++ b/ui/src/components/CaseRevisionRail.test.tsx @@ -6,6 +6,7 @@ import type { AnchorHTMLAttributes } from "react"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { CaseDocumentRevisions } from "@/api/cases"; +import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils"; import { CaseRevisionRail } from "./CaseRevisionRail"; function act(callback: () => void) { @@ -122,4 +123,18 @@ describe("CaseRevisionRail", () => { expect(container.querySelector('[data-testid="md"]')?.textContent).toBe("# First version"); act(() => root.unmount()); }); + + it("keeps revision diff lines out of session replay", async () => { + mockCasesApi.listRevisions.mockResolvedValue(revisions); + const root = await render(); + const compare = Array.from(container.querySelectorAll("button")).find((b) => /compare|diff/i.test(b.textContent ?? "") || /compare|diff/i.test(b.getAttribute("aria-label") ?? "")); + expect(compare).toBeTruthy(); + act(() => compare!.dispatchEvent(new MouseEvent("click", { bubbles: true }))); + await flush(); + const dialog = document.querySelector('[role="dialog"]'); + expect(dialog).not.toBeNull(); + expect(replayLeaks("Second version", dialog!)).toEqual({ rendered: true, recorded: false }); + expect(replayLeaks("First version", dialog!)).toEqual({ rendered: true, recorded: false }); + act(() => root.unmount()); + }); }); diff --git a/ui/src/components/CaseRevisionRail.tsx b/ui/src/components/CaseRevisionRail.tsx index 7d7de2c546f..1af77b76565 100644 --- a/ui/src/components/CaseRevisionRail.tsx +++ b/ui/src/components/CaseRevisionRail.tsx @@ -14,6 +14,7 @@ import { MarkdownBody } from "@/components/MarkdownBody"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { cn, relativeTime } from "@/lib/utils"; import { Diff } from "lucide-react"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; /** Author + via-issue attribution line for a revision. */ function RevisionByline({ revision }: { revision: CaseDocumentRevision }) { @@ -150,7 +151,7 @@ function CaseDocumentDiffModal({ <span className="select-none px-3 text-center text-muted-foreground"> {markerByKind[row.kind]} </span> - <pre className="overflow-x-auto whitespace-pre-wrap break-words px-3 py-0 text-inherit"> + <pre className={cn("overflow-x-auto whitespace-pre-wrap break-words px-3 py-0 text-inherit", ANALYTICS_MASK_CLASS)}> {row.text.length > 0 ? row.text : " "} </pre> </div> diff --git a/ui/src/components/CompanySettingsSidebar.production.tsx b/ui/src/components/CompanySettingsSidebar.production.tsx index 24adf77aec0..2dd61e2837d 100644 --- a/ui/src/components/CompanySettingsSidebar.production.tsx +++ b/ui/src/components/CompanySettingsSidebar.production.tsx @@ -100,9 +100,9 @@ export function CompanySettingsSidebar() { <nav className="flex-1 min-h-0 overflow-y-auto scrollbar-auto-hide px-3 py-2"> <div className="flex flex-col gap-0.5"> - <SidebarNavItem analyticsChrome to="/company/settings" label="General" icon={SlidersHorizontal} end /> + <SidebarNavItem to="/company/settings" label="General" icon={SlidersHorizontal} end /> {showPage("instance.profile") && ( - <SidebarNavItem analyticsChrome + <SidebarNavItem to={`${INSTANCE_SETTINGS_PATH_PREFIX}/profile`} label="Profile" icon={UserRoundPen} @@ -110,7 +110,7 @@ export function CompanySettingsSidebar() { /> )} {showPage("company.members") && ( - <SidebarNavItem analyticsChrome + <SidebarNavItem to="/company/settings/members" label="Members" icon={Users} @@ -130,22 +130,22 @@ export function CompanySettingsSidebar() { /> ))} {showPage("company.invites") && ( - <SidebarNavItem analyticsChrome to="/company/settings/invites" label="Invites" icon={MailPlus} end /> + <SidebarNavItem to="/company/settings/invites" label="Invites" icon={MailPlus} end /> )} {showPage("company.secrets") && ( - <SidebarNavItem analyticsChrome to="/company/settings/secrets" label="Secrets" icon={KeyRound} end /> + <SidebarNavItem to="/company/settings/secrets" label="Secrets" icon={KeyRound} end /> )} {showPage("instance.environments") && ( - <SidebarNavItem analyticsChrome + <SidebarNavItem to={`${INSTANCE_SETTINGS_PATH_PREFIX}/environments`} label="Environments" icon={MonitorCog} end /> )} - <SidebarNavItem analyticsChrome to="/company/settings/connections" label="Connections" icon={Link2} end /> + <SidebarNavItem to="/company/settings/connections" label="Connections" icon={Link2} end /> {showPage("instance.access") && ( - <SidebarNavItem analyticsChrome + <SidebarNavItem to={`${INSTANCE_SETTINGS_PATH_PREFIX}/access`} label="Access" icon={Shield} @@ -153,7 +153,7 @@ export function CompanySettingsSidebar() { /> )} {showPage("instance.heartbeats") && ( - <SidebarNavItem analyticsChrome + <SidebarNavItem to={`${INSTANCE_SETTINGS_PATH_PREFIX}/heartbeats`} label="Heartbeats" icon={Clock3} @@ -161,20 +161,20 @@ export function CompanySettingsSidebar() { /> )} {showPage("company.export") && ( - <SidebarNavItem analyticsChrome to="/company/export" label="Export" icon={Download} /> + <SidebarNavItem to="/company/export" label="Export" icon={Download} /> )} {!isCloud && showPage("company.import") && ( - <SidebarNavItem analyticsChrome to="/company/import" label="Import" icon={Upload} end /> + <SidebarNavItem to="/company/import" label="Import" icon={Upload} end /> )} {showPage("instance.experimental") && ( - <SidebarNavItem analyticsChrome + <SidebarNavItem to={`${INSTANCE_SETTINGS_PATH_PREFIX}/experimental`} label="Experimental" icon={FlaskConical} /> )} {showPlugins && ( - <SidebarNavItem analyticsChrome + <SidebarNavItem to={`${INSTANCE_SETTINGS_PATH_PREFIX}/plugins`} label="Plugins" icon={Puzzle} @@ -202,7 +202,7 @@ export function CompanySettingsSidebar() { </div> ) : null} {showPage("instance.adapters") && ( - <SidebarNavItem analyticsChrome + <SidebarNavItem to={`${INSTANCE_SETTINGS_PATH_PREFIX}/adapters`} label="Adapters" icon={Cpu} diff --git a/ui/src/components/CompanySettingsSidebar.tsx b/ui/src/components/CompanySettingsSidebar.tsx index 7a7d44fc5ba..0545cdf3176 100644 --- a/ui/src/components/CompanySettingsSidebar.tsx +++ b/ui/src/components/CompanySettingsSidebar.tsx @@ -93,7 +93,7 @@ export function CompanySettingsSidebar() { className="flex h-(--sz-60px) shrink-0 items-center px-3" > <div data-slot="settings-back-group" className={`${primarySidebarStyles.group} w-full`}> - <SidebarNavItem analyticsChrome to="/dashboard" label="Back to app" icon={ArrowLeft} /> + <SidebarNavItem to="/dashboard" label="Back to app" icon={ArrowLeft} /> </div> </div> <nav @@ -102,9 +102,9 @@ export function CompanySettingsSidebar() { className={primarySidebarStyles.nav} > <div data-slot="contextual-sidebar-group" className={primarySidebarStyles.group}> - <SidebarNavItem analyticsChrome to="/company/settings" label="General" icon={SlidersHorizontal} end /> + <SidebarNavItem to="/company/settings" label="General" icon={SlidersHorizontal} end /> {showPage("instance.profile") && ( - <SidebarNavItem analyticsChrome + <SidebarNavItem to={`${INSTANCE_SETTINGS_PATH_PREFIX}/profile`} label="Profile" icon={UserRoundPen} @@ -112,7 +112,7 @@ export function CompanySettingsSidebar() { /> )} {showPage("company.members") && ( - <SidebarNavItem analyticsChrome + <SidebarNavItem to="/company/settings/members" label="Members" icon={Users} @@ -132,19 +132,19 @@ export function CompanySettingsSidebar() { /> ))} {showPage("company.secrets") && ( - <SidebarNavItem analyticsChrome to="/company/settings/secrets" label="Secrets" icon={KeyRound} end /> + <SidebarNavItem to="/company/settings/secrets" label="Secrets" icon={KeyRound} end /> )} {showPage("instance.environments") && ( - <SidebarNavItem analyticsChrome + <SidebarNavItem to={`${INSTANCE_SETTINGS_PATH_PREFIX}/environments`} label="Environments" icon={MonitorCog} end /> )} - <SidebarNavItem analyticsChrome to="/company/settings/connections" label="Connections" icon={Link2} end /> + <SidebarNavItem to="/company/settings/connections" label="Connections" icon={Link2} end /> {showPage("instance.access") && ( - <SidebarNavItem analyticsChrome + <SidebarNavItem to={`${INSTANCE_SETTINGS_PATH_PREFIX}/access`} label="Access" icon={Shield} @@ -152,20 +152,20 @@ export function CompanySettingsSidebar() { /> )} {showPage("company.export") && ( - <SidebarNavItem analyticsChrome to="/company/export" label="Export" icon={Download} /> + <SidebarNavItem to="/company/export" label="Export" icon={Download} /> )} {!isCloud && showPage("company.import") && ( - <SidebarNavItem analyticsChrome to="/company/import" label="Import" icon={Upload} end /> + <SidebarNavItem to="/company/import" label="Import" icon={Upload} end /> )} {showPage("instance.experimental") && ( - <SidebarNavItem analyticsChrome + <SidebarNavItem to={`${INSTANCE_SETTINGS_PATH_PREFIX}/experimental`} label="Experimental" icon={FlaskConical} /> )} {showPlugins && ( - <SidebarNavItem analyticsChrome + <SidebarNavItem to={`${INSTANCE_SETTINGS_PATH_PREFIX}/plugins`} label="Plugins" icon={Puzzle} @@ -193,7 +193,7 @@ export function CompanySettingsSidebar() { </div> ) : null} {showPage("instance.adapters") && ( - <SidebarNavItem analyticsChrome + <SidebarNavItem to={`${INSTANCE_SETTINGS_PATH_PREFIX}/adapters`} label="Adapters" icon={Cpu} diff --git a/ui/src/components/CoordinatorSidebar.tsx b/ui/src/components/CoordinatorSidebar.tsx index c571096459c..8895ac8150c 100644 --- a/ui/src/components/CoordinatorSidebar.tsx +++ b/ui/src/components/CoordinatorSidebar.tsx @@ -167,13 +167,13 @@ export function CoordinatorSidebar({ children }: { children?: ReactNode }) { <div className="design-sidebar-primary"> {rail ? <Tooltip><TooltipTrigger asChild>{newTaskButton}</TooltipTrigger><TooltipContent side="right">New task</TooltipContent></Tooltip> : newTaskButton} <div className="design-sidebar-primary my-2"> - <SidebarNavItem analyticsChrome className="design-sidebar-item" to="/chats" label="Chat" icon={MessageCircle} badge={unreadChatCount} badgeLabel="unread chats" /> + <SidebarNavItem className="design-sidebar-item" to="/chats" label="Chat" icon={MessageCircle} badge={unreadChatCount} badgeLabel="unread chats" /> <div className="group/coordinator-new relative"> - <SidebarNavItem analyticsChrome to="/issues" label="Tasks" icon={CircleCheck} className={cn("design-sidebar-item", !rail && "pr-9")} /> + <SidebarNavItem to="/issues" label="Tasks" icon={CircleCheck} className={cn("design-sidebar-item", !rail && "pr-9")} /> {!rail && <button type="button" aria-label="New task" title="New task" onClick={() => openNewIssue()} className="absolute right-3 top-1/2 -translate-y-1/2 rounded-md p-1 text-muted-foreground opacity-0 transition-opacity group-hover/coordinator-new:opacity-100 group-focus-within/coordinator-new:opacity-100 pointer-coarse:opacity-100 hover:bg-sidebar-accent focus-visible:ring-2 focus-visible:ring-ring"><Plus className="size-4" /></button>} </div> - <SidebarNavItem analyticsChrome className="design-sidebar-item" to="/decisions" label="Inbox" icon={Inbox} badge={attentionCount} badgeLabel="decisions" /> + <SidebarNavItem className="design-sidebar-item" to="/decisions" label="Inbox" icon={Inbox} badge={attentionCount} badgeLabel="decisions" /> {orderedPins.length > 0 && <PinnedNavigationList key={`${companyId}:${userId}`} items={orderedPins} rail={rail} onReorder={pinnedNavigation.reorder} onUnpin={pinnedNavigation.toggle} />} </div> <Flyout open={moreOpen} onOpenChange={setMoreOpen}> diff --git a/ui/src/components/DecisionCard.test.tsx b/ui/src/components/DecisionCard.test.tsx index fe0c90ecce7..c3fcaf10be7 100644 --- a/ui/src/components/DecisionCard.test.tsx +++ b/ui/src/components/DecisionCard.test.tsx @@ -9,6 +9,7 @@ import { DecisionCard, type DecisionIssueRef } from "./DecisionCard"; import type { Decision, DecisionEffectExecution } from "../api/decisions"; import { ThemeProvider } from "../context/ThemeContext"; import { TooltipProvider } from "./ui/tooltip"; +import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils"; let container: HTMLDivElement | null = null; let root: Root | null = null; @@ -319,3 +320,15 @@ describe("DecisionCard", () => { expect(expired.textContent).not.toContain("expiry deadline"); }); }); + +describe("DecisionCard session replay", () => { + it("keeps agent-written option labels, descriptions and field labels out of session replay", () => { + const el = render({ decision: mkDecision({ + options: [{ id: "reply", label: "Reply to Globex renewal", description: "Draft answer to jane@globex.com", effects: [{ type: "comment_on_issue", targetIssueId: "issue-target", staleness: "lenient", bodyMarkdown: "nudge" }] }], + inputs: [{ id: "note", label: "Note for jane@globex.com", type: "text" }] as unknown as Decision["inputs"], + }) }); + expect(replayLeaks("Reply to Globex renewal", el)).toEqual({ rendered: true, recorded: false }); + expect(replayLeaks("Draft answer to jane@globex.com", el)).toEqual({ rendered: true, recorded: false }); + expect(replayLeaks("Note for jane@globex.com", el)).toEqual({ rendered: true, recorded: false }); + }); +}); diff --git a/ui/src/components/DecisionCard.tsx b/ui/src/components/DecisionCard.tsx index a7d128a38f0..692ed40f13a 100644 --- a/ui/src/components/DecisionCard.tsx +++ b/ui/src/components/DecisionCard.tsx @@ -22,6 +22,7 @@ import { Button } from "./ui/button"; import { Input } from "./ui/input"; import { Textarea } from "./ui/textarea"; import { MarkdownBody } from "./MarkdownBody"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; /** * Presentational card for a single Decisions-v1 decision (PAP-14966 / PAP-14939 @@ -325,6 +326,7 @@ export function DecisionCard({ SHELL[tone], dimmed && "opacity-80", className, + ANALYTICS_MASK_CLASS, )} data-decision-state={badgeLabel.toLowerCase()} > diff --git a/ui/src/components/DecisionResolver.test.tsx b/ui/src/components/DecisionResolver.test.tsx index 520bb38d332..25d7be5118b 100644 --- a/ui/src/components/DecisionResolver.test.tsx +++ b/ui/src/components/DecisionResolver.test.tsx @@ -4,6 +4,7 @@ import { flushSync } from "react-dom"; import { createRoot } from "react-dom/client"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { DecisionOutcome } from "../api/decisions"; +import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils"; const state = vi.hoisted(() => ({ issueStatus: "todo", queriedIssueIds: [] as string[] })); @@ -20,7 +21,7 @@ vi.mock("@tanstack/react-query", async (importOriginal) => ({ originIssueId: "origin-1", status: "open", targetSnapshots: { "target-1": { updatedAt: "2026-07-31T00:00:00.000Z" } }, - options: [{ id: "yes", label: "Yes", effects: [ + options: [{ id: "yes", label: "Yes", description: "Send the Globex renewal reply", effects: [ { type: "create_issue", targetIssueId: "target-1", @@ -123,4 +124,13 @@ describe("DecisionResolver", () => { flushSync(() => root.unmount()); }); + + it("keeps the compact view's option text out of session replay", () => { + const root = createRoot(container); + flushSync(() => root.render(<DecisionResolver companyId="company-1" decisionId="decision-1" leading={<span>Lead</span>} />)); + expect(container.querySelector('[data-testid="decision-status"]')).toBeNull(); + expect(replayLeaks("Yes", container).recorded).toBe(false); + expect(replayLeaks("Yes", container).rendered).toBe(true); + flushSync(() => root.unmount()); + }); }); diff --git a/ui/src/components/DecisionResolver.tsx b/ui/src/components/DecisionResolver.tsx index 9d35f4dd881..c425f88b399 100644 --- a/ui/src/components/DecisionResolver.tsx +++ b/ui/src/components/DecisionResolver.tsx @@ -13,6 +13,7 @@ import { MarkdownBody } from "./MarkdownBody"; import { NeedsYouPanel, NeedsYouPanelNote } from "./coordinator/NeedsYouCardKit"; import { Button } from "./ui/button"; import { Textarea } from "./ui/textarea"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; interface DecisionResolverProps { companyId: string; @@ -91,7 +92,7 @@ function CompactDecision({ decision, resolveIssue, targetChanged, busy, errorMes .some((effect) => effect.staleness === "strict" && decisionEffectTargetIssueIds(effect).some((target) => stale.has(target))) ?? false; const body = decision.body?.trim(); return ( - <div className="space-y-4" data-decision-state="pending"> + <div className={cn("space-y-4", ANALYTICS_MASK_CLASS)} data-decision-state="pending"> <div className="space-y-3"> <h2 data-decision-prompt className="text-base font-medium">{decision.title}</h2> {body ? <div className="text-sm text-muted-foreground"><MarkdownBody className="paperclip-markdown-on-accent">{body}</MarkdownBody></div> : null} diff --git a/ui/src/components/DesignSidebar.tsx b/ui/src/components/DesignSidebar.tsx index ecd0941a11f..c0cfd9f0a0e 100644 --- a/ui/src/components/DesignSidebar.tsx +++ b/ui/src/components/DesignSidebar.tsx @@ -30,20 +30,20 @@ export function DesignSidebar({ onNewTask, recentTasks = [] }: { onNewTask: () = <nav className="design-sidebar-navigation" aria-label="Main navigation"> <div className="design-sidebar-primary"> <Button variant="ghost" className="design-sidebar-new-task" onClick={onNewTask}><CirclePlus aria-hidden />New Task</Button> - <SidebarNavItem analyticsChrome className="design-sidebar-item" to={`${root}/dashboard`} label="Dashboard" icon={LayoutDashboard} /> - <SidebarNavItem analyticsChrome className="design-sidebar-item" to={`${root}/chats`} label="Chat" icon={MessageCircle} /> + <SidebarNavItem className="design-sidebar-item" to={`${root}/dashboard`} label="Dashboard" icon={LayoutDashboard} /> + <SidebarNavItem className="design-sidebar-item" to={`${root}/chats`} label="Chat" icon={MessageCircle} /> </div> <SidebarSection label="Work"> - <SidebarNavItem analyticsChrome className="design-sidebar-item" to={`${root}/issues`} label="Tasks" icon={CircleCheck} /> - <SidebarNavItem analyticsChrome className="design-sidebar-item" to={`${root}/projects`} label="Projects" icon={FolderOpen} /> - <SidebarNavItem analyticsChrome className="design-sidebar-item" to={`${root}/routines`} label="Routines" icon={Repeat} /> - <SidebarNavItem analyticsChrome className="design-sidebar-item" to={`${root}/artifacts`} label="Artifacts" icon={Package} /> + <SidebarNavItem className="design-sidebar-item" to={`${root}/issues`} label="Tasks" icon={CircleCheck} /> + <SidebarNavItem className="design-sidebar-item" to={`${root}/projects`} label="Projects" icon={FolderOpen} /> + <SidebarNavItem className="design-sidebar-item" to={`${root}/routines`} label="Routines" icon={Repeat} /> + <SidebarNavItem className="design-sidebar-item" to={`${root}/artifacts`} label="Artifacts" icon={Package} /> </SidebarSection> <SidebarSection label="Org"> - <SidebarNavItem analyticsChrome className="design-sidebar-item" to={`${root}/agents`} label="Agents" icon={Users} /> - <SidebarNavItem analyticsChrome className="design-sidebar-item" to={`${root}/skills`} label="Skills" icon={Boxes} /> - <SidebarNavItem analyticsChrome className="design-sidebar-item" to={`${root}/apps`} label="Connectors" icon={Unplug} /> - <SidebarNavItem analyticsChrome className="design-sidebar-item" to={`${root}/activity`} label="Audit" icon={History} /> + <SidebarNavItem className="design-sidebar-item" to={`${root}/agents`} label="Agents" icon={Users} /> + <SidebarNavItem className="design-sidebar-item" to={`${root}/skills`} label="Skills" icon={Boxes} /> + <SidebarNavItem className="design-sidebar-item" to={`${root}/apps`} label="Connectors" icon={Unplug} /> + <SidebarNavItem className="design-sidebar-item" to={`${root}/activity`} label="Audit" icon={History} /> </SidebarSection> {companyRecentTasks.length > 0 ? <div className="design-sidebar-recents"> <SidebarSection label="Recent Tasks"> diff --git a/ui/src/components/DocumentDiffModal.tsx b/ui/src/components/DocumentDiffModal.tsx index 68f3880d44e..3636f8eee8e 100644 --- a/ui/src/components/DocumentDiffModal.tsx +++ b/ui/src/components/DocumentDiffModal.tsx @@ -20,6 +20,8 @@ import { SelectTrigger, SelectValue, } from "@/components/ui/select"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; function getRevisionLabel(revision: DocumentRevision) { const actor = revision.createdByUserId @@ -168,7 +170,7 @@ export function DocumentDiffModal({ <span className="select-none px-3 text-center text-muted-foreground"> {markerByKind[row.kind]} </span> - <pre className="overflow-x-auto whitespace-pre-wrap break-words px-3 py-0 text-inherit"> + <pre className={cn("overflow-x-auto whitespace-pre-wrap break-words px-3 py-0 text-inherit", ANALYTICS_MASK_CLASS)}> {row.text.length > 0 ? row.text : " "} </pre> </div> diff --git a/ui/src/components/EmailMessageCard.tsx b/ui/src/components/EmailMessageCard.tsx index b1c374e1ac4..7f6157622e8 100644 --- a/ui/src/components/EmailMessageCard.tsx +++ b/ui/src/components/EmailMessageCard.tsx @@ -8,6 +8,8 @@ import type { } from "@paperclipai/shared"; import { useEmailThread } from "@/hooks/useEmailThread"; import { issuesApi } from "@/api/issues"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; const EmailContext = createContext<EmailThreadSummary | null>(null); export function EmailThreadProvider({ companyId, @@ -59,7 +61,7 @@ export function EmailMessageCard({ aria-label={ message.direction === "inbound" ? "Email received" : "Email sent" } - className={contextNotice ? "task-context-notice space-y-3" : "space-y-4 rounded-xl border border-border bg-card p-5"} + className={cn(contextNotice ? "task-context-notice space-y-3" : "space-y-4 rounded-xl border border-border bg-card p-5", ANALYTICS_MASK_CLASS)} > <div className="flex flex-wrap items-center justify-between gap-2"> <span className="flex items-center gap-2 text-sm font-semibold"> diff --git a/ui/src/components/EmailTaskActivity.tsx b/ui/src/components/EmailTaskActivity.tsx index 9a5781d82c4..4c354c1d7e2 100644 --- a/ui/src/components/EmailTaskActivity.tsx +++ b/ui/src/components/EmailTaskActivity.tsx @@ -8,6 +8,8 @@ import { Input } from "@/components/ui/input"; import { describeError } from "@/api/errors"; import { QueryErrorState, useQueryView } from "./QueryView"; import type { EmailPublicationSummary } from "@paperclipai/shared"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; // Email actions belong to the agent's task conversation. Only surface mail // without a task comment yet and delivery outcomes that need attention here. @@ -93,7 +95,7 @@ function EmailDelivery({ {p.request && !p.providerMessageId && ( <article aria-label="Email send intent" - className="task-context-notice space-y-3" + className={cn("task-context-notice space-y-3", ANALYTICS_MASK_CLASS)} > <p className="font-semibold">{p.request.subject ?? "Email reply"}</p> {p.request.to && <p>To: {p.request.to.join(", ")}</p>} diff --git a/ui/src/components/EmptyState.tsx b/ui/src/components/EmptyState.tsx index 9dfe8e40334..1b23884f89f 100644 --- a/ui/src/components/EmptyState.tsx +++ b/ui/src/components/EmptyState.tsx @@ -2,7 +2,6 @@ import { Plus } from "lucide-react"; import type { LucideIcon } from "lucide-react"; import type { ReactNode } from "react"; import { Button } from "@/components/ui/button"; -import { ANALYTICS_UNMASK_PROPS } from "@/lib/analytics/privacy"; interface EmptyStateProps { icon: LucideIcon; @@ -17,8 +16,6 @@ interface EmptyStateProps { onAction?: () => void; /** Hide the leading "+" glyph on the action button (e.g. for a "Set up" CTA). */ hideActionIcon?: boolean; - /** The text is fixed product copy, so session replay may show it. */ - analyticsChrome?: boolean; } export function EmptyState({ @@ -30,10 +27,9 @@ export function EmptyState({ action, onAction, hideActionIcon = false, - analyticsChrome = false, }: EmptyStateProps) { return ( - <div {...(analyticsChrome ? ANALYTICS_UNMASK_PROPS : {})} className={graphic ? "empty-state-artwork flex flex-col items-center justify-center gap-5 py-16 text-center" : "flex flex-col items-center justify-center py-16 text-center"}> + <div className={graphic ? "empty-state-artwork flex flex-col items-center justify-center gap-5 py-16 text-center" : "flex flex-col items-center justify-center py-16 text-center"}> {graphic ? <div className="empty-state-graphic" aria-hidden="true">{graphic}</div> : <div className="bg-muted/50 p-4 mb-4"> <Icon className="h-10 w-10 text-muted-foreground/50" /> </div>} diff --git a/ui/src/components/ExecutionWorkspaceCloseDialog.tsx b/ui/src/components/ExecutionWorkspaceCloseDialog.tsx index 412ea33953a..49470a8679b 100644 --- a/ui/src/components/ExecutionWorkspaceCloseDialog.tsx +++ b/ui/src/components/ExecutionWorkspaceCloseDialog.tsx @@ -17,6 +17,8 @@ import { DialogHeader, DialogTitle, } from "./ui/dialog"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; type ExecutionWorkspaceCloseDialogProps = { workspaceId: string; @@ -268,7 +270,7 @@ export function ExecutionWorkspaceCloseDialog({ <div className="font-medium">{action.label}</div> <div className="mt-1 break-words text-muted-foreground">{action.description}</div> {action.command ? ( - <pre className="mt-2 whitespace-pre-wrap break-all rounded-lg bg-background px-3 py-2 font-mono text-xs text-foreground"> + <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} diff --git a/ui/src/components/ExternalObjectPill.tsx b/ui/src/components/ExternalObjectPill.tsx index adee15645fb..f244da5c884 100644 --- a/ui/src/components/ExternalObjectPill.tsx +++ b/ui/src/components/ExternalObjectPill.tsx @@ -18,6 +18,7 @@ import { externalObjectTypeLabel, } from "../lib/external-objects"; import { cn } from "../lib/utils"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; export interface ExternalObjectPillData { providerKey: string | null; @@ -153,7 +154,7 @@ export function ExternalObjectPill({ sizeClassName="h-3 w-3" label={`${providerLabel}: ${statusLabel}`} /> - <span className="max-w-(--sz-16rem) truncate font-medium">{valueLabel}</span> + <span className={cn("max-w-(--sz-16rem) truncate font-medium", ANALYTICS_MASK_CLASS)}>{valueLabel}</span> </> ); const countSuffix = typeof sourceCount === "number" && sourceCount > 1 ? ( @@ -164,7 +165,7 @@ export function ExternalObjectPill({ {showProviderIcon && ProviderIcon ? ( <ProviderIcon aria-hidden="true" className="h-3 w-3 shrink-0" /> ) : null} - <span className="inline-flex min-w-0 items-center gap-1"> + <span className={cn("inline-flex min-w-0 items-center gap-1", ANALYTICS_MASK_CLASS)}> {labelText} </span> {countSuffix} diff --git a/ui/src/components/FileViewerSheet.tsx b/ui/src/components/FileViewerSheet.tsx index 4a3f558e3b6..400e59be555 100644 --- a/ui/src/components/FileViewerSheet.tsx +++ b/ui/src/components/FileViewerSheet.tsx @@ -356,7 +356,7 @@ export function FileContentViewer({ content, highlightedLine, onLoaded, previewM tabIndex={0} className={cn("paperclip-file-viewer-code min-w-0 flex-1 overflow-auto bg-(--code-bg-resolved) focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset", ANALYTICS_MASK_CLASS)} > - <pre className="m-0 font-mono text-xs leading-5"> + <pre className={cn("m-0 font-mono text-xs leading-5", ANALYTICS_MASK_CLASS)}> {lines.map((lineText, index) => { const lineNumber = index + 1; const isHighlighted = lineNumber === highlightedLine; diff --git a/ui/src/components/InstructionHistory.tsx b/ui/src/components/InstructionHistory.tsx index f9bd3a7c8e9..c8c249c2be5 100644 --- a/ui/src/components/InstructionHistory.tsx +++ b/ui/src/components/InstructionHistory.tsx @@ -5,6 +5,8 @@ import { agentsApi } from "../api/agents"; import { describeError } from "../api/errors"; import { Button } from "./ui/button"; import { QueryErrorState, useQueryView } from "./QueryView"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; export function InstructionHistory({ agentId, @@ -129,13 +131,13 @@ export function InstructionHistory({ {diff.data && ( <> <p className="text-sm text-muted-foreground">Selected revision</p> - <pre className="whitespace-pre-wrap break-words rounded-md border border-border p-3 font-mono text-sm"> + <pre className={cn("whitespace-pre-wrap break-words rounded-md border border-border p-3 font-mono text-sm", ANALYTICS_MASK_CLASS)}> {diff.data.from.content} </pre> <p className="text-sm text-muted-foreground"> Changes from selected revision to current </p> - <pre className="whitespace-pre-wrap break-words rounded-md border border-border p-3 font-mono text-sm"> + <pre className={cn("whitespace-pre-wrap break-words rounded-md border border-border p-3 font-mono text-sm", ANALYTICS_MASK_CLASS)}> {diff.data.removed && `Removed:\n${diff.data.removed}\n`} {diff.data.added && `Added:\n${diff.data.added}`} {!diff.data.removed && diff --git a/ui/src/components/IssueLinkQuicklook.tsx b/ui/src/components/IssueLinkQuicklook.tsx index 106f19f22dc..d7242390c97 100644 --- a/ui/src/components/IssueLinkQuicklook.tsx +++ b/ui/src/components/IssueLinkQuicklook.tsx @@ -16,6 +16,7 @@ import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover import { StatusGlyph } from "@/components/StatusGlyph"; import { ProjectTile } from "@/components/ProjectTile"; import { useFlyoutAppearance } from "@/components/ui/flyout-appearance"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; /* ------------------------------------------------------------------ */ /* Single-flight quicklook store */ @@ -211,7 +212,7 @@ export function IssueQuicklookCard({ </RouterDom.Link> {description ? ( - <p data-slot="task-preview-description" className="text-xs leading-5 text-muted-foreground [display:-webkit-box] [-webkit-box-orient:vertical] [-webkit-line-clamp:4] overflow-hidden"> + <p data-slot="task-preview-description" className={cn("text-xs leading-5 text-muted-foreground [display:-webkit-box] [-webkit-box-orient:vertical] [-webkit-line-clamp:4] overflow-hidden", ANALYTICS_MASK_CLASS)}> {description} </p> ) : null} diff --git a/ui/src/components/IssueRecoveryActionCard.tsx b/ui/src/components/IssueRecoveryActionCard.tsx index ecbec1c8b72..e02af9c234d 100644 --- a/ui/src/components/IssueRecoveryActionCard.tsx +++ b/ui/src/components/IssueRecoveryActionCard.tsx @@ -51,6 +51,7 @@ import { readRecoveryRetryLineage, type RecoveryRetryLineage, } from "@/lib/recovery-lineage"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; export type RecoveryCardCardState = RecoveryDisplayState; export const deriveRecoveryCardState = deriveRecoveryDisplayState; @@ -1167,7 +1168,7 @@ export function IssueRecoveryActionCard({ </> ) : null} </div> - <p className="mt-1 text-sm leading-6">{headline}</p> + <p className={cn("mt-1 text-sm leading-6", ANALYTICS_MASK_CLASS)}>{headline}</p> </div> </header> {variant === "compact" ? null : ( @@ -1306,11 +1307,11 @@ export function IssueRecoveryActionCard({ <MetadataRow label="Evidence"> {evidenceSummary ? ( evidenceSummary.isCode ? ( - <span className="break-words font-mono text-(length:--text-micro) text-foreground/80"> + <span className={cn("break-words font-mono text-(length:--text-micro) text-foreground/80", ANALYTICS_MASK_CLASS)}> {evidenceSummary.text} </span> ) : ( - <span className="text-xs leading-5 text-foreground/80">{evidenceSummary.text}</span> + <span className={cn("text-xs leading-5 text-foreground/80", ANALYTICS_MASK_CLASS)}>{evidenceSummary.text}</span> ) ) : ( <MissingValue /> @@ -1381,7 +1382,7 @@ export function IssueRecoveryActionCard({ )} > <span className="font-medium leading-5">{option.label}</span> - <span className="text-(length:--text-micro) leading-4 text-muted-foreground">{option.description}</span> + <span className={cn("text-(length:--text-micro) leading-4 text-muted-foreground", ANALYTICS_MASK_CLASS)}>{option.description}</span> </button> ))} </div> diff --git a/ui/src/components/IssueRelatedWorkPanel.tsx b/ui/src/components/IssueRelatedWorkPanel.tsx index 6d732628c4f..4909a530a36 100644 --- a/ui/src/components/IssueRelatedWorkPanel.tsx +++ b/ui/src/components/IssueRelatedWorkPanel.tsx @@ -4,6 +4,8 @@ import { ExternalObjectPill } from "./ExternalObjectPill"; import type { IssueExternalObjectGroup } from "../hooks/useIssueExternalObjects"; import { externalObjectToneSeverity } from "../lib/external-objects"; import { Badge } from "@/components/ui/badge"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; type GroupedSource = { label: string; @@ -147,7 +149,7 @@ function ExternalObjectsSection({ > <ExternalObjectPill object={pill} sourceCount={mentionCount} sourceSummary={sourceLabels.join(", ")} /> {pill.displayTitle ? ( - <span className="min-w-0 flex-1 truncate text-sm text-muted-foreground"> + <span className={cn("min-w-0 flex-1 truncate text-sm text-muted-foreground", ANALYTICS_MASK_CLASS)}> {pill.displayTitle} </span> ) : null} diff --git a/ui/src/components/IssueRunLedger.test.tsx b/ui/src/components/IssueRunLedger.test.tsx index 71414b8a808..d194e6d6d4d 100644 --- a/ui/src/components/IssueRunLedger.test.tsx +++ b/ui/src/components/IssueRunLedger.test.tsx @@ -8,6 +8,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { RunForIssue } from "../api/activity"; import type { ActiveRunForIssue } from "../api/heartbeats"; import { IssueRunLedgerContent } from "./IssueRunLedger"; +import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils"; vi.mock("@/lib/router", () => ({ Link: ({ children, to, ...props }: { children: ReactNode; to: string } & ComponentProps<"a">) => ( @@ -319,6 +320,7 @@ describe("IssueRunLedger", () => { expect(container.textContent).toContain("Retry exhausted"); expect(container.textContent).toContain("no further automatic retry will be queued"); expect(container.textContent).toContain("Manual intervention required"); + expect(replayLeaks("Bounded retry exhausted after 4 scheduled attempts", container)).toEqual({ rendered: true, recorded: false }); }); it("labels max-turn stops and continuation retries without confusing them with per-run turns", () => { diff --git a/ui/src/components/IssueRunLedger.tsx b/ui/src/components/IssueRunLedger.tsx index 3c8a34eda75..aa8e465449b 100644 --- a/ui/src/components/IssueRunLedger.tsx +++ b/ui/src/components/IssueRunLedger.tsx @@ -37,6 +37,7 @@ import { runRequestedProviderTrace, } from "./ProviderTraceStatusBadge"; import { readFromIssueChatBootstrap } from "@/lib/issue-chat-bootstrap"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; type IssueRunLedgerProps = { issueId: string; @@ -973,7 +974,7 @@ export function IssueRunLedgerContent({ </div> {retryState ? ( - <div className="rounded-md border border-border/70 bg-accent/20 px-2 py-2 text-xs leading-5 text-muted-foreground"> + <div className={cn("rounded-md border border-border/70 bg-accent/20 px-2 py-2 text-xs leading-5 text-muted-foreground", ANALYTICS_MASK_CLASS)}> {retryState.detail ? <p>{retryState.detail}</p> : null} {retryState.secondary ? ( <p>{retryState.secondary}</p> diff --git a/ui/src/components/IssueThreadInteractionCard.tsx b/ui/src/components/IssueThreadInteractionCard.tsx index f4e4078df38..bea9313e3a7 100644 --- a/ui/src/components/IssueThreadInteractionCard.tsx +++ b/ui/src/components/IssueThreadInteractionCard.tsx @@ -58,6 +58,7 @@ import { DecisionCardFooter } from "./DecisionCardFooter"; import { ToolActionAuditHashCopy } from "./ToolActionAuditHashCopy"; import { NeedsYouPanel, NeedsYouPanelNote, NeedsYouPanelRow } from "./coordinator/NeedsYouCardKit"; import { claimReviseDraftWork, clearReviseDraft, releaseReviseDraftWork, reviseDraftKey, useReviseDraft, type ReviseDraftWork } from "@/lib/revise-draft-store"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; const OTHER_ANSWER_ID = "__paperclip_other__"; @@ -1982,7 +1983,7 @@ function ToolActionResolution({ </button> </CollapsibleTrigger> <CollapsibleContent> - <pre className="mt-2 max-h-64 overflow-auto whitespace-pre-wrap break-words rounded-md bg-muted p-3 font-mono text-xs text-foreground">{formattedOutput}</pre> + <pre className={cn("mt-2 max-h-64 overflow-auto whitespace-pre-wrap break-words rounded-md bg-muted p-3 font-mono text-xs text-foreground", ANALYTICS_MASK_CLASS)}>{formattedOutput}</pre> </CollapsibleContent> </Collapsible> ) : <p className="flex items-center gap-1.5">{status}</p>} @@ -2065,7 +2066,7 @@ function RequestToolActionCard({ const preview = payload.previewMarkdown?.trim() ?? ""; const previewIsLine = Boolean(preview) && !preview.includes("\n") && preview.length <= 120; return ( - <div className="space-y-4 text-foreground"> + <div className={cn("space-y-4 text-foreground", ANALYTICS_MASK_CLASS)}> <div className="space-y-3"> <CompactDecisionAsk>{ask}</CompactDecisionAsk> <CompactDecisionNote note={compactDecisionNote(interaction, [ask, payload.previewMarkdown])} /> @@ -2074,7 +2075,7 @@ function RequestToolActionCard({ {preview && !previewIsLine ? <DecisionPanelMarkdown markdown={preview} lead={false} externalReferences={externalReferences} /> : null} {isPending ? inspectableArguments ? <details> <summary className="cursor-pointer text-xs font-medium text-muted-foreground">Arguments</summary> - <pre className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words font-mono text-xs text-foreground">{payload.argumentsSummaryJson}</pre> + <pre className={cn("mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words font-mono text-xs text-foreground", ANALYTICS_MASK_CLASS)}>{payload.argumentsSummaryJson}</pre> <ToolActionAuditHashCopy hash={payload.argumentsHash} /> </details> : <p className="text-xs text-muted-foreground">Request arguments are unavailable.</p> : null} {isPending ? ( @@ -2116,7 +2117,7 @@ function RequestToolActionCard({ } return ( - <div className="text-foreground"> + <div className={cn("text-foreground", ANALYTICS_MASK_CLASS)}> <div className="flex items-start gap-3"> <span role="img" aria-label={payload.appDisplayName || payload.toolDisplayName}> <AppLogo name={payload.appDisplayName || payload.toolDisplayName} size={36} /> @@ -2131,7 +2132,7 @@ function RequestToolActionCard({ <summary className="cursor-pointer text-xs font-medium text-muted-foreground"> Arguments </summary> - <pre className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words font-mono text-xs text-foreground"> + <pre className={cn("mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words font-mono text-xs text-foreground", ANALYTICS_MASK_CLASS)}> {payload.argumentsSummaryJson} </pre> <ToolActionAuditHashCopy hash={payload.argumentsHash} /> @@ -2885,7 +2886,7 @@ function RequestConnectionAuthorizationCard({ <div className="space-y-3"> <p className="text-sm text-muted-foreground" data-testid="connection-authorization-body">{lead}</p> <DecisionPanel> - <NeedsYouPanelRow icon={<Lock />} title={connectionName && connectionName !== providerName ? `${providerName} · ${connectionName}` : providerName} meta="Not connected" /> + <NeedsYouPanelRow icon={<Lock />} title={connectionName && connectionName !== providerName ? <>{providerName} · <span className={ANALYTICS_MASK_CLASS}>{connectionName}</span></> : providerName} meta="Not connected" /> <NeedsYouPanelNote>{consentSentence}</NeedsYouPanelNote> </DecisionPanel> </div> @@ -4437,7 +4438,7 @@ export function IssueThreadInteractionCard({ if (coordinatorEnabled && !compactDecision && interaction.kind === "suggest_tasks") { return <InteractionAudienceContext.Provider value={audience}> <CoordinatorTaskCommitment interaction={interaction}> - <div className="p-4 space-y-3"> + <div className={cn("p-4 space-y-3", ANALYTICS_MASK_CLASS)}> {interaction.status === "pending" ? <InteractionAudienceLine audience={audience} /> : null} <SuggestTasksCard interaction={interaction} agentMap={agentMap} currentUserId={currentUserId} userLabelMap={userLabelMap} onAcceptInteraction={onAcceptInteraction} onRejectInteraction={onRejectInteraction} /> @@ -4447,7 +4448,7 @@ export function IssueThreadInteractionCard({ } if (!compactDecision && interaction.kind === "connection_intent" && interaction.payload.accessRequest) { return ( - <div id={`interaction-${interaction.id}`}> + <div className={ANALYTICS_MASK_CLASS} id={`interaction-${interaction.id}`}> <ConnectionIntentInteractionBody footerSlot={footerSlot} interaction={interaction} @@ -4526,7 +4527,7 @@ export function IssueThreadInteractionCard({ // denial with the same audience the header states (PAP-17287). <InteractionAudienceContext.Provider value={audience}> <CompactArtifactRowContext.Provider value={compactDecision ? artifactRow : null}> - <div data-presentation={presentationVariant} className={compactDecision ? "coordinator-decision-content space-y-4" : cn("rounded-lg border p-5 shadow-none", styles.shell)}> + <div data-presentation={presentationVariant} className={compactDecision ? cn("coordinator-decision-content space-y-4", ANALYTICS_MASK_CLASS) : cn("rounded-lg border p-5 shadow-none", styles.shell, ANALYTICS_MASK_CLASS)}> {compactDecision ? <> {!bodyNamesDecision ? <CompactDecisionAsk><PromptText>{compactTitle}</PromptText></CompactDecisionAsk> : null} {/* Questions and confirmations put the note under their ask (UI1). */} diff --git a/ui/src/components/LinkPreview.tsx b/ui/src/components/LinkPreview.tsx index d505edc10b7..075a19f5869 100644 --- a/ui/src/components/LinkPreview.tsx +++ b/ui/src/components/LinkPreview.tsx @@ -6,6 +6,8 @@ import type { LinkPreview as Preview, LinkPreviewResult, LinkPreviewState, LinkP import { useLinkPreviewContext, type LinkPreviewContextValue } from "@/context/LinkPreviewContext"; import { timeAgo } from "@/lib/timeAgo"; import { linkPreviewQueryOptions } from "@/lib/link-preview-query"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; export const linkPreviewStateLabel: Record<LinkPreviewState, string> = { unknown: "Status unknown", open: "Open", merged: "Merged", conflicts: "Merge conflicts", draft: "Draft", closed: "Closed", @@ -19,7 +21,7 @@ function PreviewCardContents({ target, preview, loading }: { target: LinkPreview const state = preview?.state ?? "unknown"; const Icon = linkPreviewStateIcon[state] ?? linkPreviewStateIcon.unknown; const updated = preview?.updatedAt && Number.isFinite(Date.parse(preview.updatedAt)) ? preview.updatedAt : null; - return <div className="flex min-w-0 flex-col gap-3" data-link-preview-state={state}> + return <div className={cn("flex min-w-0 flex-col gap-3", ANALYTICS_MASK_CLASS)} data-link-preview-state={state}> <div className="flex items-center gap-2 text-xs text-muted-foreground"> <Icon aria-hidden="true" className="link-preview-status size-4 shrink-0" data-state={state} /> <span className="min-w-0 break-all font-mono">{target.label}</span> diff --git a/ui/src/components/ProjectGitAuthorization.test.tsx b/ui/src/components/ProjectGitAuthorization.test.tsx index c736508f79d..ef833504266 100644 --- a/ui/src/components/ProjectGitAuthorization.test.tsx +++ b/ui/src/components/ProjectGitAuthorization.test.tsx @@ -6,6 +6,7 @@ import type { Project } from "@paperclipai/shared"; import { describe, expect, it, vi } from "vitest"; import { projectsApi } from "@/api/projects"; import { ProjectGitAuthorization } from "./ProjectGitAuthorization"; +import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils"; vi.mock("@/api/projects", () => ({ projectsApi: { @@ -76,4 +77,42 @@ describe("ProjectGitAuthorization", () => { client.clear(); } }); + + it("masks GitHub logins in session replay", async () => { + const saved = { + grantId: "grant-a", + authorizedByUserId: "user-a", + options: [ + { grantId: "grant-a", connectionName: "Work GitHub", login: "saved-octo-quillon" }, + { grantId: "grant-b", connectionName: "Side GitHub", login: "picked-octo-varnell" }, + ], + }; + const client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } }); + client.setQueryData(["project-git-authorization", "company-a", "project-b"], saved); + const container = document.createElement("div"), + root = createRoot(container); + document.body.appendChild(container); + try { + await act(async () => + root.render( + <QueryClientProvider client={client}> + <ProjectGitAuthorization project={{ id: "project-b", companyId: "company-a" } as Project} /> + </QueryClientProvider>, + ), + ); + expect(replayLeaks("saved-octo-quillon", container)).toEqual({ rendered: true, recorded: false }); + const trigger = container.querySelector<HTMLElement>('[role="combobox"]')!; + await act(async () => { + trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })); + }); + expect(replayLeaks("picked-octo-varnell", document.body)).toEqual({ rendered: true, recorded: false }); + const option = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find((item) => item.textContent?.includes("picked-octo-varnell"))!; + await act(async () => option.click()); + expect(replayLeaks("picked-octo-varnell", trigger)).toEqual({ rendered: true, recorded: false }); + } finally { + await act(async () => root.unmount()); + container.remove(); + client.clear(); + } + }); }); diff --git a/ui/src/components/ProjectGitAuthorization.tsx b/ui/src/components/ProjectGitAuthorization.tsx index 966d3a746fc..4930a41a51c 100644 --- a/ui/src/components/ProjectGitAuthorization.tsx +++ b/ui/src/components/ProjectGitAuthorization.tsx @@ -4,6 +4,8 @@ import type { Project } from "@paperclipai/shared"; import { projectsApi } from "@/api/projects"; import { Button } from "./ui/button"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; export function ProjectGitAuthorization({ project }: { project: Project }) { const client = useQueryClient(); @@ -31,7 +33,7 @@ export function ProjectGitAuthorization({ project }: { project: Project }) { Task runs continue to use their own identity. </p> {data?.grantId && ( - <p role="status" className="text-sm"> + <p role="status" className={cn("text-sm", ANALYTICS_MASK_CLASS)}> Authorized:{" "} {data.options.find((option) => option.grantId === data.grantId)?.login ?? "selected grant (unavailable or owned by another member)"} @@ -40,12 +42,12 @@ export function ProjectGitAuthorization({ project }: { project: Project }) { {data && ( <div className="flex flex-wrap gap-2"> <Select value={selected} onValueChange={setSelected} disabled={save.isPending}> - <SelectTrigger aria-label="Your GitHub authorization"> + <SelectTrigger aria-label="Your GitHub authorization" className={ANALYTICS_MASK_CLASS}> <SelectValue placeholder="Select your GitHub account" /> </SelectTrigger> <SelectContent> {data.options.map((option) => ( - <SelectItem key={option.grantId} value={option.grantId}> + <SelectItem key={option.grantId} value={option.grantId} className={ANALYTICS_MASK_CLASS}> {option.login} · {option.connectionName} </SelectItem> ))} diff --git a/ui/src/components/RoutineActivityRow.tsx b/ui/src/components/RoutineActivityRow.tsx index 783383d0cd3..e236047923e 100644 --- a/ui/src/components/RoutineActivityRow.tsx +++ b/ui/src/components/RoutineActivityRow.tsx @@ -2,6 +2,7 @@ import { useState } from "react"; import { ChevronRight } from "lucide-react"; import type { ActivityEvent } from "@paperclipai/shared"; import { cn } from "@/lib/utils"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; export type RoutineActivityEvent = Pick<ActivityEvent, "id" | "action" | "details" | "createdAt">; @@ -89,7 +90,7 @@ export function RoutineActivityRow({ event }: { event: RoutineActivityEvent }) { ) : null} </button> {expanded && hasPayload ? ( - <pre className="mx-2 mb-2 overflow-x-auto rounded-md bg-muted p-3 font-mono text-xs text-foreground"> + <pre className={cn("mx-2 mb-2 overflow-x-auto rounded-md bg-muted p-3 font-mono text-xs text-foreground", ANALYTICS_MASK_CLASS)}> {JSON.stringify(event.details, null, 2)} </pre> ) : null} diff --git a/ui/src/components/RoutineContextualSidebar.tsx b/ui/src/components/RoutineContextualSidebar.tsx index 4e46f247c46..4e562e10226 100644 --- a/ui/src/components/RoutineContextualSidebar.tsx +++ b/ui/src/components/RoutineContextualSidebar.tsx @@ -104,12 +104,12 @@ export function RoutineContextualSidebar({ Operate </p> <div className="flex flex-col gap-0.5"> - <SidebarNavItem analyticsChrome + <SidebarNavItem to={routineDetailHref(routineId, "runs")} label="Runs" icon={Play} /> - <SidebarNavItem analyticsChrome + <SidebarNavItem to={routineDetailHref(routineId, "activity")} label="Activity" icon={Activity} diff --git a/ui/src/components/RoutineHistoryTab.tsx b/ui/src/components/RoutineHistoryTab.tsx index 9a1dcb33456..7641e88beac 100644 --- a/ui/src/components/RoutineHistoryTab.tsx +++ b/ui/src/components/RoutineHistoryTab.tsx @@ -38,6 +38,8 @@ import { Skeleton } from "@/components/ui/skeleton"; import { EmptyState } from "./EmptyState"; import { MarkdownBody } from "./MarkdownBody"; import { Badge } from "@/components/ui/badge"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; type AgentLookup = Map<string, { id: string; name: string }>; type ProjectLookup = Map<string, { id: string; name: string }>; @@ -970,7 +972,7 @@ function DiffTable({ rows }: { rows: DiffRow[] }) { <span className="select-none px-3 text-center text-muted-foreground"> {markerByKind[row.kind]} </span> - <pre className="overflow-x-auto whitespace-pre-wrap break-words px-3 py-0 text-inherit"> + <pre className={cn("overflow-x-auto whitespace-pre-wrap break-words px-3 py-0 text-inherit", ANALYTICS_MASK_CLASS)}> {row.text.length > 0 ? row.text : " "} </pre> </div> diff --git a/ui/src/components/RunnerInspector.test.tsx b/ui/src/components/RunnerInspector.test.tsx index aa8feacc334..c82169023a7 100644 --- a/ui/src/components/RunnerInspector.test.tsx +++ b/ui/src/components/RunnerInspector.test.tsx @@ -7,6 +7,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { ApiError } from "@/api/client"; import { ConnectivityProvider, createConnectivityStore, type ConnectivityStore } from "@/lib/connectivity"; import { RunnerInspector } from "./RunnerInspector"; +import { isBlockedFromReplay, replayLeaks } from "@/lib/analytics/replay-recording.test-utils"; const accessMock = vi.hoisted(() => vi.fn()); const eventsMock = vi.hoisted(() => vi.fn()); @@ -273,6 +274,7 @@ describe("RunnerInspector", () => { flushSync(() => reveal?.click()); await flush(); expect(container.textContent).toContain("run-one-secret"); + expect(isBlockedFromReplay("run-one-secret", document.body)).toBe(true); flushSync(() => root.render( @@ -290,6 +292,44 @@ describe("RunnerInspector", () => { expect(container.textContent).not.toContain("run-one-secret"); }); + it("blocks an exact frame revealed in the trace view from session replay", async () => { + traceMock.mockResolvedValue(traceInspection("run-1", "run-1-redacted")); + revealMock.mockResolvedValue({ + schema: "paperclip.provider_trace_frame.v1", + frameId: 1, + timestamp: "1", + direction: "provider_to_client", + transport: "stdio_jsonl", + provider: "codex", + byteLength: 31, + digest: `sha256:${"b".repeat(64)}`, + rawBase64: btoa(JSON.stringify({ authorization: "Bearer trace-view-Kq72Lx" })), + }); + vi.spyOn(window, "confirm").mockReturnValue(true); + + flushSync(() => + root.render( + <RunnerInspector + runId="run-1" + run={{ status: "succeeded", resultJson: null }} + open + onOpenChange={vi.fn()} + />, + ), + ); + await flush(); + flushSync(() => + Array.from(document.querySelectorAll<HTMLButtonElement>('[role="tab"]')).find((tab) => tab.textContent?.includes("Exact trace"))!.click(), + ); + await flush(); + expect(replayLeaks("run-1-redacted", document.body)).toEqual({ rendered: true, recorded: false }); + flushSync(() => + Array.from(document.querySelectorAll("button")).find((button) => button.textContent?.includes("Reveal exact frame"))!.click(), + ); + await flush(); + expect(isBlockedFromReplay("Bearer trace-view-Kq72Lx", document.body)).toBe(true); + }); + it("clears exact frames when raw-trace access is revoked while open", async () => { traceMock.mockResolvedValue(traceInspection("run-1", "run-1-redacted")); revealMock.mockResolvedValue({ diff --git a/ui/src/components/RunnerInspector.tsx b/ui/src/components/RunnerInspector.tsx index 2af63e0ffe4..285d36f0c29 100644 --- a/ui/src/components/RunnerInspector.tsx +++ b/ui/src/components/RunnerInspector.tsx @@ -57,6 +57,7 @@ import { SheetTitle, } from "@/components/ui/sheet"; import { cn } from "@/lib/utils"; +import { ANALYTICS_MASK_CLASS, ANALYTICS_NO_CAPTURE_CLASS } from "@/lib/analytics/privacy"; import { useCopyAction } from "@/lib/use-copy-action"; type TraceEntry = Record<string, unknown>; @@ -489,7 +490,7 @@ function JsonNode({ function JsonExplorer({ value, label = "Search this JSON" }: { value: unknown; label?: string }) { const [query, setQuery] = useState(""); return ( - <div className="overflow-hidden rounded-md border border-border bg-muted/20"> + <div className={cn("overflow-hidden rounded-md border border-border bg-muted/20", ANALYTICS_MASK_CLASS)}> <div className="relative border-b border-border bg-background/60"> <Search className="absolute left-2.5 top-2.5 h-3.5 w-3.5 text-muted-foreground" /> <Input @@ -1172,7 +1173,7 @@ export function RunnerInspector({ <JsonExplorer value={selectedFrame.parsed} /> {Array.isArray(selectedFrame.withheldPaths) && selectedFrame.withheldPaths.length > 0 ? <div className="flex items-start gap-2 rounded-md border border-border bg-accent/30 px-3 py-2 text-xs text-muted-foreground"><ShieldAlert className="mt-0.5 h-3.5 w-3.5 shrink-0 text-accent-foreground" /><span>Withheld paths: {selectedFrame.withheldPaths.join(", ")}</span></div> : null} {canInspectRaw === true ? <Button size="sm" variant="outline" onClick={() => void reveal(Number(selectedFrame.frameId))}><Eye className="mr-1.5 h-4 w-4" />Reveal exact frame</Button> : null} - {revealedFrame ? <div className="rounded-md border border-destructive/30 p-2"><p className="mb-2 flex items-center gap-1.5 text-xs font-medium text-destructive"><ShieldAlert className="h-3.5 w-3.5" />Exact unredacted frame</p><JsonExplorer value={decodeExactFrame(revealedFrame.rawBase64)} label="Search exact frame" /></div> : null} + {revealedFrame ? <div className={cn("rounded-md border border-destructive/30 p-2", ANALYTICS_NO_CAPTURE_CLASS)}><p className="mb-2 flex items-center gap-1.5 text-xs font-medium text-destructive"><ShieldAlert className="h-3.5 w-3.5" />Exact unredacted frame</p><JsonExplorer value={decodeExactFrame(revealedFrame.rawBase64)} label="Search exact frame" /></div> : null} </div> ) : <p className="text-sm text-muted-foreground">This PRP event has no recoverable raw frame.</p>} </section> @@ -1226,7 +1227,7 @@ export function RunnerInspector({ {view === "trace" ? ( <div className="grid min-h-0 flex-1 md:grid-cols-(--gtc-runner-inspector-trace)"> <ScrollArea className="border-r border-border"><div className="p-2">{frames.length ? [...frames].sort((left, right) => Number(left.frameId) - Number(right.frameId)).map((frame) => <button key={Number(frame.frameId)} type="button" onClick={() => { const operation = operations.find((candidate) => candidate.frames.some((candidateFrame) => Number(candidateFrame.frameId) === Number(frame.frameId))); if (operation) setSelectedKey(operation.key); setSelectedFrameId(Number(frame.frameId)); }} className={cn("mb-1 w-full rounded-md border px-3 py-2 text-left", Number(frame.frameId) === Number(selectedFrame?.frameId) ? "border-primary/40 bg-primary/10" : "border-transparent hover:bg-muted/50")}><span className="flex items-center gap-2 text-sm font-medium"><span className="font-mono text-xs text-muted-foreground">#{String(frame.frameId)}</span><span className="truncate">{frameMethod(frame) || text(frame.direction)}</span></span><span className="mt-1 block text-(length:--text-nano) text-muted-foreground">{text(frame.direction).replaceAll("_", " ")} · {formatBytes(Number(frame.byteLength) || 0)}</span></button>) : <p className="p-3 text-sm text-muted-foreground">No raw frames were captured for this run.</p>}</div></ScrollArea> - <ScrollArea><div className="space-y-3 p-5">{selectedFrame ? <><div className="flex flex-wrap items-center gap-2"><h3 className="text-sm font-semibold">Exact trace frame #{String(selectedFrame.frameId)}</h3><Badge variant="outline">{frameMethod(selectedFrame) || text(selectedFrame.direction)}</Badge></div><JsonExplorer value={selectedFrame.parsed} />{canInspectRaw === true ? <Button size="sm" variant="outline" onClick={() => void reveal(Number(selectedFrame.frameId))}><Eye className="mr-1.5 h-4 w-4" />Reveal exact frame</Button> : null}{revealedFrame ? <JsonExplorer value={decodeExactFrame(revealedFrame.rawBase64)} label="Search exact frame" /> : null}</> : <p className="text-sm text-muted-foreground">Select a frame from the chronological trace.</p>}</div></ScrollArea> + <ScrollArea><div className="space-y-3 p-5">{selectedFrame ? <><div className="flex flex-wrap items-center gap-2"><h3 className="text-sm font-semibold">Exact trace frame #{String(selectedFrame.frameId)}</h3><Badge variant="outline">{frameMethod(selectedFrame) || text(selectedFrame.direction)}</Badge></div><JsonExplorer value={selectedFrame.parsed} />{canInspectRaw === true ? <Button size="sm" variant="outline" onClick={() => void reveal(Number(selectedFrame.frameId))}><Eye className="mr-1.5 h-4 w-4" />Reveal exact frame</Button> : null}{revealedFrame ? <div className={ANALYTICS_NO_CAPTURE_CLASS}><JsonExplorer value={decodeExactFrame(revealedFrame.rawBase64)} label="Search exact frame" /></div> : null}</> : <p className="text-sm text-muted-foreground">Select a frame from the chronological trace.</p>}</div></ScrollArea> </div> ) : null} diff --git a/ui/src/components/Sidebar.production.tsx b/ui/src/components/Sidebar.production.tsx index 766485d84c5..21f79a5aad7 100644 --- a/ui/src/components/Sidebar.production.tsx +++ b/ui/src/components/Sidebar.production.tsx @@ -149,9 +149,9 @@ export function Sidebar() { width; a nav row also keeps search reachable from the collapsed rail, where the old header icon was dropped entirely. Cmd/Ctrl+K remains the keyboard path (command palette). */} - <SidebarNavItem analyticsChrome to="/search" label="Search" icon={Search} /> - <SidebarNavItem analyticsChrome to="/dashboard" label="Dashboard" icon={LayoutDashboard} liveCount={liveRunCount} /> - <SidebarNavItem analyticsChrome + <SidebarNavItem to="/search" label="Search" icon={Search} /> + <SidebarNavItem to="/dashboard" label="Dashboard" icon={LayoutDashboard} liveCount={liveRunCount} /> + <SidebarNavItem to="/inbox" label="Inbox" icon={Inbox} @@ -161,7 +161,7 @@ export function Sidebar() { alert={inboxBadge.failedRuns > 0} /> {showDecisions ? ( - <SidebarNavItem analyticsChrome + <SidebarNavItem to="/decisions" label="Decisions" icon={ListChecks} @@ -170,21 +170,21 @@ export function Sidebar() { /> ) : null} {showStatusCards ? ( - <SidebarNavItem analyticsChrome to="/status" label="Status" icon={LayoutGrid} textBadge="beta" /> + <SidebarNavItem to="/status" label="Status" icon={LayoutGrid} textBadge="beta" /> ) : null} {conferenceRoomChatEnabled ? ( - <SidebarNavItem analyticsChrome to="/board-chat" label="Conference Room" icon={MessagesSquare} /> + <SidebarNavItem to="/board-chat" label="Conference Room" icon={MessagesSquare} /> ) : null} </div> <SidebarSection label="Work" collapsible={{ open: workOpen, onOpenChange: setWorkOpen }}> - <SidebarNavItem analyticsChrome to="/issues" label="Tasks" icon={CircleDot} /> + <SidebarNavItem to="/issues" label="Tasks" icon={CircleDot} /> {showCases ? ( - <SidebarNavItem analyticsChrome to="/cases" label="Cases" icon={Layers} textBadge="beta" /> + <SidebarNavItem to="/cases" label="Cases" icon={Layers} textBadge="beta" /> ) : null} - <SidebarNavItem analyticsChrome to="/routines" label="Routines" icon={Repeat} /> + <SidebarNavItem to="/routines" label="Routines" icon={Repeat} /> {showGoalsLink ? ( - <SidebarNavItem analyticsChrome to="/goals" label="Goals" icon={Target} /> + <SidebarNavItem to="/goals" label="Goals" icon={Target} /> ) : goalsLinkPending ? ( <div data-testid="sidebar-goals-placeholder" @@ -192,14 +192,14 @@ export function Sidebar() { aria-hidden="true" /> ) : null} - <SidebarNavItem analyticsChrome to="/artifacts" label="Artifacts" icon={Package} /> - <SidebarNavItem analyticsChrome to="/skills" label="Skills" icon={Boxes} /> + <SidebarNavItem to="/artifacts" label="Artifacts" icon={Package} /> + <SidebarNavItem to="/skills" label="Skills" icon={Boxes} /> {showWorkspacesLink ? ( - <SidebarNavItem analyticsChrome to="/workspaces" label="Workspaces" icon={GitBranch} /> + <SidebarNavItem to="/workspaces" label="Workspaces" icon={GitBranch} /> ) : null} {streamlined ? ( <> - <SidebarNavItem analyticsChrome to="/projects" label="Projects" icon={FolderOpen} /> + <SidebarNavItem to="/projects" label="Projects" icon={FolderOpen} /> <SidebarStarredProjects /> </> ) : null} @@ -224,14 +224,14 @@ export function Sidebar() { <SidebarAgents streamlined={streamlined} /> <SidebarSection label="Company" collapsible={{ open: companyOpen, onOpenChange: setCompanyOpen }}> - <SidebarNavItem analyticsChrome to="/org" label="Org" icon={Network} /> - {showApps ? <SidebarNavItem analyticsChrome to="/apps" label="Connectors" icon={Unplug} /> : null} - <SidebarNavItem analyticsChrome to="/timeline" label="Timeline" icon={GanttChartSquare} /> - <SidebarNavItem analyticsChrome to="/costs" label="Costs" icon={DollarSign} /> + <SidebarNavItem to="/org" label="Org" icon={Network} /> + {showApps ? <SidebarNavItem to="/apps" label="Connectors" icon={Unplug} /> : null} + <SidebarNavItem to="/timeline" label="Timeline" icon={GanttChartSquare} /> + <SidebarNavItem to="/costs" label="Costs" icon={DollarSign} /> {/* One entry — /audit merged into the rich Activity feed (PAP-16302). */} - <SidebarNavItem analyticsChrome to="/activity" label="Activity" icon={History} /> - <SidebarNavItem analyticsChrome to="/activity/commentary" label="Commentary" icon={History} /> - <SidebarNavItem analyticsChrome to="/company/settings" label="Settings" icon={Settings} /> + <SidebarNavItem to="/activity" label="Activity" icon={History} /> + <SidebarNavItem to="/activity/commentary" label="Commentary" icon={History} /> + <SidebarNavItem to="/company/settings" label="Settings" icon={Settings} /> </SidebarSection> <PluginSlotOutlet diff --git a/ui/src/components/Sidebar.tsx b/ui/src/components/Sidebar.tsx index 5d4f3224ab3..8d4a9df0b3a 100644 --- a/ui/src/components/Sidebar.tsx +++ b/ui/src/components/Sidebar.tsx @@ -176,10 +176,10 @@ function ClassicSidebar({ children }: { children?: ReactNode }) { width; a nav row also keeps search reachable from the collapsed rail, where the old header icon was dropped entirely. Cmd/Ctrl+K remains the keyboard path (command palette). */} - <SidebarNavItem analyticsChrome to="/search" label="Search" icon={Search} /> - <SidebarNavItem analyticsChrome to="/dashboard" label="Dashboard" icon={LayoutDashboard} liveCount={liveRunCount} /> + <SidebarNavItem to="/search" label="Search" icon={Search} /> + <SidebarNavItem to="/dashboard" label="Dashboard" icon={LayoutDashboard} liveCount={liveRunCount} /> {!combinedInboxTasks ? ( - <SidebarNavItem analyticsChrome + <SidebarNavItem to="/inbox" label="Inbox" icon={Inbox} @@ -189,9 +189,9 @@ function ClassicSidebar({ children }: { children?: ReactNode }) { alert={inboxBadge.failedRuns > 0} /> ) : null} - {agentChatEnabled && !chatRail ? <SidebarNavItem analyticsChrome to="/chats" label="Chat" icon={MessageCircle} badge={unreadChatCount} badgeLabel="unread chats" /> : null} + {agentChatEnabled && !chatRail ? <SidebarNavItem to="/chats" label="Chat" icon={MessageCircle} badge={unreadChatCount} badgeLabel="unread chats" /> : null} {showDecisions ? ( - <SidebarNavItem analyticsChrome + <SidebarNavItem to="/decisions" label="Decisions" icon={ListChecks} @@ -200,10 +200,10 @@ function ClassicSidebar({ children }: { children?: ReactNode }) { /> ) : null} {showStatusCards ? ( - <SidebarNavItem analyticsChrome to="/status" label="Status" icon={LayoutGrid} textBadge="beta" /> + <SidebarNavItem to="/status" label="Status" icon={LayoutGrid} textBadge="beta" /> ) : null} {conferenceRoomChatEnabled ? ( - <SidebarNavItem analyticsChrome to="/board-chat" label="Conference Room" icon={MessagesSquare} /> + <SidebarNavItem to="/board-chat" label="Conference Room" icon={MessagesSquare} /> ) : null} </div> @@ -212,12 +212,12 @@ function ClassicSidebar({ children }: { children?: ReactNode }) { agents you talk to live in the Chat surface's own secondary rail (ChatContextualSidebar), not in the primary nav. */} {chatRail ? ( - <SidebarNavItem analyticsChrome to="/chats" label="Chat" icon={MessageCircle} badge={unreadChatCount} badgeLabel="unread chats" /> + <SidebarNavItem to="/chats" label="Chat" icon={MessageCircle} badge={unreadChatCount} badgeLabel="unread chats" /> ) : null} {/* Combined Inbox + Task List: Inbox is a view inside Tasks, so the unread/failed-run badge rides on Tasks. */} {combinedInboxTasks ? ( - <SidebarNavItem analyticsChrome + <SidebarNavItem to="/issues" label="Tasks" icon={CircleCheck} @@ -227,21 +227,21 @@ function ClassicSidebar({ children }: { children?: ReactNode }) { alert={inboxBadge.failedRuns > 0} /> ) : ( - <SidebarNavItem analyticsChrome to="/issues" label="Tasks" icon={CircleCheck} /> + <SidebarNavItem to="/issues" label="Tasks" icon={CircleCheck} /> )} {streamlinedUiEnabled ? ( <> - <SidebarNavItem analyticsChrome to="/projects" label="Projects" icon={FolderOpen} /> + <SidebarNavItem to="/projects" label="Projects" icon={FolderOpen} /> <SidebarStarredProjects /> </> ) : null} - <SidebarNavItem analyticsChrome to="/routines" label="Routines" icon={Repeat} /> - <SidebarNavItem analyticsChrome to="/artifacts" label="Artifacts" icon={Package} /> + <SidebarNavItem to="/routines" label="Routines" icon={Repeat} /> + <SidebarNavItem to="/artifacts" label="Artifacts" icon={Package} /> {showCases ? ( - <SidebarNavItem analyticsChrome to="/cases" label="Cases" icon={Layers} textBadge="beta" /> + <SidebarNavItem to="/cases" label="Cases" icon={Layers} textBadge="beta" /> ) : null} {showGoalsLink ? ( - <SidebarNavItem analyticsChrome to="/goals" label="Goals" icon={Target} /> + <SidebarNavItem to="/goals" label="Goals" icon={Target} /> ) : goalsLinkPending ? ( <div data-testid="sidebar-goals-placeholder" @@ -250,7 +250,7 @@ function ClassicSidebar({ children }: { children?: ReactNode }) { /> ) : null} {showWorkspacesLink ? ( - <SidebarNavItem analyticsChrome to="/workspaces" label="Workspaces" icon={GitBranch} /> + <SidebarNavItem to="/workspaces" label="Workspaces" icon={GitBranch} /> ) : null} <PluginSlotOutlet slotTypes={["sidebar"]} @@ -272,10 +272,10 @@ function ClassicSidebar({ children }: { children?: ReactNode }) { label="Org" collapsible={{ open: organizationOpen, onOpenChange: setOrganizationOpen }} > - <SidebarNavItem analyticsChrome to="/agents" label="Agents" icon={Users} /> - <SidebarNavItem analyticsChrome to="/skills" label="Skills" icon={Boxes} /> - <SidebarNavItem analyticsChrome to="/apps" label="Connectors" icon={Unplug} /> - <SidebarNavItem analyticsChrome to="/activity" label="Audit" icon={History} /> + <SidebarNavItem to="/agents" label="Agents" icon={Users} /> + <SidebarNavItem to="/skills" label="Skills" icon={Boxes} /> + <SidebarNavItem to="/apps" label="Connectors" icon={Unplug} /> + <SidebarNavItem to="/activity" label="Audit" icon={History} /> </SidebarSection> ) : null} @@ -291,13 +291,13 @@ function ClassicSidebar({ children }: { children?: ReactNode }) { label="Organization" collapsible={{ open: organizationOpen, onOpenChange: setOrganizationOpen }} > - <SidebarNavItem analyticsChrome to="/org" label="Org" icon={Network} /> - <SidebarNavItem analyticsChrome to="/apps" label="Connectors" icon={Unplug} /> - <SidebarNavItem analyticsChrome to="/timeline" label="Timeline" icon={GanttChartSquare} /> - <SidebarNavItem analyticsChrome to="/costs" label="Costs" icon={DollarSign} /> - <SidebarNavItem analyticsChrome to="/activity" label="Activity" icon={History} /> - <SidebarNavItem analyticsChrome to="/activity/commentary" label="Commentary" icon={History} /> - <SidebarNavItem analyticsChrome to="/company/settings" label="Settings" icon={Settings} /> + <SidebarNavItem to="/org" label="Org" icon={Network} /> + <SidebarNavItem to="/apps" label="Connectors" icon={Unplug} /> + <SidebarNavItem to="/timeline" label="Timeline" icon={GanttChartSquare} /> + <SidebarNavItem to="/costs" label="Costs" icon={DollarSign} /> + <SidebarNavItem to="/activity" label="Activity" icon={History} /> + <SidebarNavItem to="/activity/commentary" label="Commentary" icon={History} /> + <SidebarNavItem to="/company/settings" label="Settings" icon={Settings} /> </SidebarSection> </> )} diff --git a/ui/src/components/SidebarNavItem.production.tsx b/ui/src/components/SidebarNavItem.production.tsx index 53e015d10ca..c7034179c89 100644 --- a/ui/src/components/SidebarNavItem.production.tsx +++ b/ui/src/components/SidebarNavItem.production.tsx @@ -2,7 +2,6 @@ import { createContext, useContext, type ReactNode } from "react"; import { NavLink } from "@/lib/router"; import { SIDEBAR_SCROLL_RESET_STATE } from "../lib/navigation-scroll"; import { cn, SIDEBAR_RAIL_HIDDEN_LABEL } from "../lib/utils"; -import { ANALYTICS_UNMASK_PROPS } from "@/lib/analytics/privacy"; import { useSidebar } from "../context/SidebarContext"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; import type { LucideIcon } from "lucide-react"; @@ -36,8 +35,6 @@ export function useSidebarNavExpanded() { interface SidebarNavItemProps { to: string; label: string; - /** The label is fixed product copy, so session replay may show it. */ - analyticsChrome?: boolean; icon?: LucideIcon; /** * Pre-rendered icon element for rows whose icon isn't a plain Lucide @@ -75,7 +72,6 @@ interface SidebarNavItemProps { export function SidebarNavItem({ to, label, - analyticsChrome = false, icon: Icon, iconNode, end, @@ -123,7 +119,6 @@ export function SidebarNavItem({ to={to} state={SIDEBAR_SCROLL_RESET_STATE} end={end} - {...(analyticsChrome ? ANALYTICS_UNMASK_PROPS : {})} aria-label={railAriaLabel} onClick={() => { if (isMobile) setSidebarOpen(false); }} className={({ isActive }) => diff --git a/ui/src/components/SidebarNavItem.tsx b/ui/src/components/SidebarNavItem.tsx index 479fd4e6ec0..6c77c4eedd2 100644 --- a/ui/src/components/SidebarNavItem.tsx +++ b/ui/src/components/SidebarNavItem.tsx @@ -3,7 +3,6 @@ import { NavLink } from "@/lib/router"; import type { IssueNavigationPrefetchHandlers } from "@/hooks/useIssueNavigationPrefetch"; import { SIDEBAR_SCROLL_RESET_STATE } from "../lib/navigation-scroll"; import { cn, SIDEBAR_RAIL_HIDDEN_LABEL } from "../lib/utils"; -import { ANALYTICS_UNMASK_PROPS } from "@/lib/analytics/privacy"; import { useSidebar } from "../context/SidebarContext"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; import type { LucideIcon } from "lucide-react"; @@ -36,8 +35,6 @@ export function useSidebarNavExpanded() { interface SidebarNavItemProps { to: string; label: string; - /** The label is fixed product copy, so session replay may show it. */ - analyticsChrome?: boolean; icon?: LucideIcon; /** * Pre-rendered icon element for rows whose icon isn't a plain Lucide @@ -77,7 +74,6 @@ interface SidebarNavItemProps { export function SidebarNavItem({ to, label, - analyticsChrome = false, icon: Icon, iconNode, end, @@ -127,7 +123,6 @@ export function SidebarNavItem({ to={to} state={SIDEBAR_SCROLL_RESET_STATE} end={end} - {...(analyticsChrome ? ANALYTICS_UNMASK_PROPS : {})} aria-label={railAriaLabel} {...linkHandlers} onClick={() => { if (isMobile) setSidebarOpen(false); }} diff --git a/ui/src/components/SkillsContextualSidebar.tsx b/ui/src/components/SkillsContextualSidebar.tsx index 6093d147f17..f9493f5e7ee 100644 --- a/ui/src/components/SkillsContextualSidebar.tsx +++ b/ui/src/components/SkillsContextualSidebar.tsx @@ -36,21 +36,21 @@ export function SkillsContextualSidebar() { className={contextualSidebarStyles.nav} > <div data-slot="contextual-sidebar-group" className={contextualSidebarStyles.group}> - <SidebarNavItem analyticsChrome + <SidebarNavItem to={SKILLS_NAVIGATION_HREFS.installed} label="Installed" icon={Library} active={activeView === "installed"} end /> - <SidebarNavItem analyticsChrome + <SidebarNavItem to={SKILLS_NAVIGATION_HREFS.discover} label="Discover" icon={Compass} active={activeView === "discover"} end /> - <SidebarNavItem analyticsChrome to={SKILLS_NAVIGATION_HREFS.sources} label="Sources" icon={GithubIcon} active={activeView === "sources"} /> + <SidebarNavItem to={SKILLS_NAVIGATION_HREFS.sources} label="Sources" icon={GithubIcon} active={activeView === "sources"} /> </div> <div data-slot="contextual-sidebar-section" className={contextualSidebarStyles.section}> @@ -67,7 +67,7 @@ export function SkillsContextualSidebar() { Skills you create, edit, and test. </p> <div data-slot="contextual-sidebar-group" className={contextualSidebarStyles.group}> - <SidebarNavItem analyticsChrome + <SidebarNavItem to={SKILLS_NAVIGATION_HREFS.authored} label="My Skills" icon={PencilRuler} diff --git a/ui/src/components/SubscriptionCostCard.test.tsx b/ui/src/components/SubscriptionCostCard.test.tsx index 221d17336e4..47d0fdf9d5e 100644 --- a/ui/src/components/SubscriptionCostCard.test.tsx +++ b/ui/src/components/SubscriptionCostCard.test.tsx @@ -5,6 +5,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { SubscriptionCostReport } from "@paperclipai/shared"; import { SubscriptionCostCard } from "./SubscriptionCostCard"; +import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils"; const mocks = vi.hoisted(() => ({ update: vi.fn(), link: vi.fn() })); vi.mock("../api/subscriptions", () => ({ subscriptionsApi: mocks })); @@ -132,4 +133,14 @@ describe("subscription costs", () => { await click("Link accounts"); await vi.waitFor(() => expect(mocks.link).toHaveBeenCalledWith("company", "account-1", "account-2", 0, 3)); }); + it("masks subscription account and owner names in session replay", async () => { + const report = fixture(); + report.accounts[0] = { ...report.accounts[0], name: "Thistlewood Claude", ownerName: "Marisol Quenby" }; + report.accounts.push({ ...report.accounts[0], id: "account-2", name: "Larkspur Claude seat", price: { ...report.accounts[0].price, revision: 3 } }); + await render(report); await click("View details"); + expect(replayLeaks("Thistlewood Claude", document.body)).toEqual({ rendered: true, recorded: false }); + expect(replayLeaks("Marisol Quenby", document.body)).toEqual({ rendered: true, recorded: false }); + await click("Edit price"); + expect(replayLeaks("Larkspur Claude seat", document.body)).toEqual({ rendered: true, recorded: false }); + }); }); diff --git a/ui/src/components/SubscriptionCostCard.tsx b/ui/src/components/SubscriptionCostCard.tsx index 83bccc8c8a9..05dfcda3294 100644 --- a/ui/src/components/SubscriptionCostCard.tsx +++ b/ui/src/components/SubscriptionCostCard.tsx @@ -2,13 +2,14 @@ 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 { formatCents, formatDateTime, formatTokens, providerDisplayName } from "../lib/utils"; +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)) @@ -55,7 +56,7 @@ function SubscriptionEditor({ account, accounts, companyId, onDone }: { </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={selectClass} 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> + <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> @@ -97,7 +98,7 @@ export function SubscriptionCostCard({ companyId, report, error, onChanged }: { {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><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={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} /> diff --git a/ui/src/components/TailscaleSshMachine.tsx b/ui/src/components/TailscaleSshMachine.tsx index d7756508ecf..c1815c0b989 100644 --- a/ui/src/components/TailscaleSshMachine.tsx +++ b/ui/src/components/TailscaleSshMachine.tsx @@ -6,6 +6,8 @@ import { useTailscaleConnections } from "@/hooks/useTailscaleConnections"; import { Link } from "@/lib/router"; import { Button } from "./ui/button"; import { Field } from "./agent-config-primitives"; +import { cn } from "@/lib/utils"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; export function TailscaleSshMachine(props: { companyId: string; connectionId: string; deviceId: string; @@ -32,7 +34,7 @@ export function TailscaleSshMachine(props: { <p className="text-sm text-muted-foreground"><Link className="underline" to="/apps/tailscale">Manage Tailscale connector</Link></p> {showConnectionSelector ? <div className="flex items-center gap-3"> <Field label="Tailnet connection"> - <select className="w-full rounded-md border border-border bg-transparent px-2.5 py-1.5 text-sm" value={props.connectionId} + <select className={cn("w-full rounded-md border border-border bg-transparent px-2.5 py-1.5 text-sm", ANALYTICS_MASK_CLASS)} value={props.connectionId} onChange={event => props.onChange({ connectionId: event.target.value, deviceId: "", host: "" })}> <option value="">Choose a connection</option> {props.connectionId && !connected.some(connection => connection.id === props.connectionId) ? <option value={props.connectionId} disabled>Unavailable connection</option> : null} diff --git a/ui/src/components/TaskDecisionRecord.test.tsx b/ui/src/components/TaskDecisionRecord.test.tsx index 7c52ad12309..fb63c8fd05e 100644 --- a/ui/src/components/TaskDecisionRecord.test.tsx +++ b/ui/src/components/TaskDecisionRecord.test.tsx @@ -8,6 +8,7 @@ import type { DecisionOutcome } from "@/api/decisions"; import type { DecisionHistoryItem } from "@paperclipai/shared"; import { CoordinatorDecisionReceipt } from "./coordinator/CoordinatorDecisionReceipt"; import { TaskDecisionRecord } from "./TaskDecisionRecord"; +import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils"; const mocks = vi.hoisted(() => ({ get: vi.fn(), resolver: vi.fn() })); vi.mock("@/api/decisions", () => ({ decisionsApi: { get: mocks.get } })); @@ -76,3 +77,13 @@ it("refreshes the mounted record after company decision events invalidate its re expect(mocks.get).toHaveBeenCalledTimes(2); expect(mocks.resolver).toHaveBeenLastCalledWith(expect.objectContaining({ recordedDecision: decision })); }); +it("keeps the recorded choice, inputs and receipt label out of session replay", async () => { + await act(async () => root.render(<QueryClientProvider client={client}><MemoryRouter initialEntries={["/ORG/issues/ORG-1#decision-decision-1"]}> + <CoordinatorDecisionReceipt item={{ href: "/ORG/issues/ORG-1#decision-decision-1", label: "Own blog first" } as DecisionHistoryItem} onOpen={() => {}} /> + <TaskDecisionRecord companyId="company" issueId="task-1" viewerId="person" /> + </MemoryRouter></QueryClientProvider>)); + await vi.waitFor(() => expect(host.textContent).toContain("The draft is ready")); + expect(replayLeaks("Own blog first", host)).toEqual({ rendered: true, recorded: false }); + expect(replayLeaks("The draft is ready", host)).toEqual({ rendered: true, recorded: false }); + expect(replayLeaks("Decision record", host)).toEqual({ rendered: true, recorded: true }); +}); diff --git a/ui/src/components/TaskDecisionRecord.tsx b/ui/src/components/TaskDecisionRecord.tsx index e63b8826fbd..4edf9d4c880 100644 --- a/ui/src/components/TaskDecisionRecord.tsx +++ b/ui/src/components/TaskDecisionRecord.tsx @@ -7,6 +7,8 @@ import { queryKeys } from "@/lib/queryKeys"; import { taskChatHashAnchor } from "./task-chat/scroll-navigation"; import { DecisionResolver } from "./DecisionResolver"; import { Button } from "./ui/button"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; /** A selected Decisions-v1 record belongs to its task, not a second history tab. */ export function TaskDecisionRecord({ companyId, issueId, viewerId, agentMap }: { @@ -28,7 +30,7 @@ export function TaskDecisionRecord({ companyId, issueId, viewerId, agentMap }: { {["loading", "reconnecting"].includes(recordView.kind) ? <p role="status" className="text-sm text-muted-foreground">Loading decision…</p> : (recordView.kind === "error") ? ( <div role="alert" className="text-sm"><p>Could not load this decision.</p><Button size="sm" variant="ghost" onClick={() => void record.refetch()}>Retry</Button></div> ) : !matchesTask ? <p role="alert" className="text-sm text-muted-foreground">This decision is not available in this task.</p> : <> - {decision.status !== "open" ? <dl className="space-y-2 text-sm"> + {decision.status !== "open" ? <dl className={cn("space-y-2 text-sm", ANALYTICS_MASK_CLASS)}> <div><dt className="text-muted-foreground">Recorded choice</dt><dd>{choice?.label ?? (decision.chosenOptionId === "dismissed" ? "Dismissed" : decision.status)}</dd></div> {(decision.inputs ?? []).filter((input) => decision.inputValues?.[input.id] !== undefined).map((input) => <div key={input.id}> <dt className="text-muted-foreground">{input.label}</dt><dd className="whitespace-pre-wrap">{decision.inputValues![input.id]}</dd> diff --git a/ui/src/components/ToastViewport.test.tsx b/ui/src/components/ToastViewport.test.tsx index cdf0babd014..ba63c222db1 100644 --- a/ui/src/components/ToastViewport.test.tsx +++ b/ui/src/components/ToastViewport.test.tsx @@ -4,6 +4,7 @@ import { createRoot } from "react-dom/client"; import { describe, expect, it, vi } from "vitest"; import { ToastProvider, useToastActions, type ToastInput } from "../context/ToastContext"; import { ToastViewport } from "./ToastViewport"; +import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils"; vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); vi.stubGlobal("requestAnimationFrame", (callback: () => void) => setTimeout(callback, 0)); @@ -25,3 +26,14 @@ describe("notification avatars", () => { } finally { act(() => root.unmount()); } }); }); +describe("toast session replay", () => { + it("masks both the title and the body", () => { + const container = document.createElement("div"); + const root = createRoot(container); + try { + act(() => root.render(<ToastProvider><Notify toast={{ title: "Default set to ops@globex.com", body: "Globex workspace connected" }} /></ToastProvider>)); + expect(replayLeaks("ops@globex.com", container)).toEqual({ rendered: true, recorded: false }); + expect(replayLeaks("Globex workspace connected", container)).toEqual({ rendered: true, recorded: false }); + } finally { act(() => root.unmount()); } + }); +}); diff --git a/ui/src/components/ToastViewport.tsx b/ui/src/components/ToastViewport.tsx index 9205814af00..4b168064478 100644 --- a/ui/src/components/ToastViewport.tsx +++ b/ui/src/components/ToastViewport.tsx @@ -11,6 +11,7 @@ import { type ToastTone, } from "../context/ToastContext"; import { cn } from "../lib/utils"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; const toneClasses: Record<ToastTone, string> = { info: "border-sky-300 bg-sky-50 text-sky-900 dark:border-sky-500/25 dark:bg-sky-950/60 dark:text-sky-100", @@ -61,7 +62,7 @@ function AnimatedToast({ ) : ( <span className={cn("mt-1 h-2 w-2 shrink-0 rounded-full", toneDotClasses[toast.tone])} /> )} - <div className="min-w-0 flex-1"> + <div className={cn("min-w-0 flex-1", ANALYTICS_MASK_CLASS)}> <p className="text-sm font-semibold leading-5">{toast.title}</p> {toast.body && ( <p className="mt-1 text-xs leading-4 opacity-70"> diff --git a/ui/src/components/actions/ActionCard.tsx b/ui/src/components/actions/ActionCard.tsx index 2c9ad9d438f..60585b01f58 100644 --- a/ui/src/components/actions/ActionCard.tsx +++ b/ui/src/components/actions/ActionCard.tsx @@ -7,6 +7,7 @@ import { Button } from "@/components/ui/button"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { EnforcementBanner } from "@/components/EnforcementBanner"; import { CapabilityBadges, DecisionBadge, RiskBadge } from "@/pages/tools/shared"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; /** * Action approval card (PAP-10787 / PAP-10778, surfaces 11/12/99). @@ -267,7 +268,7 @@ export function ActionCard({ {/* JSON input */} <div className="space-y-1"> <p className="text-xs font-medium uppercase tracking-normal text-muted-foreground">Input</p> - <pre className="overflow-x-auto rounded-md border border-border bg-muted/40 p-3 font-mono text-xs leading-relaxed text-foreground"> + <pre className={cn("overflow-x-auto rounded-md border border-border bg-muted/40 p-3 font-mono text-xs leading-relaxed text-foreground", ANALYTICS_MASK_CLASS)}> {json} </pre> </div> @@ -275,7 +276,7 @@ export function ActionCard({ {/* Why I'm asking */} <div className="space-y-1"> <p className="text-xs font-medium uppercase tracking-normal text-muted-foreground">Why I'm asking</p> - <p className="text-sm text-muted-foreground"> + <p className={cn("text-sm text-muted-foreground", ANALYTICS_MASK_CLASS)}> {reason} {policyNumber != null ? ( <> diff --git a/ui/src/components/ai-connections/AiConnectionAccountControls.test.tsx b/ui/src/components/ai-connections/AiConnectionAccountControls.test.tsx new file mode 100644 index 00000000000..762d3ca2bbd --- /dev/null +++ b/ui/src/components/ai-connections/AiConnectionAccountControls.test.tsx @@ -0,0 +1,18 @@ +// @vitest-environment jsdom +import { renderToStaticMarkup } from "react-dom/server"; +import { afterEach, expect, it, vi } from "vitest"; +import type { ConnectionGrant } from "@paperclipai/shared"; +import { AiConnectionAccountControls } from "./AiConnectionAccountControls"; +import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils"; + +afterEach(() => { document.body.innerHTML = ""; }); + +it("masks the account label line in session replay", () => { + document.body.innerHTML = renderToStaticMarkup(<AiConnectionAccountControls + account={{ id: "connection", grantId: "grant", companyId: "company", provider: "openai", method: "subscription", + name: "Team ChatGPT", accountLabel: "tamsin.vale@example.test", ownership: "shared", status: "connected" }} + grant={{ id: "grant", capabilities: { canRevoke: true, canEditAudience: false } } as ConnectionGrant} + currentUserId="user" onMakeDefault={vi.fn()} onReconnect={vi.fn()} onRevoke={vi.fn()} />); + expect(replayLeaks("tamsin.vale@example.test")).toEqual({ rendered: true, recorded: false }); + expect(replayLeaks("Reconnect")).toEqual({ rendered: true, recorded: true }); +}); diff --git a/ui/src/components/ai-connections/AiConnectionAccountControls.tsx b/ui/src/components/ai-connections/AiConnectionAccountControls.tsx index 27e4c17a594..4453ecb3087 100644 --- a/ui/src/components/ai-connections/AiConnectionAccountControls.tsx +++ b/ui/src/components/ai-connections/AiConnectionAccountControls.tsx @@ -8,6 +8,7 @@ import { AI_PROVIDERS, type AiConnectionSummary } from "./model"; import { describeError } from "@/api/errors"; import { AiDefaultCrown } from "./AiConnectionDefault"; import { isOwnAiAccount } from "./useAiConnectionDefaults"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; /** AI-only account controls; identity, access and navigation belong to AppDetail. */ export function AiConnectionAccountControls({ @@ -48,7 +49,7 @@ export function AiConnectionAccountControls({ )} <div className="flex flex-wrap items-center justify-between gap-3"> <div className="min-w-0 text-sm"> - <p className="break-words text-xs text-muted-foreground">{account.method === "subscription" ? "Subscription" : "API key"}{account.accountLabel ? ` · ${account.accountLabel}` : ""}</p> + <p className={cn("break-words text-xs text-muted-foreground", ANALYTICS_MASK_CLASS)}>{account.method === "subscription" ? "Subscription" : "API key"}{account.accountLabel ? ` · ${account.accountLabel}` : ""}</p> </div> {!readOnly && grant.capabilities?.canRevoke && ( <div className="flex flex-wrap items-center gap-2"> diff --git a/ui/src/components/ai-connections/AiConnectionAccountDetails.test.tsx b/ui/src/components/ai-connections/AiConnectionAccountDetails.test.tsx index b69086cea3d..c6178f4a05f 100644 --- a/ui/src/components/ai-connections/AiConnectionAccountDetails.test.tsx +++ b/ui/src/components/ai-connections/AiConnectionAccountDetails.test.tsx @@ -7,6 +7,7 @@ import type { AiConnectionAccountIdentity, AiManagedConnectionSummary, Connectio import { AiConnectionAccountDetails } from "./AiConnectionAccountDetails"; import { ManagedAiConnectionDetails } from "./ManagedAiConnectionDetails"; import { TooltipProvider } from "@/components/ui/tooltip"; +import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils"; vi.mock("@/lib/router", () => ({ useNavigate: () => vi.fn() })); vi.mock("@/api/auth", () => ({ authApi: { getSession: vi.fn(async () => ({ user: { id: "user" } })) } })); @@ -156,3 +157,10 @@ it("reuses recent identity observations and invalidates them after reconnect", a expect(host.textContent).toContain("new-account@example.test"); expect(host.textContent).not.toContain("avery@example.test"); }); + +it("masks the provider account and organization labels in session replay", async () => { + observation = { ...known, accountLabel: "perrin.ashdown@example.test", organizationLabel: "Brackenridge Analytics" }; + await render(); + expect(replayLeaks("perrin.ashdown@example.test", document.body)).toEqual({ rendered: true, recorded: false }); + expect(replayLeaks("Brackenridge Analytics", document.body)).toEqual({ rendered: true, recorded: false }); +}); diff --git a/ui/src/components/ai-connections/AiConnectionAccountDetails.tsx b/ui/src/components/ai-connections/AiConnectionAccountDetails.tsx index 75bf0c94a81..c39b44d81e4 100644 --- a/ui/src/components/ai-connections/AiConnectionAccountDetails.tsx +++ b/ui/src/components/ai-connections/AiConnectionAccountDetails.tsx @@ -5,6 +5,8 @@ import { describeError } from "@/api/errors"; import { retryTransientOnly } from "@/lib/query-client"; import { Button } from "@/components/ui/button"; import { AI_PROVIDERS, aiMethodLabel } from "./model"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; /** Provider profile loading is independent of account access and maintenance controls. */ export function AiConnectionAccountDetails({ account, grant }: { @@ -28,10 +30,10 @@ export function AiConnectionAccountDetails({ account, grant }: { <h3 className="text-sm font-semibold">Connected account</h3> <dl className="grid grid-cols-2 gap-3 text-sm"> <dt className="text-muted-foreground">{AI_PROVIDERS[account.provider].name} account</dt> - <dd className="break-words">{accountLabel ?? "Not available"}</dd> + <dd className={cn("break-words", ANALYTICS_MASK_CLASS)}>{accountLabel ?? "Not available"}</dd> {(isChatGpt || identity.data?.organizationLabel) && <> <dt className="text-muted-foreground">{isChatGpt ? "ChatGPT workspace" : "Organization"}</dt> - <dd className="break-words">{identity.data?.organizationLabel ?? (identity.isPending && canLookUp ? "Checking…" : "Not available")}</dd> + <dd className={cn("break-words", ANALYTICS_MASK_CLASS)}>{identity.data?.organizationLabel ?? (identity.isPending && canLookUp ? "Checking…" : "Not available")}</dd> </>} <dt className="text-muted-foreground">Sign-in method</dt> <dd>{aiMethodLabel(account.provider, account.method)}</dd> diff --git a/ui/src/components/ai-connections/AiConnectionCredentialStep.tsx b/ui/src/components/ai-connections/AiConnectionCredentialStep.tsx index 83a7af6a4d0..98612f09eec 100644 --- a/ui/src/components/ai-connections/AiConnectionCredentialStep.tsx +++ b/ui/src/components/ai-connections/AiConnectionCredentialStep.tsx @@ -15,6 +15,7 @@ import { instanceSettingsApi } from "@/api/instanceSettings"; import { queryKeys } from "@/lib/queryKeys"; import { resolveAdapterTestEnvironmentId, resolveLocalDefaultEnvironmentId, resolveManagedSandboxEnvironmentId } from "@/lib/adapter-test-environment"; import { resolveForcedKubernetesEnvironment } from "@/lib/forced-kubernetes-environment"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; type Props = { companyId: string; @@ -87,8 +88,8 @@ function SubscriptionConnectionStep({ companyId, provider, initialMethod, fixedM return <div className="mx-auto w-full min-w-0 max-w-xl space-y-6"> {!hideName && <label className="block space-y-2 text-sm">Connection name<Input value={name} onChange={(event) => setName(event.target.value)} disabled={Boolean(connectionId)} /></label>} {!suppliedEnvironmentId && !forced.forced && loginEnvironments.length > 1 && <Select value={environmentId ?? ""} onValueChange={setChosenEnvironment}> - <SelectTrigger aria-label="Sign-in environment"><SelectValue placeholder="Sign-in environment" /></SelectTrigger> - <SelectContent>{loginEnvironments.map((env) => <SelectItem key={env.id} value={env.id}>{env.name}</SelectItem>)}</SelectContent> + <SelectTrigger className={ANALYTICS_MASK_CLASS} aria-label="Sign-in environment"><SelectValue placeholder="Sign-in environment" /></SelectTrigger> + <SelectContent className={ANALYTICS_MASK_CLASS}>{loginEnvironments.map((env) => <SelectItem key={env.id} value={env.id}>{env.name}</SelectItem>)}</SelectContent> </Select>} {loadError ? <QueryErrorState size="inline" error={loadError.error} action="prepare sign-in" onRetry={loadError.retry} retrying={loadError.isFetching} /> : environmentError ? <p role="alert" className="text-sm text-destructive">{environmentError}</p> : null} @@ -131,8 +132,8 @@ function ApiKeyConnectionStep({ companyId, provider, connectionId, name: initial {save.error && <p role="alert" className="text-sm text-destructive">{describeError(save.error).body}</p>} {copilot && <p className="text-sm text-muted-foreground">Use a personal fine-grained token with Copilot Requests permission. <a className="underline" href="https://docs.github.com/en/copilot/how-tos/copilot-cli/set-up-copilot-cli/authenticate-copilot-cli" target="_blank" rel="noreferrer">GitHub token instructions</a>. Verification discovers models in the selected environment and sends no model prompt. Repository access uses a separate connection.</p>} {copilot && !suppliedEnvironmentId && <Select value={environmentId ?? ""} onValueChange={setChosenEnvironment} disabled={preparing || save.isPending}> - <SelectTrigger aria-label="Copilot execution environment"><SelectValue placeholder="Execution environment" /></SelectTrigger> - <SelectContent>{(envs.data ?? []).filter(env => env.status === "active").map(env => <SelectItem key={env.id} value={env.id}>{env.name}</SelectItem>)}</SelectContent> + <SelectTrigger className={ANALYTICS_MASK_CLASS} aria-label="Copilot execution environment"><SelectValue placeholder="Execution environment" /></SelectTrigger> + <SelectContent className={ANALYTICS_MASK_CLASS}>{(envs.data ?? []).filter(env => env.status === "active").map(env => <SelectItem key={env.id} value={env.id}>{env.name}</SelectItem>)}</SelectContent> </Select>} {environmentError && <p role="alert" className="text-sm text-destructive">{environmentError}</p>} {defaults} diff --git a/ui/src/components/ai-connections/AiConnectionDefault.tsx b/ui/src/components/ai-connections/AiConnectionDefault.tsx index b5ee6fe8d93..90fa8ad5b01 100644 --- a/ui/src/components/ai-connections/AiConnectionDefault.tsx +++ b/ui/src/components/ai-connections/AiConnectionDefault.tsx @@ -5,6 +5,7 @@ import { Button } from "@/components/ui/button"; import { DropdownMenuItem } from "@/components/ui/dropdown-menu"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; import { AI_PROVIDERS } from "./model"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; export function AiDefaultCrown({ account }: { account: Pick<AiManagedConnectionSummary, "provider"> }) { const [open, setOpen] = useState(false); @@ -16,7 +17,7 @@ export function AiDefaultCrown({ account }: { account: Pick<AiManagedConnectionS <Crown className="size-4" aria-hidden="true" /> </button> </TooltipTrigger> - <TooltipContent>{label}</TooltipContent> + <TooltipContent className={ANALYTICS_MASK_CLASS}>{label}</TooltipContent> </Tooltip>; } diff --git a/ui/src/components/ai-connections/AiConnectionField.test.tsx b/ui/src/components/ai-connections/AiConnectionField.test.tsx index 6525ae11bf3..55712ab15fc 100644 --- a/ui/src/components/ai-connections/AiConnectionField.test.tsx +++ b/ui/src/components/ai-connections/AiConnectionField.test.tsx @@ -8,6 +8,7 @@ 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; @@ -235,3 +236,21 @@ it("shows readable copy with a retry when connections cannot be loaded", async ( 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 }); +}); diff --git a/ui/src/components/ai-connections/AiConnectionField.tsx b/ui/src/components/ai-connections/AiConnectionField.tsx index eb0bbfbb7b7..fbf560a48ab 100644 --- a/ui/src/components/ai-connections/AiConnectionField.tsx +++ b/ui/src/components/ai-connections/AiConnectionField.tsx @@ -27,6 +27,8 @@ import { DialogDescription, DialogFooter, } from "@/components/ui/dialog"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; export function aiProviderForAdapter( adapterType: string, @@ -143,7 +145,7 @@ export function AiConnectionField({ )} {(compatiblePools.length > 0 || value?.mode === "router") && <label className="block space-y-1 text-sm"> AI connection - <select className="block w-full rounded-md border bg-background px-3 py-2" disabled={readOnly} value={value?.mode === "router" ? value.connectionId : ""} onChange={event => { + <select className={cn("block w-full rounded-md border bg-background px-3 py-2", ANALYTICS_MASK_CLASS)} disabled={readOnly} value={value?.mode === "router" ? value.connectionId : ""} onChange={event => { if (event.target.value) changeBinding({ mode: "router", connectionId: event.target.value }); else changeBinding({ mode: "responsible_user", provider, method }); }}> @@ -178,14 +180,14 @@ export function AiConnectionField({ if (!open) setPendingAdoption(undefined); }} > - <DialogContent className="max-h-(--sz-85vh) overflow-y-auto sm:max-w-2xl" onCloseAutoFocus={restoreFocus}> + <DialogContent className={cn("max-h-(--sz-85vh) overflow-y-auto sm:max-w-2xl", ANALYTICS_MASK_CLASS)} onCloseAutoFocus={restoreFocus}> <DialogHeader> - <DialogTitle>{pendingAdoption?.mode === "router" ? `Use ${accounts.data?.pools?.find(pool => pool.id === pendingAdoption.connectionId)?.name ?? "this pool"}?` : `Adopt Connections for ${agentName}`}</DialogTitle> + <DialogTitle className={ANALYTICS_MASK_CLASS}>{pendingAdoption?.mode === "router" ? `Use ${accounts.data?.pools?.find(pool => pool.id === pendingAdoption.connectionId)?.name ?? "this pool"}?` : `Adopt Connections for ${agentName}`}</DialogTitle> <DialogDescription> {pendingAdoption?.mode === "router" ? "Reset existing sessions that use an account outside this pool." : "Saving validates access to the selected connection. Existing sessions keep their account or require an explicit reset before adoption."} </DialogDescription> </DialogHeader> - {pendingAdoption?.mode !== "router" && <p className="text-sm"> + {pendingAdoption?.mode !== "router" && <p className={cn("text-sm", ANALYTICS_MASK_CLASS)}> {pendingAdoption?.mode === "responsible_user" ? `Responsible user’s default. For you: ${pendingAccount ? aiConnectionDisplayLabel(pendingAccount) : "Not connected"}. Other users use their own default.` : pendingAccount && aiConnectionDisplayLabel(pendingAccount)} @@ -213,7 +215,7 @@ export function AiConnectionField({ </DialogContent> </Dialog> <Dialog open={connecting} onOpenChange={(open) => { if (!selectDefault.isPending) setConnecting(open); }}> - <DialogContent className="max-h-(--sz-85vh) overflow-y-auto sm:max-w-2xl" onCloseAutoFocus={restoreFocus}> + <DialogContent className={cn("max-h-(--sz-85vh) overflow-y-auto sm:max-w-2xl", ANALYTICS_MASK_CLASS)} onCloseAutoFocus={restoreFocus}> <DialogHeader> <DialogTitle>{reconnecting ? "Reconnect account" : "Connect account"}</DialogTitle> <DialogDescription> diff --git a/ui/src/components/ai-connections/AiConnectionIdentity.test.tsx b/ui/src/components/ai-connections/AiConnectionIdentity.test.tsx new file mode 100644 index 00000000000..995b589ec25 --- /dev/null +++ b/ui/src/components/ai-connections/AiConnectionIdentity.test.tsx @@ -0,0 +1,17 @@ +// @vitest-environment jsdom +import { renderToStaticMarkup } from "react-dom/server"; +import { afterEach, expect, it } from "vitest"; +import { AiConnectionIdentity } from "./AiConnectionIdentity"; +import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils"; + +afterEach(() => { document.body.innerHTML = ""; }); + +it("masks the connection name and account label in session replay", () => { + document.body.innerHTML = renderToStaticMarkup(<AiConnectionIdentity connection={{ + id: "connection", grantId: "grant", companyId: "company", provider: "anthropic", method: "subscription", + name: "Zephyr Labs Claude", accountLabel: "quill.marten@example.test", ownership: "shared", status: "connected", + }} />); + expect(replayLeaks("Zephyr Labs Claude")).toEqual({ rendered: true, recorded: false }); + expect(replayLeaks("quill.marten@example.test")).toEqual({ rendered: true, recorded: false }); + expect(replayLeaks("Company shared")).toEqual({ rendered: true, recorded: true }); +}); diff --git a/ui/src/components/ai-connections/AiConnectionIdentity.tsx b/ui/src/components/ai-connections/AiConnectionIdentity.tsx index b35aebbbfd4..23d71aead47 100644 --- a/ui/src/components/ai-connections/AiConnectionIdentity.tsx +++ b/ui/src/components/ai-connections/AiConnectionIdentity.tsx @@ -5,6 +5,8 @@ import { aiMethodLabel, type AiConnectionSummary, } from "./model"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; export function AiConnectionIdentity({ connection, @@ -17,10 +19,10 @@ export function AiConnectionIdentity({ <div className="flex min-w-0 items-start gap-3"> <AppLogo name={provider.name} brandKey={connection.provider} logoUrl={provider.logo} size={24} /> <div className="flex min-w-0 flex-col gap-1"> - <span className="break-words text-sm font-medium"> + <span className={cn("break-words text-sm font-medium", ANALYTICS_MASK_CLASS)}> {connection.name} </span> - <span className="text-xs text-muted-foreground"> + <span className={cn("text-xs text-muted-foreground", ANALYTICS_MASK_CLASS)}> {provider.name} ·{" "} {aiMethodLabel(connection.provider, connection.method)} {connection.accountLabel ? ` · ${connection.accountLabel}` : ""} diff --git a/ui/src/components/ai-connections/AiConnectionPicker.test.tsx b/ui/src/components/ai-connections/AiConnectionPicker.test.tsx new file mode 100644 index 00000000000..f1fcbe53184 --- /dev/null +++ b/ui/src/components/ai-connections/AiConnectionPicker.test.tsx @@ -0,0 +1,25 @@ +// @vitest-environment jsdom +import { renderToStaticMarkup } from "react-dom/server"; +import { afterEach, expect, it, vi } from "vitest"; +import { AiConnectionPicker } from "./AiConnectionPicker"; +import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils"; + +afterEach(() => { document.body.innerHTML = ""; }); + +it("masks a shared connection's account label in session replay", () => { + document.body.innerHTML = renderToStaticMarkup(<AiConnectionPicker + requirement={{ companyId: "company", provider: "anthropic" }} + connections={[{ id: "connection", grantId: "grant", companyId: "company", provider: "anthropic", method: "api_key", + name: "Shared Claude key", accountLabel: "orla.brisk@example.test", ownership: "shared", status: "connected" }]} + currentUserId="user" agentId="agent" agentName="Nova" onChange={vi.fn()} onConnect={vi.fn()} />); + expect(replayLeaks("orla.brisk@example.test")).toEqual({ rendered: true, recorded: false }); +}); + +it("masks the responsible user's default connection name in session replay", () => { + document.body.innerHTML = renderToStaticMarkup(<AiConnectionPicker + requirement={{ companyId: "company", provider: "anthropic" }} + connections={[{ id: "mine", grantId: "grant", companyId: "company", provider: "anthropic", method: "subscription", + name: "Orla's Claude Max", ownership: "personal", ownerUserId: "user", isDefault: true, status: "connected" }]} + currentUserId="user" agentId="agent" agentName="Nova" onChange={vi.fn()} onConnect={vi.fn()} />); + expect(replayLeaks("Orla's Claude Max")).toEqual({ rendered: true, recorded: false }); +}); diff --git a/ui/src/components/ai-connections/AiConnectionPicker.tsx b/ui/src/components/ai-connections/AiConnectionPicker.tsx index a781deb7e83..b3738bab67d 100644 --- a/ui/src/components/ai-connections/AiConnectionPicker.tsx +++ b/ui/src/components/ai-connections/AiConnectionPicker.tsx @@ -13,6 +13,7 @@ import { type AiConnectionRequirement, type AiConnectionSummary, } from "./model"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; export interface AiConnectionPickerProps { requirement: AiConnectionRequirement; @@ -110,13 +111,13 @@ export function AiConnectionPicker({ selectedId={value?.mode === "responsible_user" ? "responsible_user" : value?.connectionId} choices={[ { id: "responsible_user", name: "Responsible user’s connection", description: <> - <span className="block">For you: {personalDefault?.name ?? "Not connected"}</span> + <span className="block">For you: <span className={ANALYTICS_MASK_CLASS}>{personalDefault?.name ?? "Not connected"}</span></span> <span className="block">Other users’ tasks use their own {AI_PROVIDERS[requirement.provider].name} connection.</span> </> }, ...compatible.filter((connection) => connection.ownership === "shared").map((connection) => ({ id: connection.id, name: connection.name, disabled: Boolean(aiConnectionProblem(connection)), - description: <>Company shared · {aiMethodLabel(connection.provider, connection.method)}{connection.accountLabel ? ` · ${connection.accountLabel}` : ""}{aiConnectionProblem(connection) ? ` · ${aiConnectionProblem(connection)}` : ""}</>, + description: <>Company shared · {aiMethodLabel(connection.provider, connection.method)}{connection.accountLabel ? <span className={ANALYTICS_MASK_CLASS}>{` · ${connection.accountLabel}`}</span> : ""}{aiConnectionProblem(connection) ? ` · ${aiConnectionProblem(connection)}` : ""}</>, })), ]} onSelect={(id) => { diff --git a/ui/src/components/ai-connections/AiConnectionPoolConnector.tsx b/ui/src/components/ai-connections/AiConnectionPoolConnector.tsx index 624c2c636d4..e8522e9b601 100644 --- a/ui/src/components/ai-connections/AiConnectionPoolConnector.tsx +++ b/ui/src/components/ai-connections/AiConnectionPoolConnector.tsx @@ -26,6 +26,8 @@ import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; import { AiConnectionUsagePanel } from "./AiConnectionUsagePanel"; import { AI_PROVIDERS, aiMethodLabel } from "./model"; +import { cn } from "@/lib/utils"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; const configOf = ({ name, enabled, members, mode, thresholdPercent }: AiConnectionPoolConfig): AiConnectionPoolConfig => ({ name, enabled, members, mode, thresholdPercent }); const emptyConfig = (): AiConnectionPoolConfig => ({ name: "AI connection pool", enabled: false, members: [], mode: "round_robin", thresholdPercent: 90 }); @@ -134,7 +136,7 @@ function PoolConnector({ companyId, pluginKey, connection }: { companyId: string return <li key={member.id} className="flex items-center gap-3 px-4 py-3"> <span className="w-4 text-center text-xs text-muted-foreground">{index + 1}</span> <AppLogo name={provider.name} logoUrl={provider.logo} size={32} /> - <div className="min-w-0 flex-1"><p className="truncate text-sm font-medium">{account?.name ?? "Connection unavailable"}</p><p className="text-xs text-muted-foreground">{account ? aiMethodLabel(account.provider, account.method) : "Restore access to this connection."}</p>{connection && draft.mode === "usage_aware" && account && <details className="mt-2 text-xs text-muted-foreground"><summary className="cursor-pointer">Usage</summary><div className="pt-3">{inspectionError ? <p role="status">{inspectionError}</p> : <AiConnectionUsagePanel account={account} cachedOnly observation={inspection[member.id]?.usage} />}</div></details>}</div> + <div className="min-w-0 flex-1"><p className={cn("truncate text-sm font-medium", ANALYTICS_MASK_CLASS)}>{account?.name ?? "Connection unavailable"}</p><p className="text-xs text-muted-foreground">{account ? aiMethodLabel(account.provider, account.method) : "Restore access to this connection."}</p>{connection && draft.mode === "usage_aware" && account && <details className="mt-2 text-xs text-muted-foreground"><summary className="cursor-pointer">Usage</summary><div className="pt-3">{inspectionError ? <p role="status">{inspectionError}</p> : <AiConnectionUsagePanel account={account} cachedOnly observation={inspection[member.id]?.usage} />}</div></details>}</div> <div className="flex shrink-0 items-center gap-1"> <Button type="button" variant="ghost" size="icon-sm" disabled={disabled || index === 0} aria-label={`Move ${account?.name ?? "connection"} up`} onClick={() => move(index, -1)}><ArrowUp className="size-4" /></Button> <Button type="button" variant="ghost" size="icon-sm" disabled={disabled || index === draft.members.length - 1} aria-label={`Move ${account?.name ?? "connection"} down`} onClick={() => move(index, 1)}><ArrowDown className="size-4" /></Button> @@ -147,12 +149,12 @@ function PoolConnector({ companyId, pluginKey, connection }: { companyId: string return <div className={connection ? "space-y-6" : "mx-auto max-w-2xl"}> {connection ? <div className="flex items-start justify-between gap-4"> <AppDetailHeader appName={draft.name} connection={connection} logoEntry={logoEntry} brandKey={logoEntry.slug} allowRemoteLogo canRename={!disabled} status={editing?.enabled ? { label: "Connected", tone: "connected" } : { label: "Paused", tone: "paused" }} actionCount={null} renaming={renaming} nameDraft={nameDraft} renamePending={disabled} onNameDraftChange={setNameDraft} onRenameStart={() => { if (!disabled) { setNameDraft(draft.name); setRenaming(true); } }} onRenameCancel={() => setRenaming(false)} onRenameSubmit={value => void save({ ...draft, name: value })} /> - <DropdownMenu><DropdownMenuTrigger asChild><Button variant="ghost" size="icon-sm" aria-label="Manage connection pool"><MoreHorizontal className="size-4" /></Button></DropdownMenuTrigger><DropdownMenuContent align="end"><DropdownMenuItem variant="destructive" disabled={busy || !canManage} onSelect={() => { setError(""); setRemoving(true); }}><Trash2 />Remove connection</DropdownMenuItem></DropdownMenuContent></DropdownMenu> + <DropdownMenu><DropdownMenuTrigger asChild><Button variant="ghost" size="icon-sm" aria-label="Manage connection pool"><MoreHorizontal className="size-4" /></Button></DropdownMenuTrigger><DropdownMenuContent className={ANALYTICS_MASK_CLASS} align="end"><DropdownMenuItem variant="destructive" disabled={busy || !canManage} onSelect={() => { setError(""); setRemoving(true); }}><Trash2 />Remove connection</DropdownMenuItem></DropdownMenuContent></DropdownMenu> </div> : <StepHeader title="Add a connection pool" subtitle={step === 0 ? "Choose connections you already use." : "New tasks rotate in this order."} step="connect" activeIndex={step} labels={["Connections", "Order"]} appIdentity={{ name, logoUrl: logoEntry.branding.logoUrl }} />} {unavailable && <p role="alert" className="text-sm text-destructive">{entry?.availability?.reason ?? "Enable the connection pool plugin in Plugins."}</p>} {!canManage && <p role="alert" className="text-sm text-muted-foreground">A connection manager can edit this pool.</p>} {error && !removing && <p role="alert" className="text-sm text-destructive">{error}</p>} - {!connection && step === 0 ? <ConnectionPicker accounts={accounts} selected={draft.members} disabled={disabled} onChange={members => setDraft({ ...draft, members })} onRefresh={() => void accountsQuery.refetch()} /> : <div className="space-y-4"> + {!connection && step === 0 ? <ConnectionPicker accounts={accounts} selected={draft.members} disabled={disabled} onChange={members => setDraft({ ...draft, members })} onRefresh={() => void accountsQuery.refetch()} /> : <div className={cn("space-y-4", ANALYTICS_MASK_CLASS)}> {connection && <div className="flex items-center justify-between gap-3"><h2 className="text-sm font-semibold">Connections</h2><Button variant="outline" size="sm" disabled={disabled} onClick={() => { setPickerMembers(draft.members); setPickerOpen(true); }}><Plus className="size-4" />Add connections</Button></div>} {orderedMembers} <p className="text-xs text-muted-foreground">{connection ? "Order changes apply to new tasks." : "Created paused. Enable it when you’re ready."}</p> @@ -161,7 +163,7 @@ function PoolConnector({ companyId, pluginKey, connection }: { companyId: string <details className="rounded-lg border border-border"><summary className="cursor-pointer px-4 py-3 text-sm font-medium">Advanced</summary><fieldset disabled={disabled} className="space-y-4 border-t border-border p-4"> <label className="flex items-center gap-2 text-sm"><Checkbox checked={draft.mode === "usage_aware"} onCheckedChange={checked => setDraft({ ...draft, mode: checked ? "usage_aware" : "round_robin" })} />Skip connections near their usage limit</label> {draft.mode === "usage_aware" && <label className="flex items-center gap-3 text-sm">Skip at<Input className="w-20" aria-label="Usage threshold" type="number" min={1} max={100} step={1} value={draft.thresholdPercent} onChange={event => setDraft({ ...draft, thresholdPercent: Number(event.target.value) })} />% usage</label>} - {draft.members.map((member, index) => <div key={member.id} className="space-y-2"><p className="text-sm font-medium">{accounts.find(account => account.id === member.binding.connectionId)?.name ?? "Connection unavailable"}</p><div className="grid gap-3 sm:grid-cols-2"><label className="space-y-1 text-xs text-muted-foreground">Model<Input aria-label={`Model for connection ${index + 1}`} value={member.profile.model} onChange={event => setDraft({ ...draft, members: draft.members.map(row => row.id === member.id ? { ...row, profile: { ...row.profile, model: event.target.value } } : row) })} /></label><label className="space-y-1 text-xs text-muted-foreground">Effort (optional)<Input aria-label={`Effort for connection ${index + 1}`} value={member.profile.effort ?? ""} onChange={event => { const { effort: _old, ...profile } = member.profile; setDraft({ ...draft, members: draft.members.map(row => row.id === member.id ? { ...row, profile: { ...profile, ...(event.target.value.trim() ? { effort: event.target.value.trim() } : {}) } } : row) }); }} /></label></div></div>)} + {draft.members.map((member, index) => <div key={member.id} className="space-y-2"><p className={cn("text-sm font-medium", ANALYTICS_MASK_CLASS)}>{accounts.find(account => account.id === member.binding.connectionId)?.name ?? "Connection unavailable"}</p><div className="grid gap-3 sm:grid-cols-2"><label className="space-y-1 text-xs text-muted-foreground">Model<Input aria-label={`Model for connection ${index + 1}`} value={member.profile.model} onChange={event => setDraft({ ...draft, members: draft.members.map(row => row.id === member.id ? { ...row, profile: { ...row.profile, model: event.target.value } } : row) })} /></label><label className="space-y-1 text-xs text-muted-foreground">Effort (optional)<Input aria-label={`Effort for connection ${index + 1}`} value={member.profile.effort ?? ""} onChange={event => { const { effort: _old, ...profile } = member.profile; setDraft({ ...draft, members: draft.members.map(row => row.id === member.id ? { ...row, profile: { ...profile, ...(event.target.value.trim() ? { effort: event.target.value.trim() } : {}) } } : row) }); }} /></label></div></div>)} </fieldset></details> <section aria-labelledby="pool-used-by" className="space-y-3"> <h2 id="pool-used-by" className="text-sm font-semibold">Used by</h2> @@ -176,17 +178,17 @@ function PoolConnector({ companyId, pluginKey, connection }: { companyId: string <Button variant="ghost" disabled={busy} onClick={() => connection ? navigate("/apps") : step ? setStep(0) : navigate("/apps")}>{!connection && step ? "Back" : "Cancel"}</Button> <Button disabled={disabled || draft.members.length === 0 || !Number.isInteger(draft.thresholdPercent) || draft.thresholdPercent < 1 || draft.thresholdPercent > 100} onClick={() => !connection && step === 0 ? setStep(1) : void save()}>{busy && <Loader2 className="size-4 animate-spin" />}{busy ? "Saving…" : connection ? "Save changes" : step ? "Create pool" : "Continue"}</Button> </div> - <Dialog open={pickerOpen} onOpenChange={setPickerOpen}><DialogContent className="sm:max-w-2xl"><DialogHeader><DialogTitle>Add connections</DialogTitle><DialogDescription>Choose connections you already use.</DialogDescription></DialogHeader><ConnectionPicker accounts={accounts} selected={pickerMembers} disabled={disabled} onChange={setPickerMembers} onRefresh={() => void accountsQuery.refetch()} /><div className="flex items-center justify-between gap-3"><Button variant="ghost" onClick={() => setPickerOpen(false)}>Cancel</Button><Button onClick={() => { setDraft({ ...draft, members: pickerMembers }); setPickerOpen(false); }}>Done</Button></div></DialogContent></Dialog> - <AlertDialog open={removing} onOpenChange={open => { if (!busy) setRemoving(open); }}><AlertDialogContent><AlertDialogHeader><AlertDialogTitle>Remove {draft.name}?</AlertDialogTitle><AlertDialogDescription>The connections in this pool are kept.</AlertDialogDescription></AlertDialogHeader>{error && <p role="alert" className="text-sm text-destructive">{error}</p>}<AlertDialogFooter className="sm:justify-between"><AlertDialogCancel disabled={busy}>Cancel</AlertDialogCancel><AlertDialogAction className="bg-destructive text-destructive-foreground hover:bg-destructive/90" disabled={busy} onClick={event => { event.preventDefault(); void remove(); }}>{busy ? "Removing…" : "Remove connection"}</AlertDialogAction></AlertDialogFooter></AlertDialogContent></AlertDialog> + <Dialog open={pickerOpen} onOpenChange={setPickerOpen}><DialogContent className={cn("sm:max-w-2xl", ANALYTICS_MASK_CLASS)}><DialogHeader><DialogTitle>Add connections</DialogTitle><DialogDescription>Choose connections you already use.</DialogDescription></DialogHeader><ConnectionPicker accounts={accounts} selected={pickerMembers} disabled={disabled} onChange={setPickerMembers} onRefresh={() => void accountsQuery.refetch()} /><div className="flex items-center justify-between gap-3"><Button variant="ghost" onClick={() => setPickerOpen(false)}>Cancel</Button><Button onClick={() => { setDraft({ ...draft, members: pickerMembers }); setPickerOpen(false); }}>Done</Button></div></DialogContent></Dialog> + <AlertDialog open={removing} onOpenChange={open => { if (!busy) setRemoving(open); }}><AlertDialogContent className={ANALYTICS_MASK_CLASS}><AlertDialogHeader><AlertDialogTitle className={ANALYTICS_MASK_CLASS}>Remove {draft.name}?</AlertDialogTitle><AlertDialogDescription>The connections in this pool are kept.</AlertDialogDescription></AlertDialogHeader>{error && <p role="alert" className="text-sm text-destructive">{error}</p>}<AlertDialogFooter className="sm:justify-between"><AlertDialogCancel disabled={busy}>Cancel</AlertDialogCancel><AlertDialogAction className="bg-destructive text-destructive-foreground hover:bg-destructive/90" disabled={busy} onClick={event => { event.preventDefault(); void remove(); }}>{busy ? "Removing…" : "Remove connection"}</AlertDialogAction></AlertDialogFooter></AlertDialogContent></AlertDialog> </div>; } function ConnectionPicker({ accounts, selected, disabled, onChange, onRefresh }: { accounts: AiManagedConnectionSummary[]; selected: AiConnectionPoolMember[]; disabled: boolean; onChange: (members: AiConnectionPoolMember[]) => void; onRefresh: () => void }) { const [search, setSearch] = useState(""); const filtered = accounts.filter(account => `${account.name} ${AI_PROVIDERS[account.provider].name}`.toLowerCase().includes(search.toLowerCase())); - return <div className="space-y-4"> + return <div className={cn("space-y-4", ANALYTICS_MASK_CLASS)}> <div className="relative"><Search className="pointer-events-none absolute left-3 top-3 size-4 text-muted-foreground" /><Input aria-label="Search connections" placeholder="Search connections…" value={search} onChange={event => setSearch(event.target.value)} className="pl-9" /></div> <div className="max-h-80 overflow-y-auto rounded-lg border border-border divide-y divide-border"> - {filtered.map(account => { const existing = selected.find(member => member.binding.connectionId === account.id); const checked = existing?.binding.grantId === account.grantId; return <label key={account.grantId} className="flex cursor-pointer items-center gap-3 px-4 py-3 hover:bg-accent/50"><Checkbox checked={checked} disabled={disabled || (!checked && (account.status !== "connected" || Boolean(existing)))} onCheckedChange={value => onChange(value ? [...selected, memberOf(account)] : selected.filter(member => member.binding.connectionId !== account.id))} aria-label={account.name} /><AppLogo name={AI_PROVIDERS[account.provider].name} logoUrl={AI_PROVIDERS[account.provider].logo} size={32} /><span className="min-w-0 flex-1"><span className="block truncate text-sm font-medium">{account.name}</span><span className="block text-xs text-muted-foreground">{aiMethodLabel(account.provider, account.method)} · {account.ownership === "shared" ? "Shared" : "Personal"}</span></span>{account.status !== "connected" && <span className="text-xs text-muted-foreground">Needs attention</span>}</label>; })} + {filtered.map(account => { const existing = selected.find(member => member.binding.connectionId === account.id); const checked = existing?.binding.grantId === account.grantId; return <label key={account.grantId} className="flex cursor-pointer items-center gap-3 px-4 py-3 hover:bg-accent/50"><Checkbox checked={checked} disabled={disabled || (!checked && (account.status !== "connected" || Boolean(existing)))} onCheckedChange={value => onChange(value ? [...selected, memberOf(account)] : selected.filter(member => member.binding.connectionId !== account.id))} aria-label={account.name} /><AppLogo name={AI_PROVIDERS[account.provider].name} logoUrl={AI_PROVIDERS[account.provider].logo} size={32} /><span className="min-w-0 flex-1"><span className={cn("block truncate text-sm font-medium", ANALYTICS_MASK_CLASS)}>{account.name}</span><span className="block text-xs text-muted-foreground">{aiMethodLabel(account.provider, account.method)} · {account.ownership === "shared" ? "Shared" : "Personal"}</span></span>{account.status !== "connected" && <span className="text-xs text-muted-foreground">Needs attention</span>}</label>; })} {filtered.length === 0 && <p className="px-4 py-6 text-sm text-muted-foreground">{accounts.length ? "No matching connections." : "No AI connections yet."}</p>} </div> <div className="flex items-center justify-between gap-3 text-sm"><Link to="/apps" target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1 text-muted-foreground hover:text-foreground">Connect a new account<ExternalLink className="size-3.5" /></Link><Button variant="ghost" size="sm" onClick={onRefresh}>Refresh</Button></div> diff --git a/ui/src/components/ai-connections/AiConnectionPoolRunDetails.test.tsx b/ui/src/components/ai-connections/AiConnectionPoolRunDetails.test.tsx new file mode 100644 index 00000000000..1994e2088a5 --- /dev/null +++ b/ui/src/components/ai-connections/AiConnectionPoolRunDetails.test.tsx @@ -0,0 +1,16 @@ +// @vitest-environment jsdom +import { renderToStaticMarkup } from "react-dom/server"; +import { afterEach, expect, it } from "vitest"; +import { AiConnectionPoolRunDetails } from "./AiConnectionPoolRunDetails"; +import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils"; + +afterEach(() => { document.body.innerHTML = ""; }); + +it("masks the pinned pool account name in session replay", () => { + document.body.innerHTML = renderToStaticMarkup(<AiConnectionPoolRunDetails context={{ + aiRouterSelection: { binding: { provider: "anthropic" }, runtimeConfig: { model: "claude-sonnet" }, notes: [] }, + aiConnection: { accountName: "Juniper Ops Pool Account", connectionId: "connection" }, + }} />); + expect(replayLeaks("Juniper Ops Pool Account")).toEqual({ rendered: true, recorded: false }); + expect(replayLeaks("claude-sonnet")).toEqual({ rendered: true, recorded: true }); +}); diff --git a/ui/src/components/ai-connections/AiConnectionPoolRunDetails.tsx b/ui/src/components/ai-connections/AiConnectionPoolRunDetails.tsx index 34e75fe2ae0..db07523c012 100644 --- a/ui/src/components/ai-connections/AiConnectionPoolRunDetails.tsx +++ b/ui/src/components/ai-connections/AiConnectionPoolRunDetails.tsx @@ -1,4 +1,6 @@ import type { AiConnectionRouterSelection } from "@paperclipai/shared"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; export function AiConnectionPoolRunDetails({ context }: { context: Record<string, unknown> | null }) { const selection = context?.aiRouterSelection as AiConnectionRouterSelection | undefined; @@ -7,7 +9,7 @@ export function AiConnectionPoolRunDetails({ context }: { context: Record<string const config = selection.runtimeConfig; const effort = config.modelReasoningEffort ?? config.reasoningEffort ?? config.effort ?? config.variant; return <div className="rounded-lg border p-4 text-sm space-y-1"> - <p className="font-medium">Task-pinned pool account · {account?.accountName ?? account?.connectionId ?? "Selected account"}</p> + <p className={cn("font-medium", ANALYTICS_MASK_CLASS)}>Task-pinned pool account · {account?.accountName ?? account?.connectionId ?? "Selected account"}</p> <p>{[selection.binding.provider, config.provider, config.acpxAgent, config.model, effort].filter(Boolean).map(String).join(" · ")}</p> {selection.notes.length > 0 && <p className="text-muted-foreground">{selection.notes.join(" ")}</p>} </div>; diff --git a/ui/src/components/ai-connections/AiConnectionSelect.test.tsx b/ui/src/components/ai-connections/AiConnectionSelect.test.tsx new file mode 100644 index 00000000000..411d87164af --- /dev/null +++ b/ui/src/components/ai-connections/AiConnectionSelect.test.tsx @@ -0,0 +1,39 @@ +// @vitest-environment jsdom +import { flushSync } from "react-dom"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { AiConnectionSelect } from "./AiConnectionSelect"; +import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils"; + +vi.mock("@/pages/apps/AppLogo", () => ({ AppLogo: () => null })); + +let root: Root; +let container: HTMLDivElement; +beforeEach(() => { + container = document.createElement("div"); + document.body.append(container); + root = createRoot(container); +}); +afterEach(() => { flushSync(() => root.unmount()); container.remove(); }); + +it("masks the selected connection in the trigger and the account labels in the open list", async () => { + const connections = [ + { id: "selected", grantId: "selected-grant", companyId: "company", provider: "anthropic" as const, method: "api_key" as const, + name: "Claude key", accountLabel: "wren.halloway@example.test", ownership: "shared" as const, status: "connected" as const }, + { id: "other", grantId: "other-grant", companyId: "company", provider: "anthropic" as const, method: "api_key" as const, + name: "Claude backup", accountLabel: "ivo.castellan@example.test", ownership: "shared" as const, status: "connected" as const }, + ]; + flushSync(() => root.render(<AiConnectionSelect requirement={{ companyId: "company", provider: "anthropic" }} + connections={connections} currentUserId="user" agentId="agent" agentName="Nova" adapterType="claude_local" + value={{ provider: "anthropic", method: "api_key", mode: "shared", connectionId: "selected", grantId: "selected-grant" }} + onChange={vi.fn()} onConnect={vi.fn()} />)); + const trigger = container.querySelector<HTMLElement>('[role="combobox"][aria-label="Connection"]')!; + expect(replayLeaks("wren.halloway@example.test", trigger)).toEqual({ rendered: true, recorded: false }); + flushSync(() => trigger.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true }))); + await new Promise(resolve => setTimeout(resolve, 0)); + flushSync(() => {}); + expect(document.querySelectorAll('[role="option"]').length).toBeGreaterThan(0); + expect(replayLeaks("ivo.castellan@example.test", document.body)).toEqual({ rendered: true, recorded: false }); + expect(replayLeaks("wren.halloway@example.test", document.body)).toEqual({ rendered: true, recorded: false }); + expect(replayLeaks("Connect an account", document.body)).toEqual({ rendered: true, recorded: false }); +}); diff --git a/ui/src/components/ai-connections/AiConnectionSelect.tsx b/ui/src/components/ai-connections/AiConnectionSelect.tsx index 1eb36785f1e..786bb4a6e91 100644 --- a/ui/src/components/ai-connections/AiConnectionSelect.tsx +++ b/ui/src/components/ai-connections/AiConnectionSelect.tsx @@ -17,12 +17,14 @@ import { Button } from "@/components/ui/button"; import { aiConnectionDisplayLabel, aiConnectionProblem, personalAiDefault } from "./model"; import type { AiConnectionPickerProps } from "./AiConnectionPicker"; import type { AiConnectionSummary } from "./model"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; function ConnectionLabel({ connection, label, wrap = false }: { connection: AiConnectionSummary; label?: string; wrap?: boolean }) { return ( <span className="flex min-w-0 items-center gap-2"> <AppLogo name={connection.name} brandKey={aiConnectionCatalogSlug(connection.provider, connection.routing)} size={20} compact /> - <span className={wrap ? "min-w-0 break-words whitespace-normal" : "truncate"}>{label ?? aiConnectionDisplayLabel(connection)}</span> + <span className={cn(wrap ? "min-w-0 break-words whitespace-normal" : "truncate", ANALYTICS_MASK_CLASS)}>{label ?? aiConnectionDisplayLabel(connection)}</span> </span> ); } @@ -119,7 +121,7 @@ export function AiConnectionSelect({ onValueChange={change} disabled={readOnly || loading || Boolean(error)} > - <SelectTrigger id={selectId} aria-label="Connection" title={selected ? aiConnectionDisplayLabel(selected) : undefined} className="w-full"> + <SelectTrigger id={selectId} aria-label="Connection" title={selected ? aiConnectionDisplayLabel(selected) : undefined} className={cn("w-full", ANALYTICS_MASK_CLASS)}> <SelectValue placeholder={ loading ? "Loading connections…" : "Choose a connection" @@ -132,7 +134,7 @@ export function AiConnectionSelect({ : value ? "Unavailable connection" : undefined} </SelectValue> </SelectTrigger> - <SelectContent> + <SelectContent className={ANALYTICS_MASK_CLASS}> {incompatible && selected && ( <SelectItem value={selected.id} disabled> <ConnectionLabel connection={selected} label={`${aiConnectionDisplayLabel(selected)} · Incompatible`} wrap /> diff --git a/ui/src/components/ai-connections/AiProviderSetup.tsx b/ui/src/components/ai-connections/AiProviderSetup.tsx index e80a0f8c94b..a2740eb6eec 100644 --- a/ui/src/components/ai-connections/AiProviderSetup.tsx +++ b/ui/src/components/ai-connections/AiProviderSetup.tsx @@ -26,6 +26,8 @@ import { SelectValue, } from "@/components/ui/select"; import { AiConnectionCredentialStep } from "./AiConnectionCredentialStep"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; const providers = [ { @@ -356,10 +358,10 @@ export function AiProviderSetup({ }} disabled={Boolean(reconnect) || Boolean(initialProtocol)} > - <SelectTrigger aria-label="API format" className="w-full"> + <SelectTrigger aria-label="API format" className={cn("w-full", ANALYTICS_MASK_CLASS)}> <SelectValue /> </SelectTrigger> - <SelectContent> + <SelectContent className={ANALYTICS_MASK_CLASS}> <SelectItem value="responses"> OpenAI Responses · Codex </SelectItem> @@ -393,10 +395,10 @@ export function AiProviderSetup({ onValueChange={(v) => setAuth(v as typeof auth)} disabled={Boolean(reconnect)} > - <SelectTrigger aria-label="Authentication" className="w-full"> + <SelectTrigger aria-label="Authentication" className={cn("w-full", ANALYTICS_MASK_CLASS)}> <SelectValue /> </SelectTrigger> - <SelectContent> + <SelectContent className={ANALYTICS_MASK_CLASS}> <SelectItem value="bearer"> {provider === "bedrock" ? "Bedrock API key" diff --git a/ui/src/components/artifacts/ArtifactCard.tsx b/ui/src/components/artifacts/ArtifactCard.tsx index db426c518f5..c383a1ab1fc 100644 --- a/ui/src/components/artifacts/ArtifactCard.tsx +++ b/ui/src/components/artifacts/ArtifactCard.tsx @@ -3,6 +3,7 @@ import { Download, ExternalLink, Paperclip, Play } from "lucide-react"; import type { CompanyArtifact } from "@/api/artifacts"; import { Link } from "@/lib/router"; import { cn, formatDate } from "@/lib/utils"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; interface ArtifactCardProps { artifact: CompanyArtifact; @@ -141,7 +142,7 @@ function TextPreview({ artifact }: { artifact: PreviewArtifact }) { return ( <PreviewFrame className="bg-card"> <div className="absolute inset-0 overflow-hidden p-3"> - <p className="max-h-full overflow-hidden whitespace-pre-wrap break-words text-base leading-6 text-muted-foreground/75"> + <p className={cn("max-h-full overflow-hidden whitespace-pre-wrap break-words text-base leading-6 text-muted-foreground/75", ANALYTICS_MASK_CLASS)}> {preview} </p> </div> diff --git a/ui/src/components/artifacts/RichArtifactCards.tsx b/ui/src/components/artifacts/RichArtifactCards.tsx index 04d36e0e0ff..65380ba9b42 100644 --- a/ui/src/components/artifacts/RichArtifactCards.tsx +++ b/ui/src/components/artifacts/RichArtifactCards.tsx @@ -31,6 +31,8 @@ import { DialogTitle, DialogTrigger, } from "@/components/ui/dialog"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; // Renderers contain UI labels only. All artifact-specific content is passed in. // Example values live exclusively in the individual stories' args. @@ -306,7 +308,7 @@ export function CommitCard(props: CommitCardProps) { function Markdown({ body, preview = false }: { body: string; preview?: boolean }) { return ( - <div className="flex flex-col gap-3 text-sm leading-relaxed"> + <div className={cn("flex flex-col gap-3 text-sm leading-relaxed", ANALYTICS_MASK_CLASS)}> <ReactMarkdown components={{ pre: ({ children }) => <pre className={preview @@ -386,9 +388,9 @@ export interface DocumentCardProps extends ArtifactIdentity { export function DocumentCard(props: DocumentCardProps) { const patch = props.patch ?? isPatchFile(props.filename); const content = (body: string, preview = false) => patch - ? <pre className={preview + ? <pre className={cn(ANALYTICS_MASK_CLASS, preview ? "paperclip-patch-preview m-0 min-w-0 overflow-hidden whitespace-pre font-mono text-xs leading-5" - : "m-0 min-w-0 whitespace-pre-wrap wrap-anywhere font-mono text-xs leading-5"}><code><PatchLines text={body} /></code></pre> + : "m-0 min-w-0 whitespace-pre-wrap wrap-anywhere font-mono text-xs leading-5", ANALYTICS_MASK_CLASS)}><code><PatchLines text={body} /></code></pre> : <Markdown body={body} preview={preview} />; return ( <Card> @@ -451,7 +453,7 @@ export interface DataCardProps extends ArtifactIdentity { function DataTable({ columns, rows }: Pick<DataCardProps, "columns" | "rows">) { return ( <div className="overflow-x-auto"> - <table className="w-full text-left text-xs"> + <table className={cn("w-full text-left text-xs", ANALYTICS_MASK_CLASS)}> <thead> <tr> {columns.map((column, i) => ( diff --git a/ui/src/components/chat/AgentChannelsPanel.tsx b/ui/src/components/chat/AgentChannelsPanel.tsx index fc4193f4937..cebc00b8398 100644 --- a/ui/src/components/chat/AgentChannelsPanel.tsx +++ b/ui/src/components/chat/AgentChannelsPanel.tsx @@ -6,6 +6,8 @@ import { Badge } from "@/components/ui/badge"; import { queryKeys } from "@/lib/queryKeys"; import { Link } from "@/lib/router"; import { useChatConnectorsEnabled, chatProviderVisible } from "@/hooks/useChatConnectorsEnabled"; +import { cn } from "@/lib/utils"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; const providerNames: Record<ChatProvider, string> = { speko: "Speko", @@ -74,7 +76,7 @@ export function AgentChannelsPanel({ <p className="text-sm font-semibold"> {providerNames[endpoint.provider]} </p> - <p className="truncate text-xs text-muted-foreground"> + <p className={cn("truncate text-xs text-muted-foreground", ANALYTICS_MASK_CLASS)}> {endpoint.botLabel ?? endpoint.providerAccountLabel ?? "Provider identity"} diff --git a/ui/src/components/chat/ExternallyConnectedTaskBanner.test.tsx b/ui/src/components/chat/ExternallyConnectedTaskBanner.test.tsx index e08a0b0aeee..d2001724f97 100644 --- a/ui/src/components/chat/ExternallyConnectedTaskBanner.test.tsx +++ b/ui/src/components/chat/ExternallyConnectedTaskBanner.test.tsx @@ -10,6 +10,7 @@ import { ExternallyConnectedTaskBanner } from "./ExternallyConnectedTaskBanner"; import { boardSendDraftKey, readBoardSendDraft } from "./board-send-draft"; import { ApiError } from "@/api/client"; import { queryKeys } from "@/lib/queryKeys"; +import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils"; const mockSession = vi.hoisted(() => ({ userId: "user-1" })); vi.mock("@/api/auth", () => ({ authApi: { getSession: vi.fn(async () => ({ user: { id: mockSession.userId } })) }, @@ -177,6 +178,12 @@ describe("ExternallyConnectedTaskBanner publication truth", () => { autoResendOverride.stalled = false; }); + it("keeps the connected channel label out of session replay", async () => { + const client = await renderBanner(); + expect(replayLeaks("#paperclip", container)).toEqual({ rendered: true, recorded: false }); + client.clear(); + }); + it("cancels an automatic resend and hides its draft after an account change", async () => { mockChatEndpointsApi.publishBoardMessage.mockRejectedValue(new ApiError("Bad gateway", 502, {})); const client = await renderBanner(); diff --git a/ui/src/components/chat/ExternallyConnectedTaskBanner.tsx b/ui/src/components/chat/ExternallyConnectedTaskBanner.tsx index 33e6fd7f512..9cba73f3f9e 100644 --- a/ui/src/components/chat/ExternallyConnectedTaskBanner.tsx +++ b/ui/src/components/chat/ExternallyConnectedTaskBanner.tsx @@ -41,6 +41,7 @@ import { } from "./board-send-draft"; import { LegacyBoardSendNotice } from "./LegacyBoardSendNotice"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; const providerNames: Record<ChatProvider, string> = { speko: "Speko", @@ -558,7 +559,7 @@ function ConnectedTaskComposer({ <p className="font-medium"> Connected to {providerNames[binding.provider]} </p> - <p className="truncate text-xs text-muted-foreground"> + <p className={cn("truncate text-xs text-muted-foreground", ANALYTICS_MASK_CLASS)}> {binding.externalLabel} · {binding.provider === "slack" ? "Messages you send here and agent replies are also posted to Slack." : "Agent assignment is fixed for this external task."} diff --git a/ui/src/components/coordinator/CoordinatorDecisionReceipt.tsx b/ui/src/components/coordinator/CoordinatorDecisionReceipt.tsx index 1fe18384503..c86d0e14a28 100644 --- a/ui/src/components/coordinator/CoordinatorDecisionReceipt.tsx +++ b/ui/src/components/coordinator/CoordinatorDecisionReceipt.tsx @@ -1,6 +1,8 @@ import { ArrowUpRight, Check } from "lucide-react"; import type { DecisionHistoryItem } from "@paperclipai/shared"; import { decisionHistoryContext, decisionHistoryHeadline } from "@/lib/coordinator-attention"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; /** A recorded decision links to its context; it is not a second approval form. */ export function CoordinatorDecisionReceipt({ item, onOpen, userLabelMap }: { @@ -12,7 +14,7 @@ export function CoordinatorDecisionReceipt({ item, onOpen, userLabelMap }: { const handledFor = item.handledForUserId ? userLabelMap?.get(item.handledForUserId) ?? "someone else" : null; return <button type="button" onClick={() => onOpen(item.href)} data-decision-history-item={item.id} className="coordinator-decision-receipt flex w-full items-center gap-3 rounded-xl border border-border bg-card p-4 text-left hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"> <Check className="size-4 shrink-0 text-muted-foreground" aria-hidden /> - <span className="min-w-0 flex-1 space-y-1"> + <span className={cn("min-w-0 flex-1 space-y-1", ANALYTICS_MASK_CLASS)}> <span className="block text-sm font-medium">{decisionHistoryHeadline(item, userLabelMap)}{handledFor ? <span className="font-normal text-muted-foreground"> · for @{handledFor}</span> : null}</span> <span className="block truncate text-sm text-muted-foreground">{decisionHistoryContext(item)}</span> {/* Who withdrew it is in the headline; the reason they gave is here (PAP-749 plan §3). */} diff --git a/ui/src/components/coordinator/CoordinatorNeedsYou.tsx b/ui/src/components/coordinator/CoordinatorNeedsYou.tsx index 0e2e12b02e4..a418b760565 100644 --- a/ui/src/components/coordinator/CoordinatorNeedsYou.tsx +++ b/ui/src/components/coordinator/CoordinatorNeedsYou.tsx @@ -43,6 +43,8 @@ import { BlockedTaskCardBody, RecoveryCardBody, ReviewTaskCardBody } from "./Nee import { NEEDS_YOU_SECTIONS, NeedsYouPanelRow, needsYouSection, type NeedsYouSection } from "./NeedsYouCardKit"; import { NeedsYouAudience, NeedsYouReceiptCard, NeedsYouRequester, NeedsYouTaskLink, NeedsYouTypeLabel, needsYouTaskRef } from "./NeedsYouCardParts"; import { CoordinatorNeedsYouSidePanel, needsYouReviewTab, needsYouReviewTabId, needsYouTabArtifact, type NeedsYouReviewPayload } from "./CoordinatorNeedsYouSidePanel"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; type Group = "type" | "none" | "task" | "agent" | "project"; @@ -320,7 +322,7 @@ export function CoordinatorNeedsYou() { const title = coordinatorCardTitle(item); const detail = coordinatorCardDetail(item, attentionDetailLine(item)); // The ask, with one plain line under it (UI1). - const heading = <div className="space-y-1.5"><h2>{title}</h2>{detail && !sameText(detail, title) ? <p className="text-sm text-muted-foreground">{detail}</p> : null}</div>; + const heading = <div className={cn("space-y-1.5", ANALYTICS_MASK_CLASS)}><h2>{title}</h2>{detail && !sameText(detail, title) ? <p className="text-sm text-muted-foreground">{detail}</p> : null}</div>; const footerContext = <AttentionObligationEvidence item={item} evidence={attentionObligationEvidence(obligations, item)} />; const type = attentionCardType(item); return <motion.div id={item.sourceKind === "decision" ? `coordinator-decision-${item.subject.id}` : undefined} tabIndex={item.sourceKind === "decision" ? -1 : undefined} layout={reducedMotion ? false : "position"} layoutId={reducedMotion ? undefined : id} transition={{ duration }} key={id}> diff --git a/ui/src/components/coordinator/NeedsYouCardKit.tsx b/ui/src/components/coordinator/NeedsYouCardKit.tsx index 11585abd94f..c1b6a804b37 100644 --- a/ui/src/components/coordinator/NeedsYouCardKit.tsx +++ b/ui/src/components/coordinator/NeedsYouCardKit.tsx @@ -2,6 +2,7 @@ import type { ReactNode } from "react"; import { ArrowUpRight } from "lucide-react"; import { attentionCardKind, attentionCardType, type AttentionCardType, type AttentionItem } from "@paperclipai/shared"; import { cn } from "@/lib/utils"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; /** * The parts every Needs You card is built from (PAP-775, Paper "A · Compact @@ -90,5 +91,5 @@ export function NeedsYouPanelRow({ icon, title, meta, onOpen, href, label }: { /** The small grey line at the bottom of a panel. */ export function NeedsYouPanelNote({ children }: { children: ReactNode }) { - return <p data-needs-you-note className="text-xs leading-4.5 text-muted-foreground">{children}</p>; + return <p data-needs-you-note className={cn("text-xs leading-4.5 text-muted-foreground", ANALYTICS_MASK_CLASS)}>{children}</p>; } diff --git a/ui/src/components/coordinator/NeedsYouCardParts.tsx b/ui/src/components/coordinator/NeedsYouCardParts.tsx index 86c99ce578d..3b18b28690e 100644 --- a/ui/src/components/coordinator/NeedsYouCardParts.tsx +++ b/ui/src/components/coordinator/NeedsYouCardParts.tsx @@ -17,6 +17,7 @@ import { cn } from "@/lib/utils"; import { timeAgo } from "@/lib/timeAgo"; import { DecisionCardFooter } from "@/components/DecisionCardFooter"; import { NeedsYouPanel, NeedsYouPanelRow, needsYouCardLabel } from "./NeedsYouCardKit"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; /** * Who is asking (PAP-775, UI2): the requester's avatar and name, agent or @@ -143,8 +144,8 @@ export function NeedsYouReceiptCard({ receipt, userLabelMap, onDismiss, onOpen, </div> </div> <div className="space-y-1.5"> - <h2>{receipt.title ?? "Your request"}</h2> - {receipt.reason ? <p className="text-sm text-muted-foreground">{receipt.reason}</p> : null} + <h2 className={ANALYTICS_MASK_CLASS}>{receipt.title ?? "Your request"}</h2> + {receipt.reason ? <p className={cn("text-sm text-muted-foreground", ANALYTICS_MASK_CLASS)}>{receipt.reason}</p> : null} </div> <NeedsYouPanel> <NeedsYouPanelRow icon={negative ? <StatusIcon status="cancelled" /> : <Check className="text-(--status-task-icon-done)" />} diff --git a/ui/src/components/decision-models/DecisionHistory.tsx b/ui/src/components/decision-models/DecisionHistory.tsx index 3cef0509d2f..e9658aaf358 100644 --- a/ui/src/components/decision-models/DecisionHistory.tsx +++ b/ui/src/components/decision-models/DecisionHistory.tsx @@ -4,6 +4,7 @@ import { decisionModelsApi } from "@/api/decision-models"; import { Link } from "@/lib/router"; import { formatDateTime, formatTokens, formatDetailedCents } from "@/lib/utils"; import { Button } from "@/components/ui/button"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; export function DecisionHistoryTable({ entries, fastResponse = false, fastResponsesEnabled = true }: { entries: (DecisionHistoryEntry & { publicationStatus?: string; connectionName?: string | null })[]; fastResponse?: boolean; fastResponsesEnabled?: boolean }) { if (!entries.length) return <p className="text-sm text-muted-foreground">{fastResponse ? "No fast responses in this period." : "No decision requests in this period."} <Link to={fastResponse && !fastResponsesEnabled ? "/company/settings/instance/experimental" : "/company/settings/connections"} className="underline underline-offset-4">{fastResponse ? fastResponsesEnabled ? "Configure fast response" : "Enable experimental fast responses" : "Configure a decision model"}</Link> to run a test.</p>; @@ -15,7 +16,7 @@ export function DecisionHistoryTable({ entries, fastResponse = false, fastRespon <td className="px-3 py-3"><div className="whitespace-nowrap">{formatDateTime(row.startedAt)}</div><div className="text-xs text-muted-foreground">{row.feature === "settings.test" ? "Setup test" : row.feature}</div></td> <td className="px-3 py-3">{row.actorType === "system" ? "Paperclip services" : row.userName ?? (row.responsibleUserId === "local-board" ? "Board" : "Former user")}</td> <td className="px-3 py-3">{row.issueId ? <Link className="underline underline-offset-4" to={`/issues/${row.issueIdentifier ?? row.issueId}`}>{row.issueIdentifier ?? "View task"}</Link> : "—"}</td> - {fastResponse && <td className="px-3 py-3">{row.connectionName ?? (row.connectionId ? "Removed connection" : "—")}</td>} + {fastResponse && <td className={`px-3 py-3 ${ANALYTICS_MASK_CLASS}`}>{row.connectionName ?? (row.connectionId ? "Removed connection" : "—")}</td>} <td className="px-3 py-3 font-mono text-xs">{row.model}</td> <td className="px-3 py-3"><div>{row.status === "succeeded" ? "Succeeded" : row.status === "running" ? "Running" : row.status === "unknown" ? "Unresolved" : row.status === "skipped" ? "Skipped" : row.status === "pending" ? "Pending" : "Failed"}</div>{row.publicationStatus && <div className="text-xs text-muted-foreground">{row.publicationStatus}</div>}{row.errorCode && <div className="text-xs text-muted-foreground">{row.errorCode.replaceAll("_", " ")}</div>}</td> <td className="px-3 py-3 font-mono">{row.durationMs === null ? "—" : `${(row.durationMs / 1000).toFixed(1)}s`}</td> diff --git a/ui/src/components/interrupt-handoff/InterruptHandoffViews.tsx b/ui/src/components/interrupt-handoff/InterruptHandoffViews.tsx index 1c9049dc768..b0f4630b71d 100644 --- a/ui/src/components/interrupt-handoff/InterruptHandoffViews.tsx +++ b/ui/src/components/interrupt-handoff/InterruptHandoffViews.tsx @@ -10,6 +10,7 @@ import { type ReassignInterruptCopy, type TimelineAssigneeLike, } from "../../lib/interrupt-handoff"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; /** * Presentational views for the interrupt-handoff UX clarity surfaces (PAP-10669). @@ -174,7 +175,7 @@ export function ComposerHandoffPreviewRow({ role="status" aria-live="polite" > - <span>{preview.text}</span> + <span className={ANALYTICS_MASK_CLASS}>{preview.text}</span> {preview.chip ? <PreviewChip chip={preview.chip} resolvers={resolvers} /> : null} {preview.suffix ? <span>{preview.suffix}</span> : null} </div> @@ -337,7 +338,7 @@ export function PauseAffectsSummaryView({ > <span className="font-medium text-foreground">{bucket.label}:</span> <span className="tabular-nums text-foreground">{bucket.count}</span> - <span className="text-muted-foreground">— {bucket.detail}</span> + <span className={cn("text-muted-foreground", ANALYTICS_MASK_CLASS)}>— {bucket.detail}</span> </li> ))} </ul> diff --git a/ui/src/components/issue-properties/external-object-rows.tsx b/ui/src/components/issue-properties/external-object-rows.tsx index 87e7fc01041..dc55317b316 100644 --- a/ui/src/components/issue-properties/external-object-rows.tsx +++ b/ui/src/components/issue-properties/external-object-rows.tsx @@ -16,6 +16,7 @@ import { cn } from "../../lib/utils"; import { ExternalObjectStatusIcon } from "../ExternalObjectStatusIcon"; import { PropertyRow } from "./primitives"; import { ExpandRelationListButton } from "./relation-controls"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; const EXTERNAL_OBJECT_PROPERTY_PREVIEW_COUNT = 5; @@ -45,7 +46,7 @@ function externalObjectRowLabel(group: IssueExternalObjectGroup): ReactNode { return ( <span className="inline-flex min-w-0 items-start gap-1" title={displayKey}> {Icon ? <Icon aria-hidden="true" className="h-3.5 w-3.5 shrink-0 mt-0.5" /> : null} - <span className="truncate">{displayKey}</span> + <span className={cn("truncate", ANALYTICS_MASK_CLASS)}>{displayKey}</span> </span> ); } @@ -115,7 +116,7 @@ function ExternalObjectPropertyValue({ group }: { group: IssueExternalObjectGrou sizeClassName="h-3.5 w-3.5" label={`${providerLabel}: ${statusLabel}`} /> - <span className="min-w-0 truncate">{value}</span> + <span className={cn("min-w-0 truncate", ANALYTICS_MASK_CLASS)}>{value}</span> </> ); const className = cn( diff --git a/ui/src/components/routine-triggers/WebhookFields.test.tsx b/ui/src/components/routine-triggers/WebhookFields.test.tsx new file mode 100644 index 00000000000..81aadd629ec --- /dev/null +++ b/ui/src/components/routine-triggers/WebhookFields.test.tsx @@ -0,0 +1,16 @@ +// @vitest-environment jsdom +import { renderToStaticMarkup } from "react-dom/server"; +import { afterEach, expect, it } from "vitest"; +import { CopyField } from "./WebhookFields"; +import { isBlockedFromReplay } from "@/lib/analytics/replay-recording.test-utils"; + +afterEach(() => { document.body.innerHTML = ""; }); + +it("blocks the webhook URL and secret from session replay", () => { + document.body.innerHTML = renderToStaticMarkup(<> + <CopyField label="Webhook URL" value="https://paperclip.example.test/api/routine-triggers/hook_k4Zr9Qe1" /> + <CopyField label="Authentication key" value="whsec_Tq8vLm2Rz7Np" /> + </>); + expect(isBlockedFromReplay("hook_k4Zr9Qe1", document.body)).toBe(true); + expect(isBlockedFromReplay("whsec_Tq8vLm2Rz7Np", document.body)).toBe(true); +}); diff --git a/ui/src/components/routine-triggers/WebhookFields.tsx b/ui/src/components/routine-triggers/WebhookFields.tsx index e55e10ebf61..aa2be35dbd1 100644 --- a/ui/src/components/routine-triggers/WebhookFields.tsx +++ b/ui/src/components/routine-triggers/WebhookFields.tsx @@ -4,6 +4,7 @@ import { Button } from "@/components/ui/button"; import { Label } from "@/components/ui/label"; import { copyTextToClipboard } from "@/lib/clipboard"; import { AgentSetupPrompt } from "@/components/AgentSetupPrompt"; +import { ANALYTICS_NO_CAPTURE_CLASS } from "@/lib/analytics/privacy"; export function CopyField({ label, @@ -20,7 +21,7 @@ export function CopyField({ <div className="space-y-1.5"> <Label className="text-xs">{label}</Label> <div className="flex min-w-0 items-center gap-2 rounded-md border border-border bg-background px-3 py-2"> - <code title={value} className="min-w-0 flex-1 truncate text-xs"> + <code title={value} className={`min-w-0 flex-1 truncate text-xs ${ANALYTICS_NO_CAPTURE_CLASS}`}> {value} </code> <Button diff --git a/ui/src/components/run-log/LogViewer.tsx b/ui/src/components/run-log/LogViewer.tsx index 7109a40e2eb..45a3b8e1b11 100644 --- a/ui/src/components/run-log/LogViewer.tsx +++ b/ui/src/components/run-log/LogViewer.tsx @@ -39,6 +39,7 @@ import { RunInvocationCard, redactPathText, } from "./RunDetails"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; export function LogViewer({ run, adapterType }: { run: HeartbeatRun; adapterType: string }) { const { visible } = usePageVisibility(); @@ -557,7 +558,7 @@ export function LogViewer({ run, adapterType }: { run: HeartbeatRun; adapterType </div> {(run.status === "failed" || run.status === "timed_out") && ( - <div className="rounded-lg border border-red-300 dark:border-red-500/30 bg-red-50 dark:bg-red-950/20 p-3 space-y-2"> + <div className={cn("rounded-lg border border-red-300 dark:border-red-500/30 bg-red-50 dark:bg-red-950/20 p-3 space-y-2", ANALYTICS_MASK_CLASS)}> <div className="text-xs font-medium text-red-700 dark:text-red-300">Failure details</div> {run.error && ( <div className="text-xs text-red-600 dark:text-red-200"> @@ -568,7 +569,7 @@ export function LogViewer({ run, adapterType }: { run: HeartbeatRun; adapterType {run.stderrExcerpt && run.stderrExcerpt.trim() && ( <div> <div className="text-xs text-red-700 dark:text-red-300 mb-1">stderr excerpt</div> - <pre className="bg-red-50 dark:bg-neutral-950 rounded-md p-2 text-xs overflow-x-auto whitespace-pre-wrap text-red-800 dark:text-red-100"> + <pre className={cn("bg-red-50 dark:bg-neutral-950 rounded-md p-2 text-xs overflow-x-auto whitespace-pre-wrap text-red-800 dark:text-red-100", ANALYTICS_MASK_CLASS)}> {redactPathText(run.stderrExcerpt, censorUsernameInLogs)} </pre> </div> @@ -576,7 +577,7 @@ export function LogViewer({ run, adapterType }: { run: HeartbeatRun; adapterType {run.resultJson && ( <div> <div className="text-xs text-red-700 dark:text-red-300 mb-1">adapter result JSON</div> - <pre className="bg-red-50 dark:bg-neutral-950 rounded-md p-2 text-xs overflow-x-auto whitespace-pre-wrap text-red-800 dark:text-red-100"> + <pre className={cn("bg-red-50 dark:bg-neutral-950 rounded-md p-2 text-xs overflow-x-auto whitespace-pre-wrap text-red-800 dark:text-red-100", ANALYTICS_MASK_CLASS)}> {JSON.stringify(redactPathValue(run.resultJson, censorUsernameInLogs), null, 2)} </pre> </div> @@ -584,7 +585,7 @@ export function LogViewer({ run, adapterType }: { run: HeartbeatRun; adapterType {run.stdoutExcerpt && run.stdoutExcerpt.trim() && !run.resultJson && ( <div> <div className="text-xs text-red-700 dark:text-red-300 mb-1">stdout excerpt</div> - <pre className="bg-red-50 dark:bg-neutral-950 rounded-md p-2 text-xs overflow-x-auto whitespace-pre-wrap text-red-800 dark:text-red-100"> + <pre className={cn("bg-red-50 dark:bg-neutral-950 rounded-md p-2 text-xs overflow-x-auto whitespace-pre-wrap text-red-800 dark:text-red-100", ANALYTICS_MASK_CLASS)}> {redactPathText(run.stdoutExcerpt, censorUsernameInLogs)} </pre> </div> @@ -601,7 +602,7 @@ export function LogViewer({ run, adapterType }: { run: HeartbeatRun; adapterType {loadingMoreEvents ? "Loading..." : eventsError ? "Retry events" : "Load more events"} </Button> )} - <div className="bg-neutral-100 dark:bg-neutral-950 rounded-lg p-3 font-mono text-xs space-y-0.5"> + <div className={cn("bg-neutral-100 dark:bg-neutral-950 rounded-lg p-3 font-mono text-xs space-y-0.5", ANALYTICS_MASK_CLASS)}> {events.map((evt) => { const color = evt.color ?? (evt.level ? levelColors[evt.level] : null) diff --git a/ui/src/components/run-log/RunDetails.tsx b/ui/src/components/run-log/RunDetails.tsx index 7eef5a734a0..672aa2734b5 100644 --- a/ui/src/components/run-log/RunDetails.tsx +++ b/ui/src/components/run-log/RunDetails.tsx @@ -9,6 +9,7 @@ import { Collapsible, CollapsibleTrigger, CollapsibleContent } from "@/component import { type HeartbeatRun, type WorkspaceOperation } from "@paperclipai/shared"; import { redactHomePathUserSegments, redactHomePathUserSegmentsInValue } from "@paperclipai/adapter-utils"; import { Badge } from "@/components/ui/badge"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; export const RUN_LOG_PAGE_BYTES = 256_000; @@ -208,7 +209,7 @@ export function RunInvocationCard({ {commandLine && ( <div className="text-xs break-all"> <span className="text-muted-foreground">Command: </span> - <span className="font-mono">{commandLine}</span> + <span className={cn("font-mono", ANALYTICS_MASK_CLASS)}>{commandLine}</span> </div> )} {Array.isArray(payload.commandNotes) && payload.commandNotes.length > 0 && ( @@ -218,7 +219,7 @@ export function RunInvocationCard({ {payload.commandNotes .filter((value): value is string => typeof value === "string" && value.trim().length > 0) .map((note, idx) => ( - <li key={`${idx}-${note}`} className="text-xs break-all font-mono"> + <li key={`${idx}-${note}`} className={cn("text-xs break-all font-mono", ANALYTICS_MASK_CLASS)}> {note} </li> ))} @@ -228,7 +229,7 @@ export function RunInvocationCard({ {payload.prompt !== undefined && ( <div> <div className="text-xs text-muted-foreground mb-1">Prompt</div> - <pre className="bg-neutral-100 dark:bg-neutral-950 rounded-md p-2 text-xs overflow-x-auto whitespace-pre-wrap"> + <pre className={cn("bg-neutral-100 dark:bg-neutral-950 rounded-md p-2 text-xs overflow-x-auto whitespace-pre-wrap", ANALYTICS_MASK_CLASS)}> {typeof payload.prompt === "string" ? redactPathText(payload.prompt, censorUsernameInLogs) : JSON.stringify(redactPathValue(payload.prompt, censorUsernameInLogs), null, 2)} @@ -238,7 +239,7 @@ export function RunInvocationCard({ {payload.context !== undefined && ( <div> <div className="text-xs text-muted-foreground mb-1">Context</div> - <pre className="bg-neutral-100 dark:bg-neutral-950 rounded-md p-2 text-xs overflow-x-auto whitespace-pre-wrap"> + <pre className={cn("bg-neutral-100 dark:bg-neutral-950 rounded-md p-2 text-xs overflow-x-auto whitespace-pre-wrap", ANALYTICS_MASK_CLASS)}> {JSON.stringify(redactPathValue(payload.context, censorUsernameInLogs), null, 2)} </pre> </div> @@ -246,7 +247,7 @@ export function RunInvocationCard({ {payload.env !== undefined && ( <div> <div className="text-xs text-muted-foreground mb-1">Environment</div> - <pre className="bg-neutral-100 dark:bg-neutral-950 rounded-md p-2 text-xs overflow-x-auto whitespace-pre-wrap font-mono"> + <pre className={cn("bg-neutral-100 dark:bg-neutral-950 rounded-md p-2 text-xs overflow-x-auto whitespace-pre-wrap font-mono", ANALYTICS_MASK_CLASS)}> {formatEnvForDisplay(payload.env, censorUsernameInLogs)} </pre> </div> @@ -462,7 +463,7 @@ export function WorkspaceOperationsSection({ {operation.stderrExcerpt && operation.stderrExcerpt.trim() && ( <div> <div className="mb-1 text-xs text-red-700 dark:text-red-300">stderr excerpt</div> - <pre className="rounded-md bg-red-50 p-2 text-xs whitespace-pre-wrap break-all text-red-800 dark:bg-neutral-950 dark:text-red-100"> + <pre className={cn("rounded-md bg-red-50 p-2 text-xs whitespace-pre-wrap break-all text-red-800 dark:bg-neutral-950 dark:text-red-100", ANALYTICS_MASK_CLASS)}> {redactPathText(operation.stderrExcerpt, censorUsernameInLogs)} </pre> </div> @@ -470,7 +471,7 @@ export function WorkspaceOperationsSection({ {operation.stdoutExcerpt && operation.stdoutExcerpt.trim() && ( <div> <div className="mb-1 text-xs text-muted-foreground">stdout excerpt</div> - <pre className="rounded-md bg-neutral-100 p-2 text-xs whitespace-pre-wrap break-all dark:bg-neutral-950"> + <pre className={cn("rounded-md bg-neutral-100 p-2 text-xs whitespace-pre-wrap break-all dark:bg-neutral-950", ANALYTICS_MASK_CLASS)}> {redactPathText(operation.stdoutExcerpt, censorUsernameInLogs)} </pre> </div> diff --git a/ui/src/components/search/SearchResultRow.tsx b/ui/src/components/search/SearchResultRow.tsx index 5f8a4db7a56..7cb322c63b0 100644 --- a/ui/src/components/search/SearchResultRow.tsx +++ b/ui/src/components/search/SearchResultRow.tsx @@ -9,6 +9,7 @@ import { StatusIcon } from "../StatusIcon"; import { Identity } from "../Identity"; import { HighlightedText, type HighlightedTextProps } from "./HighlightedText"; import { taskStatusIconProps } from "@/lib/task-status-presentation"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; type SnippetStyle = { Icon: ComponentType<SVGProps<SVGSVGElement>>; @@ -265,7 +266,7 @@ function SnippetLine({ text, highlights, field, fallbackLabel, multiline = false <HighlightedText text={text} highlights={highlights} - className={multiline ? "line-clamp-2 leading-relaxed" : "line-clamp-1 truncate"} + className={cn(multiline ? "line-clamp-2 leading-relaxed" : "line-clamp-1 truncate", ANALYTICS_MASK_CLASS)} /> </div> ); diff --git a/ui/src/components/skill-studio/SkillSourceConnectionRepair.tsx b/ui/src/components/skill-studio/SkillSourceConnectionRepair.tsx index 33ee7b94a1a..eb41dd3b3c1 100644 --- a/ui/src/components/skill-studio/SkillSourceConnectionRepair.tsx +++ b/ui/src/components/skill-studio/SkillSourceConnectionRepair.tsx @@ -10,6 +10,7 @@ import { Button } from '@/components/ui/button'; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'; import { RadioCardGroup } from '@/components/ui/radio-card'; import { SkillSourceBranchRepair } from './SkillSourceBranchRepair'; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; export function SkillSourceConnectionRepair({ companyId, source, onClose, onSaved, onReturnFocus }: { companyId: string; source: SkillSource; onClose: () => void; onSaved: () => Promise<void>; @@ -41,7 +42,7 @@ export function SkillSourceConnectionRepair({ companyId, source, onClose, onSave <div className="min-h-0 overflow-y-auto space-y-4"> {query.isPending && <p role="status" className="text-sm text-muted-foreground">Loading connections…</p>} {query.error && <p role="alert" className="text-sm text-destructive">{describeError(query.error).body} <Button variant="ghost" size="sm" onClick={() => void query.refetch()}>Try again</Button></p>} - <RadioCardGroup ariaLabel="GitHub connection" value={connectionId} onValueChange={setConnectionId} disabled={save.isPending} + <RadioCardGroup ariaLabel="GitHub connection" className={ANALYTICS_MASK_CLASS} value={connectionId} onValueChange={setConnectionId} disabled={save.isPending} options={connections.map(connection => ({ value: connection.id, title: connection.name }))} /> {query.isSuccess && connections.length === 0 && <p className="text-sm text-muted-foreground">Connect GitHub to continue.</p>} <Button asChild variant="link" className="justify-start p-0"><Link to="/apps">Manage GitHub connections</Link></Button> diff --git a/ui/src/components/skills/ConnectedAppSkills.tsx b/ui/src/components/skills/ConnectedAppSkills.tsx index b1f5aeeb20e..2dfcc0ad373 100644 --- a/ui/src/components/skills/ConnectedAppSkills.tsx +++ b/ui/src/components/skills/ConnectedAppSkills.tsx @@ -9,6 +9,8 @@ import { useToastActions } from "../../context/ToastContext"; import { formatBytes } from "../../lib/issue-output"; import { queryKeys } from "../../lib/queryKeys"; import { describeError } from "@/api/errors"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; const STATUS_LABEL: Record<CompanyMcpSkill["status"], string> = { pending_review: "Needs review", @@ -129,7 +131,7 @@ export function ConnectedAppSkillsList({ skills, pendingSkillId, preview, onPrev preview?.error ? <p className="text-sm text-destructive">{preview.error}</p> : preview?.loading || !previewCurrent ? <p className="text-sm text-muted-foreground">Loading instructions…</p> // Shown as text: the content comes from the app and is never rendered as a page. - : <pre className="max-h-96 overflow-auto whitespace-pre-wrap rounded-md bg-muted p-3 font-mono text-xs">{preview?.markdown}</pre> + : <pre className={cn("max-h-96 overflow-auto whitespace-pre-wrap rounded-md bg-muted p-3 font-mono text-xs", ANALYTICS_MASK_CLASS)}>{preview?.markdown}</pre> ) : null} </li> ); diff --git a/ui/src/components/task-chat/TaskChatCompactInteractionCard.tsx b/ui/src/components/task-chat/TaskChatCompactInteractionCard.tsx index e5c4831cd16..7064f866cec 100644 --- a/ui/src/components/task-chat/TaskChatCompactInteractionCard.tsx +++ b/ui/src/components/task-chat/TaskChatCompactInteractionCard.tsx @@ -76,6 +76,7 @@ import { } from "./TaskChatComposerTakeoverContext"; import { TaskChatPlanPreviewCard } from "./TaskChatPlanPreviewCard"; import { TaskChatRichInput } from "./TaskChatRichInput"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; const TAKEOVER_TEXTAREA_CLASS = "min-h-16 resize-y border-0 bg-muted/35 text-sm shadow-none focus-visible:ring-0 focus-visible:ring-offset-0"; @@ -578,7 +579,7 @@ function ReceiptDisclosure({ {interaction.payload.toolAction.previewMarkdown} </MarkdownBody> </div> - <pre className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words font-mono text-xs"> + <pre className={cn("mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words font-mono text-xs", ANALYTICS_MASK_CLASS)}> {interaction.payload.toolAction.argumentsSummaryJson} </pre> <ToolActionAuditHashCopy hash={interaction.payload.toolAction.argumentsHash} /> @@ -954,7 +955,7 @@ function ConfirmationCard({ <summary className="cursor-pointer text-xs font-medium text-muted-foreground"> Arguments </summary> - <pre className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words font-mono text-xs text-foreground"> + <pre className={cn("mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words font-mono text-xs text-foreground", ANALYTICS_MASK_CLASS)}> {interaction.payload.toolAction.argumentsSummaryJson} </pre> <ToolActionAuditHashCopy hash={interaction.payload.toolAction.argumentsHash} /> diff --git a/ui/src/components/task-chat/TaskChatProtocolActivityRow.tsx b/ui/src/components/task-chat/TaskChatProtocolActivityRow.tsx index fca5eba7ec6..4aaa7da9c36 100644 --- a/ui/src/components/task-chat/TaskChatProtocolActivityRow.tsx +++ b/ui/src/components/task-chat/TaskChatProtocolActivityRow.tsx @@ -28,6 +28,7 @@ import { protocolActivityPresentation, providerNoticeSeverity, } from "./task-chat-activity-presentation"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; const COMPACT_RESEARCH_RESULT_LIMIT = 5; const COMPACT_WORKSPACE_FILE_LIMIT = 8; @@ -176,7 +177,7 @@ function ProviderDetails({ item, neutral = false }: { item: TaskChatProviderActi <DetailList details={item.details} /> ) : null} {item.output ? ( - <pre className="max-h-(--sz-64) overflow-auto whitespace-pre-wrap rounded-sm bg-muted/50 p-2 font-mono text-(length:--text-micro) text-foreground">{item.output}</pre> + <pre className={cn("max-h-(--sz-64) overflow-auto whitespace-pre-wrap rounded-sm bg-muted/50 p-2 font-mono text-(length:--text-micro) text-foreground", ANALYTICS_MASK_CLASS)}>{item.output}</pre> ) : null} {item.outputTruncated ? <p className="text-muted-foreground">Output truncated to 8 KiB.</p> : null} </div> @@ -224,7 +225,7 @@ function WorkspaceFileDetails({ item }: { item: TaskChatWorkspaceFileItem }) { item.presentation === "document" ? ( <div className="max-h-(--sz-64) overflow-auto rounded-sm bg-muted/30 p-2 text-foreground"><MarkdownBody>{item.preview}</MarkdownBody></div> ) : ( - <pre className="max-h-(--sz-64) overflow-auto whitespace-pre-wrap rounded-sm bg-muted/50 p-2 font-mono text-(length:--text-micro) text-foreground">{item.preview}</pre> + <pre className={cn("max-h-(--sz-64) overflow-auto whitespace-pre-wrap rounded-sm bg-muted/50 p-2 font-mono text-(length:--text-micro) text-foreground", ANALYTICS_MASK_CLASS)}>{item.preview}</pre> ) ) : <p className="text-muted-foreground">Preview unavailable.</p>} {item.previewTruncated ? <p className="text-muted-foreground">Preview truncated by the runner.</p> : null} diff --git a/ui/src/components/task-chat/TaskChatProtocolCard.tsx b/ui/src/components/task-chat/TaskChatProtocolCard.tsx index b56664bdc6e..cfea850bc9e 100644 --- a/ui/src/components/task-chat/TaskChatProtocolCard.tsx +++ b/ui/src/components/task-chat/TaskChatProtocolCard.tsx @@ -57,6 +57,7 @@ import { TaskChatDiffCounts, TaskChatDiffView } from "./TaskChatDiffView"; import { parseUnifiedDiffLines } from "./diff-lines"; import { useArtifactsV1Enabled } from "@/hooks/useArtifactsV1Enabled"; import { ArtifactFileRow, ArtifactRow, fileRowSourceFromAttachment, fileRowSourceFromWorkProduct, subjectFromAttachment, subjectFromDocumentSummary, subjectFromWorkProduct, workProductStateBadge } from "@/components/artifacts/v1"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; export interface TaskChatProtocolCardProps { item: TaskChatProtocolItem; @@ -400,7 +401,7 @@ function ProviderActivityCard({ </dl> ) : null} {item.output ? ( - <pre className="mt-2 max-h-(--sz-64) overflow-auto whitespace-pre-wrap rounded-sm bg-muted/50 p-2 font-mono text-xs text-foreground"> + <pre className={cn("mt-2 max-h-(--sz-64) overflow-auto whitespace-pre-wrap rounded-sm bg-muted/50 p-2 font-mono text-xs text-foreground", ANALYTICS_MASK_CLASS)}> {item.output} </pre> ) : null} @@ -623,7 +624,7 @@ function WorkspaceFileCard({ item }: { item: TaskChatWorkspaceFileItem }) { src={item.preview} /> ) : ( - <pre className="max-h-(--sz-70vh) overflow-auto whitespace-pre-wrap rounded-sm bg-muted/50 p-3 font-mono text-xs"> + <pre className={cn("max-h-(--sz-70vh) overflow-auto whitespace-pre-wrap rounded-sm bg-muted/50 p-3 font-mono text-xs", ANALYTICS_MASK_CLASS)}> {item.preview} </pre> )} diff --git a/ui/src/components/task-chat/TaskChatRunnerActivityGroup.tsx b/ui/src/components/task-chat/TaskChatRunnerActivityGroup.tsx index c5d1da43cf7..852fcea5671 100644 --- a/ui/src/components/task-chat/TaskChatRunnerActivityGroup.tsx +++ b/ui/src/components/task-chat/TaskChatRunnerActivityGroup.tsx @@ -35,6 +35,7 @@ import { toolActivityPresentation, type ToolIcon } from "./tool-taxonomy"; import { useTaskChatShimmer } from "./TaskChatShimmer"; import { TaskChatDiffCounts, TaskChatDiffView } from "./TaskChatDiffView"; import { useTaskReferenceLabel, withTaskReference } from "./task-reference"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; type Activity = TaskChatActivityPhaseItem["items"][number]; type ToolActivity = Extract<Activity, { kind: "tool" }>; @@ -430,7 +431,7 @@ function ActivityDetailsBody({ item }: { item: Activity }) { ) : null} {item.blockedReason ? <p className="text-destructive">Blocked: {item.blockedReason}</p> : null} {item.detail ? ( - <pre className="whitespace-pre-wrap break-words font-mono"> + <pre className={cn("whitespace-pre-wrap break-words font-mono", ANALYTICS_MASK_CLASS)}> {item.detail} </pre> ) : null} diff --git a/ui/src/components/task-chat/TaskChatToolCard.tsx b/ui/src/components/task-chat/TaskChatToolCard.tsx index 7e79f3b4cd5..9a9d8da86ee 100644 --- a/ui/src/components/task-chat/TaskChatToolCard.tsx +++ b/ui/src/components/task-chat/TaskChatToolCard.tsx @@ -16,6 +16,7 @@ import { useTaskReferenceLabel, withTaskReference } from "./task-reference"; import { ProviderToolIcon, useProviderToolIcons } from "@/components/ProviderToolIcon"; import type { ToolCallProgressSnapshot } from "@paperclipai/shared"; import { TaskChatToolProgress, useToolCallProgress } from "./tool-call-progress"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; const STATUS_ICON = { pending: { Icon: Loader2, spin: false, tone: "text-muted-foreground" }, @@ -149,7 +150,7 @@ export function TaskChatToolCard({ item, progress: givenProgress }: { </div> ) : null} {item.detail && showDetail ? ( - <pre className="task-chat-expanded-line-wrap ml-1.5 mt-0.5 min-w-0 max-w-full overflow-hidden whitespace-pre-wrap border-l-2 border-border py-1 pl-2.5 font-mono text-(length:--text-micro) leading-relaxed text-muted-foreground"> + <pre className={cn("task-chat-expanded-line-wrap ml-1.5 mt-0.5 min-w-0 max-w-full overflow-hidden whitespace-pre-wrap border-l-2 border-border py-1 pl-2.5 font-mono text-(length:--text-micro) leading-relaxed text-muted-foreground", ANALYTICS_MASK_CLASS)}> {item.detail} </pre> ) : null} diff --git a/ui/src/components/task-side-panel/TaskAttachmentPanel.tsx b/ui/src/components/task-side-panel/TaskAttachmentPanel.tsx index 738de068a7d..ba5e8264e9f 100644 --- a/ui/src/components/task-side-panel/TaskAttachmentPanel.tsx +++ b/ui/src/components/task-side-panel/TaskAttachmentPanel.tsx @@ -16,6 +16,8 @@ import { attachmentDownloadPath, isMarkdownAttachment, isTextAttachment } from " import { queryKeys } from "@/lib/queryKeys"; import { readTextPreview, TEXT_PREVIEW_MAX_BYTES } from "@/lib/text-preview"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; export { readTextPreview, TEXT_PREVIEW_MAX_BYTES } from "@/lib/text-preview"; export function TextAttachmentPreview({ title, text, markdown, html = false, csv = false, patch = isPatchFile(title), downloadUrl }: { @@ -40,13 +42,13 @@ export function TextAttachmentPreview({ title, text, markdown, html = false, csv <a href={downloadUrl} download aria-label={`Download ${title}`} title={`Download ${title}`}><Download aria-hidden /></a> </Button> </header> - <div className={renderHtml || renderCsv ? "flex min-h-0 flex-1 flex-col overflow-hidden" : "min-h-0 min-w-0 flex-1 overflow-auto p-4"}> + <div className={cn(renderHtml || renderCsv ? "flex min-h-0 flex-1 flex-col overflow-hidden" : "min-h-0 min-w-0 flex-1 overflow-auto p-4", ANALYTICS_MASK_CLASS)}> {text.length === 0 ? <p className="text-sm text-muted-foreground">File is empty.</p> : renderCsv ? <CsvPreview text={text} title={title} /> : renderHtml ? <HtmlArtifactPreview html={text} title={title} /> : markdown && mode === "rendered" ? <MarkdownBody mediaMode="reference">{text}</MarkdownBody> - : patch ? <pre className="paperclip-patch-source m-0 min-w-0 whitespace-pre-wrap wrap-anywhere font-mono text-sm" aria-label={`${title} patch`}><code><PatchLines text={text} /></code></pre> - : <pre className="whitespace-pre-wrap wrap-anywhere font-mono text-sm" aria-label={`${title} raw text`}>{text}</pre>} + : patch ? <pre className={cn("paperclip-patch-source m-0 min-w-0 whitespace-pre-wrap wrap-anywhere font-mono text-sm", ANALYTICS_MASK_CLASS)} aria-label={`${title} patch`}><code><PatchLines text={text} /></code></pre> + : <pre className={cn("whitespace-pre-wrap wrap-anywhere font-mono text-sm", ANALYTICS_MASK_CLASS)} aria-label={`${title} raw text`}>{text}</pre>} </div> </div> ); diff --git a/ui/src/components/transcript/RunTranscriptView.tsx b/ui/src/components/transcript/RunTranscriptView.tsx index af8a05676bd..166eb701a42 100644 --- a/ui/src/components/transcript/RunTranscriptView.tsx +++ b/ui/src/components/transcript/RunTranscriptView.tsx @@ -14,6 +14,7 @@ import { User, } from "lucide-react"; import { toolTaxonomy } from "../task-chat/tool-taxonomy"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; /** Family glyph for a tool block/row; the taxonomy falls back to Wrench. */ function ToolFamilyIcon({ name, className }: { name: string; className?: string }) { @@ -878,7 +879,7 @@ function TranscriptProviderActivity({ block, density }: { block: Extract<Transcr {steps.length > 0 ? <ol className="space-y-1">{steps.map((step, index) => <li key={String(step.stepId ?? index)}><span className="mr-2" aria-hidden="true">{step.status === "completed" ? "✓" : step.status === "blocked" ? "!" : "○"}</span>{String(step.body ?? "")}</li>)}</ol> : null} {children.length > 0 ? <ul className="space-y-1">{children.map((child, index) => <li key={String(child.childId ?? index)}><strong>{String(child.role ?? "Child agent")}</strong> · {String(child.status ?? "unknown")}<div className="text-muted-foreground">{String(child.summary ?? "")}</div></li>)}</ul> : null} {sources.length > 0 ? <ul className="space-y-1">{sources.map((source, index) => { const url = typeof source.url === "string" && /^https?:\/\//.test(source.url) ? source.url : null; return <li key={String(source.sourceId ?? index)}>{url ? <a className="underline" href={url} target="_blank" rel="noreferrer">{String(source.title ?? url)}</a> : String(source.title ?? "Unavailable source")} <span className="text-muted-foreground">Provider-reported</span></li>; })}</ul> : null} - {output ? <pre className="max-h-64 overflow-auto whitespace-pre-wrap rounded bg-background p-2 font-mono">{output}</pre> : null} + {output ? <pre className={cn("max-h-64 overflow-auto whitespace-pre-wrap rounded bg-background p-2 font-mono", ANALYTICS_MASK_CLASS)}>{output}</pre> : null} {block.family === "provider_notice" && Array.isArray(block.payload.details) ? <dl className="space-y-1">{block.payload.details.slice(0, 64).map((value, index) => { const detail = asRecord(value); return detail && typeof detail.name === "string" && typeof detail.value === "string" ? <div key={index}><dt className="text-muted-foreground">{detail.name}</dt><dd className="whitespace-pre-wrap break-words">{detail.value}</dd></div> : null; })}</dl> : null} {block.family === "model_identity" ? <div><span className="text-muted-foreground">Requested</span> {String(block.payload.requestedModel ?? "—")} · <span className="text-muted-foreground">Effective</span> {String(block.payload.effectiveModel ?? "—")}</div> : null} </div> : null} @@ -1109,7 +1110,7 @@ function TranscriptToolCard({ <div className="mb-1 text-(length:--text-nano) font-semibold uppercase tracking-(--tracking-caps) text-muted-foreground"> Input </div> - <pre className="overflow-x-auto whitespace-pre-wrap break-words font-mono text-(length:--text-micro) text-foreground/80"> + <pre className={cn("overflow-x-auto whitespace-pre-wrap break-words font-mono text-(length:--text-micro) text-foreground/80", ANALYTICS_MASK_CLASS)}> {formatToolPayload(block.input) || "<empty>"} </pre> </div> @@ -1117,7 +1118,7 @@ function TranscriptToolCard({ <div className="mb-1 text-(length:--text-nano) font-semibold uppercase tracking-(--tracking-caps) text-muted-foreground"> Result </div> - <pre className={cn( + <pre className={cn(ANALYTICS_MASK_CLASS, "overflow-x-auto whitespace-pre-wrap break-words font-mono text-(length:--text-micro)", block.status === "error" ? "text-red-700 dark:text-red-300" : "text-foreground/80", )}> @@ -1262,7 +1263,7 @@ function TranscriptCommandGroup({ </span> </div> {item.result && ( - <pre className={cn( + <pre className={cn(ANALYTICS_MASK_CLASS, "overflow-x-auto whitespace-pre-wrap break-words font-mono text-(length:--text-micro)", item.status === "error" ? "text-red-700 dark:text-red-300" : "text-foreground/80", )}> @@ -1403,14 +1404,14 @@ function TranscriptToolGroup({ <div className={cn("grid gap-2 pl-7", compact ? "grid-cols-1" : "lg:grid-cols-2")}> <div> <div className="mb-0.5 text-(length:--text-nano) font-semibold uppercase tracking-(--tracking-caps) text-muted-foreground">Input</div> - <pre className="overflow-x-auto whitespace-pre-wrap break-words font-mono text-(length:--text-micro) text-foreground/80"> + <pre className={cn("overflow-x-auto whitespace-pre-wrap break-words font-mono text-(length:--text-micro) text-foreground/80", ANALYTICS_MASK_CLASS)}> {formatToolPayload(item.input) || "<empty>"} </pre> </div> {item.result && ( <div> <div className="mb-0.5 text-(length:--text-nano) font-semibold uppercase tracking-(--tracking-caps) text-muted-foreground">Result</div> - <pre className={cn( + <pre className={cn(ANALYTICS_MASK_CLASS, "overflow-x-auto whitespace-pre-wrap break-words font-mono text-(length:--text-micro)", item.status === "error" ? "text-red-700 dark:text-red-300" : "text-foreground/80", )}> @@ -1506,7 +1507,7 @@ function TranscriptEventRow({ </div> )} {block.detail && ( - <pre className="mt-2 overflow-x-auto whitespace-pre-wrap break-words font-mono text-(length:--text-micro) text-foreground/75"> + <pre className={cn("mt-2 overflow-x-auto whitespace-pre-wrap break-words font-mono text-(length:--text-micro) text-foreground/75", ANALYTICS_MASK_CLASS)}> {block.detail} </pre> )} @@ -1559,7 +1560,7 @@ function TranscriptDiffGroup({ {open ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />} </div> {open && ( - <pre className={cn( + <pre className={cn(ANALYTICS_MASK_CLASS, "mt-2 overflow-x-auto whitespace-pre-wrap break-words font-mono pl-5", compact ? "text-(length:--text-micro)" : "text-xs", )}> @@ -1637,7 +1638,7 @@ function TranscriptStderrGroup({ {open ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />} </div> {open && ( - <pre className="mt-2 overflow-x-auto whitespace-pre-wrap break-words font-mono text-(length:--text-micro) text-amber-700/80 dark:text-amber-300/80 pl-5"> + <pre className={cn("mt-2 overflow-x-auto whitespace-pre-wrap break-words font-mono text-(length:--text-micro) text-amber-700/80 dark:text-amber-300/80 pl-5", ANALYTICS_MASK_CLASS)}> {block.lines.map((line, i) => ( <span key={`${line.ts}-${i}`}> <span className="select-none text-amber-500/50 dark:text-amber-400/40">{i > 0 ? "\n" : ""}</span> @@ -1674,7 +1675,7 @@ function TranscriptSystemGroup({ {open ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />} </div> {open && ( - <pre className="mt-2 overflow-x-auto whitespace-pre-wrap break-words font-mono text-(length:--text-micro) text-blue-700/80 dark:text-blue-300/80 pl-5"> + <pre className={cn("mt-2 overflow-x-auto whitespace-pre-wrap break-words font-mono text-(length:--text-micro) text-blue-700/80 dark:text-blue-300/80 pl-5", ANALYTICS_MASK_CLASS)}> {block.lines.map((line, i) => ( <span key={`${line.ts}-${i}`}> <span className="select-none text-blue-500/40 dark:text-blue-400/30">{i > 0 ? "\n" : ""}</span> @@ -1714,7 +1715,7 @@ function TranscriptStdoutRow({ </button> </div> {open && ( - <pre className={cn( + <pre className={cn(ANALYTICS_MASK_CLASS, "mt-2 overflow-x-auto whitespace-pre-wrap break-words font-mono text-foreground/80", density === "compact" ? "text-(length:--text-micro)" : "text-xs", )}> @@ -1834,7 +1835,7 @@ function RawTranscriptView({ <span className="text-(length:--text-nano) uppercase tracking-(--tracking-caps) text-muted-foreground"> {entry.kind} </span> - <pre className="min-w-0 whitespace-pre-wrap break-words text-foreground/80"> + <pre className={cn("min-w-0 whitespace-pre-wrap break-words text-foreground/80", ANALYTICS_MASK_CLASS)}> {rawEntryContent(entry)} </pre> </div> @@ -1868,7 +1869,7 @@ export function RunTranscriptView({ if (entries.length === 0) { return ( - <div className={cn("rounded-2xl border border-dashed border-border/70 bg-background/40 p-4 text-sm text-muted-foreground", className)}> + <div className={cn("rounded-2xl border border-dashed border-border/70 bg-background/40 p-4 text-sm text-muted-foreground", className, ANALYTICS_MASK_CLASS)}> {emptyMessage} </div> ); @@ -1876,14 +1877,14 @@ export function RunTranscriptView({ if (mode === "raw") { return ( - <div className={className}> + <div className={cn(className, ANALYTICS_MASK_CLASS)}> <RawTranscriptView entries={visibleEntries} density={density} /> </div> ); } return ( - <div className={cn("space-y-3", className)}> + <div className={cn("space-y-3", className, ANALYTICS_MASK_CLASS)}> {keyedBlocks.map(({ block, key }, index) => ( <div key={key} diff --git a/ui/src/components/ui/button.tsx b/ui/src/components/ui/button.tsx index 161a28aaaaa..dac25928f69 100644 --- a/ui/src/components/ui/button.tsx +++ b/ui/src/components/ui/button.tsx @@ -3,7 +3,6 @@ import { cva, type VariantProps } from "class-variance-authority" import { Slot } from "radix-ui" import { cn } from "@/lib/utils" -import { ANALYTICS_UNMASK_PROPS } from "@/lib/analytics/privacy" const buttonVariants = cva( "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-(--tp-color-background-color-border-color-box-shadow-opacity) disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-(length:--rad-3) aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive", @@ -45,15 +44,12 @@ const Button = React.forwardRef< React.ComponentProps<"button"> & VariantProps<typeof buttonVariants> & { asChild?: boolean - /** The label is fixed product copy, so session replay may show it. */ - analyticsChrome?: boolean } >(function Button({ className, variant = "default", size = "default", asChild = false, - analyticsChrome = false, ...props }, ref) { const Comp = asChild ? Slot.Root : "button" @@ -62,7 +58,6 @@ const Button = React.forwardRef< <Comp ref={ref} data-slot="button" - {...(analyticsChrome ? ANALYTICS_UNMASK_PROPS : {})} data-variant={variant} data-size={size} className={cn(buttonVariants({ variant, size, className }))} diff --git a/ui/src/components/ui/label.tsx b/ui/src/components/ui/label.tsx index bd8e9cf2013..f752f82ba6b 100644 --- a/ui/src/components/ui/label.tsx +++ b/ui/src/components/ui/label.tsx @@ -2,20 +2,14 @@ import * as React from "react" import { Label as LabelPrimitive } from "radix-ui" import { cn } from "@/lib/utils" -import { ANALYTICS_UNMASK_PROPS } from "@/lib/analytics/privacy" function Label({ className, - analyticsChrome = false, ...props -}: React.ComponentProps<typeof LabelPrimitive.Root> & { - /** The text is fixed product copy, so session replay may show it. */ - analyticsChrome?: boolean -}) { +}: React.ComponentProps<typeof LabelPrimitive.Root>) { return ( <LabelPrimitive.Root data-slot="label" - {...(analyticsChrome ? ANALYTICS_UNMASK_PROPS : {})} className={cn( "flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50", className diff --git a/ui/src/components/ui/tabs.tsx b/ui/src/components/ui/tabs.tsx index d9d6644a27c..03067ae166f 100644 --- a/ui/src/components/ui/tabs.tsx +++ b/ui/src/components/ui/tabs.tsx @@ -3,7 +3,6 @@ import { cva, type VariantProps } from "class-variance-authority" import { Tabs as TabsPrimitive } from "radix-ui" import { cn } from "@/lib/utils" -import { ANALYTICS_UNMASK_PROPS } from "@/lib/analytics/privacy" function Tabs({ className, @@ -57,16 +56,11 @@ function TabsList({ function TabsTrigger({ className, - analyticsChrome = false, ...props -}: React.ComponentProps<typeof TabsPrimitive.Trigger> & { - /** The text is fixed product copy, so session replay may show it. */ - analyticsChrome?: boolean -}) { +}: React.ComponentProps<typeof TabsPrimitive.Trigger>) { return ( <TabsPrimitive.Trigger data-slot="tabs-trigger" - {...(analyticsChrome ? ANALYTICS_UNMASK_PROPS : {})} className={cn( "focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring text-foreground/60 hover:text-foreground dark:text-muted-foreground dark:hover:text-foreground relative inline-flex h-(--sz-calc-27) flex-1 items-center justify-center gap-1.5 border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-(--tp-color-background-color-border-color-box-shadow) group-data-[orientation=vertical]/tabs:w-full group-data-[orientation=vertical]/tabs:justify-start focus-visible:ring-(length:--rad-3) focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 group-data-[variant=default]/tabs-list:data-[state=active]:shadow-sm group-data-[variant=line]/tabs-list:data-[state=active]:shadow-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", "group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:border-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent", diff --git a/ui/src/components/voice/SpekoCallHistory.tsx b/ui/src/components/voice/SpekoCallHistory.tsx index e20d6371138..08915f7a248 100644 --- a/ui/src/components/voice/SpekoCallHistory.tsx +++ b/ui/src/components/voice/SpekoCallHistory.tsx @@ -6,6 +6,8 @@ import { Button } from "@/components/ui/button"; import { voiceSessionsApi } from "@/api/voiceSessions"; import { voicePhoneApi } from "@/api/voicePhone"; import { voiceHistoryApi } from "@/api/voiceHistory"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; function charge(amount: string | null) { if (amount === null) return "Not yet reported"; @@ -17,7 +19,7 @@ export function SpekoCallReport({ report }: { report: VoiceCallReport }) { return <div className="space-y-3"> <dl className="flex flex-wrap gap-4 text-sm"><div><dt className="text-muted-foreground">Speko charge</dt><dd>{charge(report.costMicroUsd)}</dd></div>{report.durationSeconds !== null && <div><dt className="text-muted-foreground">Duration</dt><dd>{report.durationSeconds} seconds</dd></div>}</dl> <p className="text-xs text-muted-foreground">Agent costs are separate. Recordings remain in Speko.</p> - {report.transcript.length ? <ol aria-label="Call transcript" className="space-y-3">{report.transcript.map(turn => <li key={turn.id} className="min-w-0"><p className="text-xs font-medium text-muted-foreground">{turn.speaker === "caller" ? "You" : "Agent"}{turn.interrupted ? " · interrupted" : ""}</p><p className="whitespace-pre-wrap break-words text-sm">{turn.text}</p></li>)}</ol> + {report.transcript.length ? <ol aria-label="Call transcript" className={cn("space-y-3", ANALYTICS_MASK_CLASS)}>{report.transcript.map(turn => <li key={turn.id} className="min-w-0"><p className="text-xs font-medium text-muted-foreground">{turn.speaker === "caller" ? "You" : "Agent"}{turn.interrupted ? " · interrupted" : ""}</p><p className="whitespace-pre-wrap break-words text-sm">{turn.text}</p></li>)}</ol> : <p className="text-sm text-muted-foreground">{report.status === "unavailable" ? "The transcript is unavailable. Paperclip will retry while Speko finishes the report." : report.status === "pending" ? "The transcript will appear after Speko finishes the call report." : "Speko did not provide a transcript for this call."}</p>} </div>; } diff --git a/ui/src/components/voice/VoiceTranscript.tsx b/ui/src/components/voice/VoiceTranscript.tsx index 66b8b498049..6003ad7d041 100644 --- a/ui/src/components/voice/VoiceTranscript.tsx +++ b/ui/src/components/voice/VoiceTranscript.tsx @@ -1,4 +1,6 @@ import type { VoiceTranscriptEntry } from "@/lib/voice-transcript"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; export interface VoiceTranscriptProps { entries: readonly VoiceTranscriptEntry[]; @@ -11,7 +13,7 @@ export function VoiceTranscript({ entries, agentName, unavailable = false }: Voi if (unavailable) return <p className="text-sm text-muted-foreground">The transcript is unavailable. Your task history is still available.</p>; if (!entries.length) return <p className="text-sm text-muted-foreground">Your conversation will appear here.</p>; return ( - <ol aria-label="Conversation transcript" aria-live="off" className="flex min-w-0 flex-col gap-4"> + <ol aria-label="Conversation transcript" aria-live="off" className={cn("flex min-w-0 flex-col gap-4", ANALYTICS_MASK_CLASS)}> {entries.map((entry) => ( <li key={entry.id} className="flex min-w-0 flex-col gap-1"> <span className="text-xs font-medium text-muted-foreground break-words"> diff --git a/ui/src/features/connections/ConnectionChoiceList.tsx b/ui/src/features/connections/ConnectionChoiceList.tsx index 2aaea7f85c4..b3c318699cf 100644 --- a/ui/src/features/connections/ConnectionChoiceList.tsx +++ b/ui/src/features/connections/ConnectionChoiceList.tsx @@ -1,5 +1,7 @@ import type { ReactNode } from "react"; import { Check, ChevronRight, Loader2 } from "lucide-react"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; /** The account-reuse rows shared by connection setup and agent bindings. */ export function ConnectionChoiceList({ choices, selectedId, pendingId, disabled, onSelect }: { @@ -21,7 +23,7 @@ export function ConnectionChoiceList({ choices, selectedId, pendingId, disabled, > {choice.icon && <span aria-hidden="true" className="shrink-0">{choice.icon}</span>} <span className="min-w-0 flex-1"> - <span className="block font-medium text-foreground">{choice.name}</span> + <span className={cn("block font-medium text-foreground", ANALYTICS_MASK_CLASS)}>{choice.name}</span> <span className="mt-1 block text-xs text-muted-foreground">{choice.description}</span> </span> {pendingId === choice.id ? <Loader2 className="h-4 w-4 shrink-0 animate-spin text-muted-foreground" /> diff --git a/ui/src/features/connections/ConnectionInstructions.tsx b/ui/src/features/connections/ConnectionInstructions.tsx index 562b4065b84..923f93299ae 100644 --- a/ui/src/features/connections/ConnectionInstructions.tsx +++ b/ui/src/features/connections/ConnectionInstructions.tsx @@ -19,6 +19,8 @@ import { Button } from "@/components/ui/button"; import { Textarea } from "@/components/ui/textarea"; import { ToggleSwitch } from "@/components/ui/toggle-switch"; import { InlineBanner } from "@/components/InlineBanner"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; export function ConnectionInstructionsEditor({ provider, template, value, onChange, disabled = false }: { provider: string; @@ -39,7 +41,7 @@ export function ConnectionInstructionsEditor({ provider, template, value, onChan {!value.enabled && <InlineBanner tone="warning">Agents can still use this connection’s tools, but won’t receive these instructions.</InlineBanner>} {editing ? <Textarea aria-label="Instructions text" value={value.text} disabled={disabled} maxLength={CONNECTION_INSTRUCTIONS_MAX_LENGTH} className="min-h-40" onChange={(event) => onChange({ ...value, text: event.target.value })} /> - : <p className="whitespace-pre-wrap text-sm leading-relaxed text-muted-foreground">{value.text}</p>} + : <p className={cn("whitespace-pre-wrap text-sm leading-relaxed text-muted-foreground", ANALYTICS_MASK_CLASS)}>{value.text}</p>} {!value.text.trim() && <p role="alert" className="text-sm text-destructive">Enter instructions.</p>} <div className="flex items-center gap-3"> <Button variant="ghost" size="sm" disabled={disabled} onClick={() => setEditing(!editing)}>{editing ? "Done editing" : "Edit instructions"}</Button> @@ -92,10 +94,10 @@ export function AgentConnectionInstructions({ companyId, agentId }: { companyId: const app = getConnectableAppDefinition(String(config.sourceTemplateKey ?? "")); const context = connectionInstructionContext(app, config); return <div key={connection.id} className="space-y-3 rounded-lg border border-border p-4"> - <Link className="text-sm font-medium underline underline-offset-2" to={`/apps/${connection.id}/permissions`}>{connection.name}</Link> + <Link className={cn("text-sm font-medium underline underline-offset-2", ANALYTICS_MASK_CLASS)} to={`/apps/${connection.id}/permissions`}>{connection.name}</Link> {!connection.agentInstructions!.enabled && <InlineBanner tone="warning">These instructions are turned off for this connection.</InlineBanner>} {context === null ? <InlineBanner tone="warning">Complete this connection’s configuration before agents receive its instructions.</InlineBanner> - : <p className="whitespace-pre-wrap text-sm leading-relaxed text-muted-foreground">{connection.agentInstructions!.text}</p>} + : <p className={cn("whitespace-pre-wrap text-sm leading-relaxed text-muted-foreground", ANALYTICS_MASK_CLASS)}>{connection.agentInstructions!.text}</p>} </div>; })} </section>; diff --git a/ui/src/features/connections/ConnectionIntentInteractionBody.tsx b/ui/src/features/connections/ConnectionIntentInteractionBody.tsx index 91f1ca7f874..401febb1f52 100644 --- a/ui/src/features/connections/ConnectionIntentInteractionBody.tsx +++ b/ui/src/features/connections/ConnectionIntentInteractionBody.tsx @@ -37,6 +37,8 @@ import { import { DecisionCardFooter } from "@/components/DecisionCardFooter"; import { NeedsYouPanel, NeedsYouPanelNote, NeedsYouPanelRow } from "@/components/coordinator/NeedsYouCardKit"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; export interface ConnectionIntentInteractionBodyProps { footerSlot?: ReactNode; @@ -364,7 +366,7 @@ export function ConnectionIntentInteractionBody({ const busy = completeMutation.isPending || declineMutation.isPending; const askFirst = accessRequest.tools.filter(tool => tool.permission === "ask_first").length; return <div id={focusTargetId} ref={focusTargetRef} tabIndex={-1} data-testid="connection-intent-focus-target"> - <div data-testid="connection-intent-access-request" className="space-y-4"> + <div data-testid="connection-intent-access-request" className={cn("space-y-4", ANALYTICS_MASK_CLASS)}> <NeedsYouPanel> {artifactRow} <NeedsYouPanelRow icon={serviceLogo} title={`${interaction.payload.serviceName} · ${accessRequest.connectionName}`} @@ -399,7 +401,7 @@ export function ConnectionIntentInteractionBody({ <div className="flex items-center gap-3"> <AgentAvatar agent={agentQuery.data ?? { id: interaction.payload.requestingAgentId, name: interaction.payload.requestingAgentName }} size={32} label={interaction.payload.requestingAgentName} /> <div className="min-w-0 flex-1"> - <p className="text-sm font-medium text-foreground">Grant {interaction.payload.requestingAgentName} access to “{accessRequest.connectionName}”?</p> + <p className={cn("text-sm font-medium text-foreground", ANALYTICS_MASK_CLASS)}>Grant {interaction.payload.requestingAgentName} access to “{accessRequest.connectionName}”?</p> </div> <AppLogo name={interaction.payload.serviceName} logoUrl={interaction.payload.serviceLogoUrl} darkLogoUrl={interaction.payload.serviceDarkLogoUrl} size={32} /> </div> @@ -460,7 +462,7 @@ export function ConnectionIntentInteractionBody({ </Button> </div> : selectedReady ? <div className="space-y-3"> - <p className="text-sm">{repair.connection.name} is ready.</p> + <p className={cn("text-sm", ANALYTICS_MASK_CLASS)}>{repair.connection.name} is ready.</p> <Button disabled={completeMutation.isPending} onClick={() => completeMutation.mutate(repair.connection.id)}> {completeMutation.isPending ? "Continuing…" : "Continue task"} </Button> @@ -485,7 +487,7 @@ export function ConnectionIntentInteractionBody({ allAgents={false} onComplete={(result) => selectAiAccountMutation.mutate({ ...result, generation })} onCancel={() => { closeSetup(); returnFocusToCard(); }} - /> : <p role="status" className="text-sm text-muted-foreground"> + /> : <p role="status" className={cn("text-sm text-muted-foreground", ANALYTICS_MASK_CLASS)}> {repair.connection.ownership === "personal" ? `${repair.connection.ownerName ?? "The account owner"} must reconnect ${repair.connection.name}.` : `The account owner must reconnect ${repair.connection.name}.`} {" "}You can continue here once it is restored. </p> @@ -604,7 +606,7 @@ export function ConnectionIntentInteractionBody({ </Button> </DialogTrigger> <DialogContent - className="max-h-(--sz-85vh) overflow-y-auto sm:max-w-3xl" + className={cn("max-h-(--sz-85vh) overflow-y-auto sm:max-w-3xl", ANALYTICS_MASK_CLASS)} showCloseButton={false} onCloseAutoFocus={(event) => { event.preventDefault(); diff --git a/ui/src/features/connections/GenericMcpConnectStep.machine.test.tsx b/ui/src/features/connections/GenericMcpConnectStep.machine.test.tsx index 3304705a9fd..0103b16ff05 100644 --- a/ui/src/features/connections/GenericMcpConnectStep.machine.test.tsx +++ b/ui/src/features/connections/GenericMcpConnectStep.machine.test.tsx @@ -4,6 +4,7 @@ import { createRoot, type Root } from "react-dom/client"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { newCustomHeaderRow } from "@/pages/apps/generic-mcp-connect"; import { GenericMcpConnectStep } from "./GenericMcpConnectStep"; +import { isBlockedFromReplay } from "@/lib/analytics/replay-recording.test-utils"; vi.mock("@/api/tools", () => ({ toolsApi: {} })); vi.mock("@/pages/apps/AppLogo", () => ({ AppLogo: () => null })); @@ -67,3 +68,25 @@ describe("Machine sign-in in the custom server step", () => { expect(container.textContent).not.toContain("Machine sign-in"); }); }); + +describe("Session replay in the custom server step", () => { + it("blocks the server link, which can carry an API key, from session replay", async () => { + const container = document.createElement("div"); + document.body.append(container); + const root = createRoot(container); + await act(async () => { + root.render( + <GenericMcpConnectStep + link="https://mcp.example/mcp?api_key=mcpk_Zt4wR8pLq2" name="" needsKey={false} keyValue="" onKeyChange={() => undefined} + authMode="auto" onAuthModeChange={() => undefined} headers={[newCustomHeaderRow()]} onHeadersChange={() => undefined} + oauthClientId="" onOAuthClientIdChange={() => undefined} oauthClientSecret="" onOAuthClientSecretChange={() => undefined} + advancedOpen={false} onAdvancedOpenChange={() => undefined} guidance={null} submitting={false} + onBack={() => undefined} onConnect={() => undefined} machineSignIn={null} + />, + ); + }); + expect(isBlockedFromReplay("mcpk_Zt4wR8pLq2", container)).toBe(true); + act(() => root.unmount()); + container.remove(); + }); +}); diff --git a/ui/src/features/connections/GenericMcpConnectStep.tsx b/ui/src/features/connections/GenericMcpConnectStep.tsx index 09e2e1eddf8..e36d99de2b0 100644 --- a/ui/src/features/connections/GenericMcpConnectStep.tsx +++ b/ui/src/features/connections/GenericMcpConnectStep.tsx @@ -6,7 +6,9 @@ import { Button } from "@/components/ui/button"; import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"; import { Input } from "@/components/ui/input"; import { RadioCard } from "@/components/ui/radio-card"; +import { ANALYTICS_NO_CAPTURE_CLASS } from "@/lib/analytics/privacy"; import { redactUrlSecrets } from "@/lib/redact-url-secrets"; +import { cn } from "@/lib/utils"; import { AppLogo } from "@/pages/apps/AppLogo"; import { MachineSignInSetup } from "./MachineSignInSetup"; import { @@ -330,7 +332,7 @@ export function GenericMcpConnectStep({ return ( <div className="mx-auto max-w-xl"> <div className="flex flex-col gap-6"> - <p className="min-w-0 truncate font-mono text-sm text-muted-foreground" title={displayedLink}>{displayedLink}</p> + <p className={cn("min-w-0 truncate font-mono text-sm text-muted-foreground", ANALYTICS_NO_CAPTURE_CLASS)} title={displayedLink}>{displayedLink}</p> {matchedEntry && onUseMatchedEntry ? ( <div className="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border bg-muted/40 px-3 py-2"> diff --git a/ui/src/features/connections/GoogleWorkspaceServices.tsx b/ui/src/features/connections/GoogleWorkspaceServices.tsx index ef17b7a1533..e3c3ddf00f9 100644 --- a/ui/src/features/connections/GoogleWorkspaceServices.tsx +++ b/ui/src/features/connections/GoogleWorkspaceServices.tsx @@ -9,6 +9,8 @@ import { NativeSelect } from "@/components/ui/select"; import { ToggleSwitch } from "@/components/ui/toggle-switch"; import { AppLogo } from "@/pages/apps/AppLogo"; import { GOOGLE_WORKSPACE_PRIVACY_POLICY_URL, googleWorkspaceDataUseDisclosure } from "./googleWorkspaceDisclosure"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; export function GoogleWorkspaceServiceFields({ value, onChange }: { value: GoogleWorkspaceServiceSelection; @@ -70,7 +72,7 @@ export function GoogleWorkspaceServicesDialog(props: DialogProps) { const pendingRequests = oauth?.pendingWorkspaceServiceRequests; const grants = useQuery({ queryKey: ["workspace-service-consent", existing?.id], queryFn: () => toolsApi.listConnectionGrants(existing!.id), enabled: Boolean(existing) }); const grantsView = useQueryView(grants); - if (existing && !grants.data) return <Dialog open onOpenChange={open => { if (!open) props.onCancel(); }}><DialogContent> + if (existing && !grants.data) return <Dialog open onOpenChange={open => { if (!open) props.onCancel(); }}><DialogContent className={ANALYTICS_MASK_CLASS}> <DialogTitle>Connect Google Workspace</DialogTitle><DialogDescription>{(grantsView.kind === "error") ? "Could not load your saved service access. Your connection has not changed." : "Loading your saved service access…"}</DialogDescription> <footer className="flex items-center justify-between gap-3"><Button variant="ghost" onClick={() => props.onCancel()}>Cancel</Button>{(grantsView.kind === "error") && <Button onClick={() => void grants.refetch()}>Try again</Button>}</footer> </DialogContent></Dialog>; @@ -121,7 +123,7 @@ function ServicePicker({ onContinue, onCancel, initial = GOOGLE_WORKSPACE_DEFAUL const [selection, setSelection] = useState(initial); const empty = Object.keys(selection).length === 0; return <Dialog open onOpenChange={open => { if (!open) onCancel(selection); }}> - <DialogContent className="max-h-(--sz-85vh) overflow-y-auto sm:max-w-3xl"> + <DialogContent className={cn("max-h-(--sz-85vh) overflow-y-auto sm:max-w-3xl", ANALYTICS_MASK_CLASS)}> <DialogHeader className="text-left"> <div className="flex items-center gap-3"><AppLogo name="Google Workspace" brandKey="google" size={40} /><DialogTitle>Connect Google Workspace</DialogTitle></div> <DialogDescription className="sr-only">Choose the Google services to connect.</DialogDescription> diff --git a/ui/src/features/connections/remote-mcp/RemoteMcpConnectionSetup.tsx b/ui/src/features/connections/remote-mcp/RemoteMcpConnectionSetup.tsx index d2bc936023e..645a6b3775f 100644 --- a/ui/src/features/connections/remote-mcp/RemoteMcpConnectionSetup.tsx +++ b/ui/src/features/connections/remote-mcp/RemoteMcpConnectionSetup.tsx @@ -17,6 +17,8 @@ import { } from "../ConnectionSetupFlow"; import type { RemoteMcpProvider } from "./providers"; import type { RemoteMcpSetupActions, RemoteMcpSetupState } from "./types"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; /** * PAP-659 C0: the connect path is one screen. `access` is still a real screen, @@ -31,7 +33,7 @@ function FieldHelp({ label, children }: { label: string; children: ReactNode }) const [open, setOpen] = useState(false); return <Tooltip open={open} onOpenChange={setOpen}> <TooltipTrigger asChild><button type="button" aria-label={`Help with ${label}`} onClick={() => setOpen(!open)} className="rounded-sm text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"><HelpCircle className="size-4" /></button></TooltipTrigger> - <TooltipContent className="max-w-xs">{children}</TooltipContent> + <TooltipContent className={cn("max-w-xs", ANALYTICS_MASK_CLASS)}>{children}</TooltipContent> </Tooltip>; } diff --git a/ui/src/features/connections/remote-mcp/RemoteMcpManagement.tsx b/ui/src/features/connections/remote-mcp/RemoteMcpManagement.tsx index 87861307db7..f4ffb968df6 100644 --- a/ui/src/features/connections/remote-mcp/RemoteMcpManagement.tsx +++ b/ui/src/features/connections/remote-mcp/RemoteMcpManagement.tsx @@ -1,6 +1,7 @@ import { useState } from "react"; import { Button } from "@/components/ui/button"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from "@/components/ui/alert-dialog"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; /** Shared by the saved connection and its interactive review stories. */ export function RemoteMcpManagement({ providerName, connected = true, canReconnect = true, canDisconnect = true, busy = false, onReconnect, onManage, onDisconnect }: { @@ -21,7 +22,7 @@ export function RemoteMcpManagement({ providerName, connected = true, canReconne <Button variant="outline" onClick={onManage}>Manage in {providerName}</Button> {connected && canDisconnect && <AlertDialog open={confirming} onOpenChange={(open) => { if (!busy) setConfirming(open); }}> <AlertDialogTrigger asChild><Button variant="ghost" className="text-destructive">Disconnect</Button></AlertDialogTrigger> - <AlertDialogContent> + <AlertDialogContent className={ANALYTICS_MASK_CLASS}> <AlertDialogHeader> <AlertDialogTitle>Disconnect {providerName}?</AlertDialogTitle> <AlertDialogDescription>Delete this connection’s saved credentials and stop further calls through Paperclip. Other connections are unaffected. Actions already sent to the provider may still complete. Connecting again requires a new sign-in or key.</AlertDialogDescription> diff --git a/ui/src/lib/analytics/privacy.test.ts b/ui/src/lib/analytics/privacy.test.ts index f8d116f8c0b..041f7015437 100644 --- a/ui/src/lib/analytics/privacy.test.ts +++ b/ui/src/lib/analytics/privacy.test.ts @@ -3,10 +3,9 @@ import { afterEach, describe, expect, it } from "vitest"; import { ANALYTICS_MASK_CLASS, + ANALYTICS_MASK_TEXT_SELECTOR, ANALYTICS_NO_CAPTURE_CLASS, - ANALYTICS_UNMASK_ATTRIBUTE, maskReplayAttribute, - maskReplayText, redactAnalyticsUrl, } from "./privacy"; @@ -15,35 +14,26 @@ function render(html: string) { return (id: string) => document.getElementById(id) as HTMLElement; } -describe("session replay text masking", () => { +describe("session replay text mask selector", () => { afterEach(() => { document.body.innerHTML = ""; }); - it("masks text on any surface that nobody marked", () => { - const el = render(`<main><p id="p">Quarterly revenue plan</p></main>`); - expect(maskReplayText("Quarterly revenue plan", el("p"))).toBe("********* ******* ****"); - }); - - it("masks text when the element is unknown", () => { - expect(maskReplayText("hello", null)).toBe("*****"); - expect(maskReplayText("hello")).toBe("*****"); - }); - - it("shows text inside opted-in chrome", () => { - const el = render(`<button ${ANALYTICS_UNMASK_ATTRIBUTE}><span id="s">New task</span></button>`); - expect(maskReplayText("New task", el("s"))).toBe("New task"); - }); - - it("keeps customer content masked even inside opted-in chrome", () => { + it("matches only text inside customer content, secrets and editable content", () => { const el = render( - `<nav ${ANALYTICS_UNMASK_ATTRIBUTE}><div class="${ANALYTICS_MASK_CLASS}"><p id="c">Customer secret</p></div>` + `<nav><a id="n">Tasks</a></nav><main><p id="p">Quarterly revenue plan</p>` + + `<div class="${ANALYTICS_MASK_CLASS}"><p id="c">Customer secret</p></div>` + `<div contenteditable="true"><p id="e">Draft</p></div>` - + `<div class="${ANALYTICS_NO_CAPTURE_CLASS}"><span id="k">sk-123</span></div></nav>`, + + `<div contenteditable="false"><p id="r">Read only</p></div>` + + `<div class="${ANALYTICS_NO_CAPTURE_CLASS}"><span id="k">sk-123</span></div></main>`, ); - expect(maskReplayText("Customer secret", el("c"))).toBe("******** ******"); - expect(maskReplayText("Draft", el("e"))).toBe("*****"); - expect(maskReplayText("sk-123", el("k"))).toBe("******"); + const masked = (id: string) => el(id).closest(ANALYTICS_MASK_TEXT_SELECTOR) !== null; + expect(masked("n")).toBe(false); + expect(masked("p")).toBe(false); + expect(masked("r")).toBe(false); + expect(masked("c")).toBe(true); + expect(masked("e")).toBe(true); + expect(masked("k")).toBe(true); }); }); @@ -54,7 +44,7 @@ describe("session replay attribute masking", () => { it("masks free-text attributes that carry customer data, such as an organization switcher label", () => { const el = render( - `<button ${ANALYTICS_UNMASK_ATTRIBUTE} id="b" aria-label="Open Verify Co organization switcher" title="Verify Co">` + `<button id="b" aria-label="Open Verify Co organization switcher" title="Verify Co">` + `<span class="${ANALYTICS_MASK_CLASS}" id="n" title="Verify Co">Verify Co</span></button>` + `<span id="t" title="Customer task title">Customer task title</span>` + `<img id="i" src="/api/attachments/1" alt="Quarterly plan">`, @@ -75,8 +65,8 @@ describe("session replay attribute masking", () => { expect(maskReplayAttribute("id", "main-content", el("t"))).toBe("main-content"); }); - it("keeps layout attributes and masks labels even on opted-in chrome", () => { - const el = render(`<button ${ANALYTICS_UNMASK_ATTRIBUTE} id="b" aria-label="New task" class="btn" data-state="open">New task</button>`); + it("keeps layout attributes and masks labels on chrome", () => { + const el = render(`<button id="b" aria-label="New task" class="btn" data-state="open">New task</button>`); expect(maskReplayAttribute("aria-label", "New task", el("b"))).toBe("*** ****"); expect(maskReplayAttribute("class", "btn", el("b"))).toBe("btn"); expect(maskReplayAttribute("data-state", "open", el("b"))).toBe("open"); diff --git a/ui/src/lib/analytics/privacy.ts b/ui/src/lib/analytics/privacy.ts index 5cc8c893a76..8232d98ce81 100644 --- a/ui/src/lib/analytics/privacy.ts +++ b/ui/src/lib/analytics/privacy.ts @@ -1,11 +1,10 @@ // Shared privacy markers for browser product analytics (PostHog). // -// Session replay masks ALL text and ALL input values by default. Only UI -// chrome that opts in shows its text: sidebar items with a fixed label, and -// any shared `Button`, `Label`, `TabsTrigger` or `EmptyState` whose caller -// passes `analyticsChrome` because its text is fixed product copy. A surface nobody marked stays -// masked. Autocapture never records element text or attribute values at all -// (see `product-analytics.ts`). +// Session replay shows text by default and masks ALL input values. Text is +// masked only inside customer content marked with `ANALYTICS_MASK_CLASS`, +// inside secrets marked with `ANALYTICS_NO_CAPTURE_CLASS` (blocked entirely) +// and inside editable content. Autocapture never records element text or +// attribute values at all (see `product-analytics.ts`). // // Apply these markers instead of PostHog class names, so `product-analytics.ts` // stays the one place that knows about PostHog. They have no effect when @@ -13,17 +12,9 @@ import { redactUrlSecrets } from "@/lib/redact-url-secrets"; -export const ANALYTICS_UNMASK_ATTRIBUTE = "data-analytics-unmask"; - /** - * Spread on shared UI chrome whose text is product copy, never customer - * content: `<button {...ANALYTICS_UNMASK_PROPS}>`. - */ -export const ANALYTICS_UNMASK_PROPS = { [ANALYTICS_UNMASK_ATTRIBUTE]: "" } as const; - -/** - * Customer content: task and issue bodies, comments, chat messages, documents - * and artifacts. Its text stays masked even inside unmasked chrome, and + * Customer content: task and issue bodies, comments, chat messages, documents, + * artifacts and connected-account data. Session replay masks its text, and * autocapture records nothing from inside it. */ export const ANALYTICS_MASK_CLASS = "ph-mask ph-sensitive"; @@ -35,23 +26,11 @@ export const ANALYTICS_MASK_CLASS = "ph-mask ph-sensitive"; */ export const ANALYTICS_NO_CAPTURE_CLASS = "ph-no-capture"; -/** Session replay sends every text node through `maskReplayText`. */ -export const ANALYTICS_MASK_TEXT_SELECTOR = "*"; - -const FORCED_MASK_SELECTOR = ".ph-mask, .ph-no-capture, [contenteditable]:not([contenteditable=\"false\"])"; -const UNMASK_SELECTOR = `[${ANALYTICS_UNMASK_ATTRIBUTE}]`; - -/** True only for text inside opted-in chrome and outside customer content. */ -export function isReplayTextRevealed(element: Element | null | undefined): boolean { - if (!element || typeof element.closest !== "function") return false; - if (element.closest(FORCED_MASK_SELECTOR)) return false; - return element.closest(UNMASK_SELECTOR) !== null; -} - -/** Session replay `maskTextFn`: keeps whitespace so the layout stays readable. */ -export function maskReplayText(text: string, element?: HTMLElement | null): string { - return isReplayTextRevealed(element) ? text : text.replace(/\S/g, "*"); -} +/** Session replay masks text only inside these markers. */ +export const ANALYTICS_MASK_TEXT_SELECTOR = [ + ...ANALYTICS_MASK_CLASS.split(" "), + ANALYTICS_NO_CAPTURE_CLASS, +].map((name) => `.${name}`).concat("[contenteditable]:not([contenteditable=\"false\"])").join(", "); /** * Attributes that only describe layout, state or structure. Every other @@ -67,7 +46,7 @@ const LAYOUT_ATTRIBUTES = new Set([ "aria-hidden", "aria-expanded", "aria-selected", "aria-checked", "aria-current", "aria-disabled", "aria-orientation", "aria-haspopup", "aria-modal", "aria-pressed", "aria-invalid", "aria-live", "aria-busy", "data-slot", "data-state", "data-side", "data-align", "data-orientation", "data-variant", - "data-size", "data-disabled", "data-highlighted", "data-placeholder", ANALYTICS_UNMASK_ATTRIBUTE, + "data-size", "data-disabled", "data-highlighted", "data-placeholder", ]); /** Fixed IDs that page CSS targets (`#root`, `#main-content`); never customer data. */ @@ -76,9 +55,9 @@ const LAYOUT_IDS = new Set(["root", "main-content", "properties-pane-header-slot /** * Session replay `maskAttributeFn`. Deny by default: only layout attributes, * rrweb's own metadata, stylesheets and links outside customer content keep - * their values. Free-text attributes stay masked even on opted-in chrome, - * because labels such as `aria-label` often name customer data (for example - * the organization switcher's "Open <name> switcher"). + * their values. Free-text attributes stay masked everywhere, because labels + * such as `aria-label` often name customer data (for example the + * organization switcher's "Open <name> switcher"). */ export function maskReplayAttribute(name: string, value: string, element?: Element | null): string { const key = name.toLowerCase(); diff --git a/ui/src/lib/analytics/product-analytics.test.ts b/ui/src/lib/analytics/product-analytics.test.ts index 18c89317093..03dd8d2c13c 100644 --- a/ui/src/lib/analytics/product-analytics.test.ts +++ b/ui/src/lib/analytics/product-analytics.test.ts @@ -144,9 +144,9 @@ describe("product analytics", () => { tracing_headers: ["acme.paperclip.app"], session_recording: { maskAllInputs: true, blockClass: "ph-no-capture" }, }); - // Replay masks every text node; maskTextFn reveals only opted-in chrome. - expect(options.session_recording?.maskTextSelector).toBe("*"); - expect(options.session_recording?.maskTextFn).toBeTypeOf("function"); + // Replay masks text only inside customer content, secrets and editable content. + expect(options.session_recording?.maskTextSelector).toBe(".ph-mask, .ph-sensitive, .ph-no-capture, [contenteditable]:not([contenteditable=\"false\"])"); + expect(options.session_recording).not.toHaveProperty("maskTextFn"); expect(options.session_recording?.maskAttributeFn).toBeTypeOf("function"); expect(options).toMatchObject({ disable_surveys: true, disable_product_tours: true, disable_web_experiments: true, disable_conversations: true }); expect(buildPostHogInitOptions({ ...config, replayEnabled: false }, "x").disable_session_recording).toBe(true); diff --git a/ui/src/lib/analytics/product-analytics.ts b/ui/src/lib/analytics/product-analytics.ts index d82cae0c206..f77e5fd955c 100644 --- a/ui/src/lib/analytics/product-analytics.ts +++ b/ui/src/lib/analytics/product-analytics.ts @@ -27,7 +27,6 @@ import { ANALYTICS_MASK_TEXT_SELECTOR, ANALYTICS_NO_CAPTURE_CLASS, maskReplayAttribute, - maskReplayText, redactAnalyticsUrl, } from "./privacy"; @@ -64,7 +63,6 @@ export type PostHogInitOptions = { session_recording: { maskAllInputs: boolean; maskTextSelector: string; - maskTextFn: (text: string, element?: HTMLElement | null) => string; maskAttributeFn: (name: string, value: string, element?: Element | null) => string; blockClass: string; }; @@ -171,10 +169,9 @@ export function buildPostHogInitOptions( enable_heatmaps: true, disable_session_recording: !config.replayEnabled, session_recording: { - // Mask everything; only opted-in UI chrome shows its text (privacy.ts). + // Text shows; only marked customer content and secrets mask (privacy.ts). maskAllInputs: true, maskTextSelector: ANALYTICS_MASK_TEXT_SELECTOR, - maskTextFn: maskReplayText, // Attributes too (title, aria-label, alt, src, ...): deny by default. maskAttributeFn: maskReplayAttribute, blockClass: ANALYTICS_NO_CAPTURE_CLASS, diff --git a/ui/src/lib/analytics/replay-masking.test.tsx b/ui/src/lib/analytics/replay-masking.test.tsx new file mode 100644 index 00000000000..2aac3758a46 --- /dev/null +++ b/ui/src/lib/analytics/replay-masking.test.tsx @@ -0,0 +1,393 @@ +// @vitest-environment jsdom + +import { readdirSync, readFileSync, statSync } from "node:fs"; +import { join } from "node:path"; +import { act } from "react"; +import { createRoot } from "react-dom/client"; +import { renderToStaticMarkup } from "react-dom/server"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import type { DocumentRevision } from "@paperclipai/shared"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { DocumentDiffModal } from "@/components/DocumentDiffModal"; +import { RunInvocationCard } from "@/components/run-log/RunDetails"; +import { ChatConversationList } from "@/pages/apps/chat/ChatConversationList"; +import { VoiceTranscript } from "@/components/voice/VoiceTranscript"; +import { RunTranscriptView } from "@/components/transcript/RunTranscriptView"; +import { buildPostHogInitOptions } from "./product-analytics"; +import { ANALYTICS_MASK_CLASS, ANALYTICS_MASK_TEXT_SELECTOR, ANALYTICS_NO_CAPTURE_CLASS } from "./privacy"; +import { isBlockedFromReplay, replayLeaks } from "./replay-recording.test-utils"; + +vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + +const UI_SRC = join(import.meta.dirname, "../.."); + +const options = buildPostHogInitOptions( + { token: "t", apiHost: "/_ph", uiHost: null, environment: "production", stackId: "s", replayEnabled: true }, + "acme.paperclip.app", +); + +function recordedText(node: Text): string { + const parent = node.parentElement; + const masked = parent?.closest(options.session_recording.maskTextSelector) != null; + return masked ? node.data.replace(/\S/g, "*") : node.data; +} + +function recordedTextOf(html: string, text: string): string { + document.body.innerHTML = html; + const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT); + while (walker.nextNode()) { + const node = walker.currentNode as Text; + if (node.data.includes(text)) return recordedText(node); + } + throw new Error(`text not rendered: ${text}`); +} + +const MASKED_SURFACES: Array<{ file: string; content: string }> = [ + { file: "components/LinkPreview.tsx", content: "{preview.title}" }, + { file: "components/LinkPreview.tsx", content: "{target.canonicalUrl}" }, + { file: "components/IssueLinkQuicklook.tsx", content: "data-slot=\"task-preview-description\"" }, + { file: "components/ExternalObjectPill.tsx", content: "{valueLabel}" }, + { file: "components/ExternalObjectPill.tsx", content: "{labelText}" }, + { file: "components/issue-properties/external-object-rows.tsx", content: "{displayKey}</span>" }, + { file: "components/issue-properties/external-object-rows.tsx", content: "{value}</span>" }, + { file: "components/IssueRelatedWorkPanel.tsx", content: "{pill.displayTitle}" }, + { file: "components/EmailMessageCard.tsx", content: "{message.subject" }, + { file: "components/EmailTaskActivity.tsx", content: "{p.request.subject" }, + { file: "pages/apps/Browse.tsx", content: "{accountName}\n </button>" }, + { file: "pages/apps/Browse.tsx", content: "{connectionToRemove?.accountName" }, + { file: "pages/apps/Browse.tsx", content: "“{connection.name}”" }, + { file: "pages/apps/Connections.tsx", content: ">{row.displayName}</span>" }, + { file: "pages/apps/AppDetail.tsx", content: "<h1 className={cn(\"text-xl font-semibold\", ANALYTICS_MASK_CLASS)}>{appName}" }, + { file: "pages/apps/AppDetail.tsx", content: "<h1 className={cn(\"truncate text-xl font-bold\", ANALYTICS_MASK_CLASS)}>{appName}" }, + { file: "components/AppConnectionSidebar.tsx", content: "{appName}</span>" }, + { file: "features/connections/ConnectionChoiceList.tsx", content: ">{choice.name}</span>" }, + { file: "features/connections/ConnectionIntentInteractionBody.tsx", content: "${accessRequest.connectionName}" }, + { file: "features/connections/ConnectionIntentInteractionBody.tsx", content: "“{accessRequest.connectionName}”" }, + { file: "features/connections/ConnectionIntentInteractionBody.tsx", content: "{repair.connection.name} is ready." }, + { file: "features/connections/ConnectionIntentInteractionBody.tsx", content: "must reconnect ${repair.connection.name}" }, + { file: "pages/apps/app-detail/IdentitiesSection.tsx", content: "<span className={ANALYTICS_MASK_CLASS}>@{github.login}</span>" }, + { file: "pages/apps/app-detail/IdentitiesSection.tsx", content: "@{github.login}\n" }, + { file: "pages/apps/app-detail/IdentitiesSection.tsx", content: "<Identity name={connectedName}" }, + { file: "pages/apps/app-detail/IdentitiesSection.tsx", content: "<AlertDialogTitle className={ANALYTICS_MASK_CLASS}>{title}" }, + { file: "pages/apps/AggregatorAppManager.tsx", content: "{account.alias ||" }, + { file: "pages/apps/AggregatorAppManager.tsx", content: "“{connection.name}”" }, + { file: "pages/apps/ComposioAppManager.tsx", content: "{account.alias ||" }, + { file: "pages/apps/ComposioAppManager.tsx", content: "“{connection.name}”" }, + { file: "pages/apps/TailscaleConnector.tsx", content: "{connected.map(connection => connection.name)" }, + { file: "pages/apps/TailscaleConnector.tsx", content: "{connection.name}</p>" }, + { file: "pages/apps/TailscaleConnector.tsx", content: "<span className={ANALYTICS_MASK_CLASS}>{connection.name}</span></Button>\n" }, + { file: "pages/apps/TailscaleConnector.tsx", content: "<span className={ANALYTICS_MASK_CLASS}>{connection.name}</span></Button>}" }, + { file: "pages/apps/ArcadeDiscoverySetup.tsx", content: "“{connection.name}”" }, + { file: "pages/apps/ExecutorManagementSetup.tsx", content: "“{connection.name}”" }, + { file: "pages/apps/AggregatorConnectDialog.tsx", content: "{existing.map(" }, + { file: "pages/apps/app-detail/ConnectedAggregatorApps.tsx", content: "{accounts[0].alias}" }, + { file: "pages/apps/chat/GitHubBotConfiguration.tsx", content: "@{person.login}</p>" }, + { file: "pages/apps/chat/GitHubBotConfiguration.tsx", content: "`@${candidate.login} is already listed" }, + { file: "pages/apps/chat/GitHubChatSetup.tsx", content: "{legacyIdentity?.login}" }, + { file: "pages/apps/chat/GitHubChatSetup.tsx", content: "{state.identity.login}" }, + { file: "pages/apps/chat/GitHubChatSetup.tsx", content: "{account.login ?? account.name}" }, + { file: "pages/apps/chat/GitHubChatSetup.tsx", content: "{legacyIdentity.login}" }, + { file: "pages/apps/chat/GitHubChatSetup.tsx", content: "{knownOrganizations.map(" }, + { file: "pages/AgentDetail.tsx", content: "{person?.user?.name ?? person?.user?.email" }, + { file: "pages/AgentDetail.tsx", content: "{responsibleUserName ?? responsibleUserLabel(null)}" }, + { file: "pages/AgentToolsTab.tsx", content: "{connection.name}</span>" }, + { file: "pages/AgentToolsTab.tsx", content: "{connectionNameById.get(tool.connectionId) ?? \"—\"}" }, + { file: "pages/tools/connection-dialogs.tsx", content: "<span className={ANALYTICS_MASK_CLASS}>{connection.name}</span></DialogTitle>" }, + { file: "pages/tools/AuditTab.tsx", content: "{connectionName}\n" }, + { file: "pages/tools/profiles/ProfileDetail.tsx", content: "{tool.applicationName ?? tool.connectionName" }, + { file: "features/connections/ConnectionInstructions.tsx", content: "{connection.name}</Link>" }, + { file: "components/decision-models/DecisionHistory.tsx", content: "{row.connectionName ??" }, + { file: "components/IssueThreadInteractionCard.tsx", content: "<span className={ANALYTICS_MASK_CLASS}>{connectionName}</span>" }, + { file: "components/ai-connections/AiConnectionField.tsx", content: "For you: ${pendingAccount" }, + { file: "components/ai-connections/AiConnectionField.tsx", content: "{compatiblePools.map(" }, + { file: "components/ai-connections/AiConnectionPoolConnector.tsx", content: "{account?.name ?? \"Connection unavailable\"}" }, + { file: "components/ai-connections/AiConnectionPoolConnector.tsx", content: "{account.name}</span>" }, + { file: "components/ai-connections/AiConnectionPoolConnector.tsx", content: "Remove {draft.name}?" }, + { file: "components/TailscaleSshMachine.tsx", content: "{connected.map(connection => <option" }, + { file: "features/connections/ConnectionInstructions.tsx", content: "{value.text}</p>" }, + { file: "features/connections/ConnectionInstructions.tsx", content: "{connection.agentInstructions!.text}</p>" }, + { file: "pages/AgentDetail.tsx", content: "{run.stderrExcerpt}</pre>" }, + { file: "pages/AgentDetail.tsx", content: "{run.stdoutExcerpt}</pre>" }, + { file: "pages/ExecutionWorkspaceDetail.tsx", content: "{operation.stderrExcerpt}</div>" }, + { file: "pages/ExecutionWorkspaceDetail.tsx", content: "{operation.stdoutExcerpt}</div>" }, + { file: "components/RunnerInspector.tsx", content: "<Search className=\"absolute left-2.5" }, + { file: "pages/apps/chat/GitHubConnectionComplete.tsx", content: "{endpoint.providerAccountLabel}\n" }, + { file: "components/chat/AgentChannelsPanel.tsx", content: "{endpoint.botLabel ??" }, + { file: "pages/apps/Connections.tsx", content: "<table className=\"w-full text-sm\">" }, + { file: "components/skill-studio/SkillSourceConnectionRepair.tsx", content: "<RadioCardGroup ariaLabel=\"GitHub connection\"" }, + { file: "pages/apps/app-detail/IdentitiesSection.tsx", content: "{grantAccountLabel(grant)}" }, + { file: "pages/apps/chat/slack/ManagedSlackSetup.tsx", content: "{workspaces[0]!.workspaceName}" }, + { file: "pages/apps/chat/slack/ManagedSlackSetup.tsx", content: "<SelectValue" }, + { file: "pages/apps/chat/slack/ManagedSlackSetup.tsx", content: "{workspace.workspaceName}" }, + { file: "pages/apps/chat/ChatEndpointDetail.tsx", content: "{resource.label}" }, + { file: "pages/apps/chat/ChatEndpointDetail.tsx", content: "{link.paperclipUserLabel ?? link.externalLabel}</p>" }, + { file: "pages/apps/chat/ChatConversationList.tsx", content: "{conversationDestination(row, provider)}" }, + { file: "pages/apps/chat/ChatConversationList.tsx", content: "{row.externalLabel}" }, + { file: "pages/apps/chat/ChatIdentityConfirm.tsx", content: "Future messages from {identity.externalLabel}" }, + { file: "pages/apps/chat/ChatIdentityConfirm.tsx", content: "{identity.externalDetail ?" }, + { file: "pages/apps/chat/SlackIdentityStep.tsx", content: "{identity.externalLabel}</p>" }, + { file: "components/AccountQuotaPanels.tsx", content: "{account.accountLabel ?? \"Subscription account\"}" }, + { file: "components/ai-connections/AiConnectionAccountDetails.tsx", content: "{accountLabel ?? \"Not available\"}" }, + { file: "components/ai-connections/AiConnectionAccountDetails.tsx", content: "{identity.data?.organizationLabel ??" }, + { file: "components/ai-connections/AiConnectionAccountControls.tsx", content: "` · ${account.accountLabel}`" }, + { file: "components/ai-connections/AiConnectionIdentity.tsx", content: "` · ${connection.accountLabel}`" }, + { file: "components/ai-connections/AiConnectionPoolRunDetails.tsx", content: "Task-pinned pool account · {account?.accountName" }, + { file: "components/AdapterLoginChrome.tsx", content: "{login?.accountLabel ?? provider} is signed in." }, + { file: "components/chat/ExternallyConnectedTaskBanner.tsx", content: "{binding.externalLabel} ·" }, + { file: "pages/apps/chat/ChatEndpointDetail.tsx", content: "Confirm {confirmationFor" }, + { file: "components/ai-connections/AiConnectionSelect.tsx", content: "{label ?? aiConnectionDisplayLabel(connection)}" }, + { file: "components/voice/SpekoCallHistory.tsx", content: "{report.transcript.map(" }, + { file: "pages/CaseDetail.tsx", content: "{caseData.summary}" }, + { file: "pages/CaseDetail.tsx", content: "{files.map(" }, + { file: "components/CaseFieldsPanel.tsx", content: "aria-label=\"Case fields\"" }, + { file: "components/task-side-panel/TaskAttachmentPanel.tsx", content: "File is empty." }, + { file: "components/artifacts/ArtifactCard.tsx", content: "{preview}" }, + { file: "components/artifacts/RichArtifactCards.tsx", content: "<PatchLines text={body} />" }, + { file: "components/artifacts/RichArtifactCards.tsx", content: "<ReactMarkdown" }, + { file: "components/artifacts/RichArtifactCards.tsx", content: "{columns.map(" }, + { file: "components/AttentionQueueRow.tsx", content: "{detailLine}" }, + { file: "components/AttentionObligationEvidence.tsx", content: "{attentionEvidenceLabel(item, entry)}" }, + { file: "components/coordinator/NeedsYouCardKit.tsx", content: "{children}</p>" }, + { file: "components/coordinator/NeedsYouCardParts.tsx", content: "{receipt.reason}" }, + { file: "components/coordinator/CoordinatorDecisionReceipt.tsx", content: "Reason: {item.reason}" }, + { file: "components/coordinator/CoordinatorDecisionReceipt.tsx", content: "{decisionHistoryHeadline(item, userLabelMap)}" }, + { file: "components/coordinator/CoordinatorNeedsYou.tsx", content: "<h2>{title}</h2>" }, + { file: "components/DecisionCard.tsx", content: "{option.description}" }, + { file: "components/DecisionCard.tsx", content: "{row.summary}" }, + { file: "components/DecisionResolver.tsx", content: "{decision.title}" }, + { file: "components/TaskDecisionRecord.tsx", content: "{decision.inputValues![input.id]}" }, + { file: "components/IssueThreadInteractionCard.tsx", content: "<SuggestTasksCard" }, + { file: "components/IssueThreadInteractionCard.tsx", content: "<ConnectionIntentInteractionBody" }, + { file: "components/IssueThreadInteractionCard.tsx", content: "<CompactDecisionAsk><PromptText>{compactTitle}" }, + { file: "components/IssueRecoveryActionCard.tsx", content: "{headline}" }, + { file: "components/IssueRecoveryActionCard.tsx", content: "{evidenceSummary.text}\n" }, + { file: "components/IssueRecoveryActionCard.tsx", content: ">{evidenceSummary.text}</span>" }, + { file: "components/IssueRunLedger.tsx", content: "{retryState.secondary}" }, + { file: "components/ToastViewport.tsx", content: "{toast.title}" }, + { file: "components/ToastViewport.tsx", content: "{toast.body}" }, + { file: "components/interrupt-handoff/InterruptHandoffViews.tsx", content: "{preview.text}" }, + { file: "components/interrupt-handoff/InterruptHandoffViews.tsx", content: "{bucket.detail}" }, + { file: "components/ApprovalPayload.tsx", content: "{String(value)}" }, + { file: "components/ApprovalPayload.tsx", content: "{String(payload.guidance)}" }, + { file: "components/ApprovalPayload.tsx", content: "{proposedComment}" }, + { file: "components/ApprovalPayload.tsx", content: "{String(plan)}" }, + { file: "components/actions/ActionCard.tsx", content: "{json}" }, + { file: "components/actions/ActionCard.tsx", content: "{reason}" }, + { file: "components/run-log/LogViewer.tsx", content: "{evt.message" }, + { file: "components/run-log/LogViewer.tsx", content: "{redactPathText(run.stderrExcerpt" }, + { file: "components/run-log/RunDetails.tsx", content: "redactPathText(payload.prompt" }, + { file: "components/run-log/RunDetails.tsx", content: "redactPathValue(payload.context" }, + { file: "components/run-log/RunDetails.tsx", content: "formatEnvForDisplay(payload.env" }, + { file: "components/DocumentDiffModal.tsx", content: "{row.text.length > 0" }, + { file: "components/CaseRevisionRail.tsx", content: "{row.text.length > 0" }, + { file: "pages/apps/app-detail/ActionTestDialog.tsx", content: "<RawResponseDisclosure value={value}" }, + { file: "pages/apps/app-detail/ActionTestDialog.tsx", content: "<RawResponseDisclosure value={outcome.result.result}" }, + { file: "components/search/SearchResultRow.tsx", content: "<HighlightedText\n text={text}" }, +]; + +function tagEnd(source: string, start: number): number { + let depth = 0; + let quote: string | null = null; + for (let i = start; i < source.length; i++) { + const c = source[i]; + if (quote) { + if (c === quote && source[i - 1] !== "\\") quote = null; + } else if (c === "\"" || c === "'" || c === "`") { + if (depth === 0 && c === "`") continue; + quote = c; + } else if (c === "{") { + depth++; + } else if (c === "}") { + depth--; + } else if (c === ">" && depth === 0) { + return i; + } + } + return source.length; +} + +function openElementsAt(source: string, index: number): string[] { + const stack: Array<{ name: string; tag: string }> = []; + const tagStart = /(?<![\w.)\]])<(\/?)([A-Za-z][\w.]*)?(?=[\s>/])/g; + for (let match = tagStart.exec(source); match && match.index < index; match = tagStart.exec(source)) { + const end = tagEnd(source, match.index + 1); + const tag = source.slice(match.index, end + 1); + const name = match[2] ?? ""; + if (match[1]) { + const open = stack.map((entry) => entry.name).lastIndexOf(name); + if (open >= 0) stack.length = open; + } else if (!tag.endsWith("/>") && end >= index) { + stack.push({ name, tag }); + } else if (!tag.endsWith("/>")) { + stack.push({ name, tag }); + } + tagStart.lastIndex = end + 1; + } + return stack.map((entry) => entry.tag); +} + +const CONNECTION_SURFACE_DIRS = ["pages/apps", "features/connections", "components/ai-connections"]; +const PORTAL_TAG = /<(DialogContent|AlertDialogContent|SelectContent|SelectTrigger|PopoverContent|DropdownMenuContent|SheetContent|TooltipContent)\b/g; + +function connectionSurfaceFiles(dir: string): string[] { + return readdirSync(join(UI_SRC, dir)).flatMap((name) => { + const path = join(dir, name); + if (statSync(join(UI_SRC, path)).isDirectory()) return connectionSurfaceFiles(path); + return /\.tsx$/.test(name) && !/\.(test|stories)\.tsx$/.test(name) ? [path] : []; + }); +} + +const CONNECTION_PORTALS = CONNECTION_SURFACE_DIRS.flatMap(connectionSurfaceFiles).flatMap((file) => { + const source = readFileSync(join(UI_SRC, file), "utf8"); + return [...source.matchAll(PORTAL_TAG)].map((match) => ({ + file, + line: source.slice(0, match.index).split("\n").length, + tag: source.slice(match.index, tagEnd(source, match.index! + 1) + 1), + })); +}); + +describe("session replay text masking", () => { + afterEach(() => { + document.body.innerHTML = ""; + }); + + it("records unmarked chrome text as it is", () => { + const html = `<nav><a>Tasks</a><a>Inbox</a></nav><h1>Q3 launch plan</h1><button>New task</button>`; + expect(recordedTextOf(html, "Tasks")).toBe("Tasks"); + expect(recordedTextOf(html, "Q3 launch plan")).toBe("Q3 launch plan"); + expect(recordedTextOf(html, "New task")).toBe("New task"); + }); + + it("masks text inside each marker, at any depth", () => { + expect(recordedTextOf(`<div class="${ANALYTICS_MASK_CLASS}"><p><span>Re: contract</span></p></div>`, "Re: contract")).toBe("*** ********"); + expect(recordedTextOf(`<div class="${ANALYTICS_NO_CAPTURE_CLASS}"><span>sk-123</span></div>`, "sk-123")).toBe("******"); + expect(recordedTextOf(`<div contenteditable="true"><p>Draft reply</p></div>`, "Draft reply")).toBe("***** *****"); + expect(recordedTextOf(`<div contenteditable="false"><p>Read only</p></div>`, "Read only")).toBe("Read only"); + }); + + it("sends only the marker selector to session replay", () => { + expect(options.session_recording.maskTextSelector).toBe(ANALYTICS_MASK_TEXT_SELECTOR); + expect(options.session_recording).not.toHaveProperty("maskTextFn"); + expect(options.session_recording.maskAllInputs).toBe(true); + expect(options.session_recording.blockClass).toBe(ANALYTICS_NO_CAPTURE_CLASS); + }); + + it("masks a voice transcript", () => { + const html = renderToStaticMarkup( + <VoiceTranscript agentName="Ada" entries={[{ id: "1", source: "user", text: "Read my latest Gmail", final: true, interrupted: false } as never]} />, + ); + expect(recordedTextOf(html, "Read my latest Gmail")).toBe("**** ** ****** *****"); + }); + + it("masks a tool result in a run transcript", () => { + const html = renderToStaticMarkup( + <RunTranscriptView + mode="raw" + entries={[{ kind: "tool_result", ts: "2026-01-01T00:00:00Z", toolUseId: "t1", toolName: "gmail_read", content: "Subject: Globex renewal", isError: false }]} + />, + ); + expect(recordedTextOf(html, "Globex renewal")).not.toMatch(/[A-Za-z]/); + }); + + it("masks the adapter command, prompt, context and environment of a run invocation", async () => { + const host = document.createElement("div"); + document.body.append(host); + const root = createRoot(host); + await act(async () => root.render( + <RunInvocationCard + censorUsernameInLogs={false} + payload={{ + adapterType: "claude_local", + command: "claude", + commandArgs: ["--append", "Reply to jane@globex.com"], + commandNotes: ["Loaded Globex renewal notes"], + prompt: "Summarize the Globex renewal thread", + context: { inbox: "jane@globex.com" }, + env: { GLOBEX_ACCOUNT: "globex-tenant" }, + }} + />, + )); + const details = [...host.querySelectorAll("button")].find((button) => button.textContent?.includes("Details")); + await act(async () => details!.click()); + expect(replayLeaks("Reply to jane@globex.com", host)).toEqual({ rendered: true, recorded: false }); + expect(replayLeaks("Loaded Globex renewal notes", host)).toEqual({ rendered: true, recorded: false }); + expect(replayLeaks("Summarize the Globex renewal thread", host)).toEqual({ rendered: true, recorded: false }); + expect(replayLeaks("jane@globex.com", host).recorded).toBe(false); + expect(replayLeaks("globex-tenant", host)).toEqual({ rendered: true, recorded: false }); + expect(replayLeaks("Prompt", host)).toEqual({ rendered: true, recorded: true }); + await act(async () => root.unmount()); + host.remove(); + }); + + it("masks document revision diff lines inside the diff dialog portal", async () => { + const revision = (revisionNumber: number, body: string) => ({ + id: `rev-${revisionNumber}`, companyId: "c", documentId: "d", issueId: "i", key: "plan", revisionNumber, + title: "Plan", format: "markdown", body, changeSummary: null, createdByAgentId: null, createdByUserId: null, + createdAt: "2026-01-01T00:00:00Z", + }) as unknown as DocumentRevision; + const host = document.createElement("div"); + document.body.append(host); + const root = createRoot(host); + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + await act(async () => root.render( + <QueryClientProvider client={client}> + <DocumentDiffModal + documentKey="plan" + latestRevisionNumber={2} + open + onOpenChange={() => {}} + revisionsQueryKey={["diff-test"]} + revisionsQueryFn={async () => [revision(1, "Call Globex about renewal"), revision(2, "Email jane@globex.com the renewal")]} + /> + </QueryClientProvider>, + )); + await vi.waitFor(() => expect(document.body.textContent).toContain("Email jane@globex.com the renewal")); + expect(host.contains(document.querySelector('[role="dialog"]'))).toBe(false); + expect(replayLeaks("Call Globex about renewal", document.body)).toEqual({ rendered: true, recorded: false }); + expect(replayLeaks("Email jane@globex.com the renewal", document.body)).toEqual({ rendered: true, recorded: false }); + await act(async () => root.unmount()); + client.clear(); + host.remove(); + }); + + it("blocks secret markers entirely instead of masking them", () => { + document.body.innerHTML = `<p class="${ANALYTICS_NO_CAPTURE_CLASS}"><span>pcgw_live_123</span></p><p>Copy token</p>`; + expect(isBlockedFromReplay("pcgw_live_123")).toBe(true); + expect(isBlockedFromReplay("Copy token")).toBe(false); + }); + + it.each([ + { name: "a linked Slack conversation", provider: "slack" as const, externalUrl: "https://globex.slack.com/archives/C1", label: "#globex-deals" }, + { name: "an unlinked Slack conversation", provider: "slack" as const, externalUrl: null, label: "#globex-deals" }, + { name: "a linked GitHub thread", provider: "github" as const, externalUrl: "https://github.com/globex/renewals/issues/7", label: "globex/renewals #7" }, + { name: "an email conversation", provider: "agentmail" as const, externalUrl: null, label: "jane@globex.com" }, + ])("masks the destination of $name in the conversation list", ({ provider, externalUrl, label }) => { + document.body.innerHTML = renderToStaticMarkup( + <ChatConversationList provider={provider} rows={[{ id: "c1", externalLabel: label, externalUrl, state: "completed", updatedAt: "2026-01-01T00:00:00Z" }]} />, + ); + expect(replayLeaks(label)).toEqual({ rendered: true, recorded: false }); + expect(replayLeaks("Completed")).toEqual({ rendered: true, recorded: true }); + }); + + it.each(MASKED_SURFACES)("keeps the source mask on $content in $file", ({ file, content }) => { + const source = readFileSync(join(UI_SRC, file), "utf8"); + const index = source.indexOf(content); + expect(index, `content not found in ${file}`).toBeGreaterThanOrEqual(0); + const contentTag = source.startsWith("<", index) ? source.slice(index, tagEnd(source, index + 1) + 1) : ""; + const elements = [...openElementsAt(source, index), contentTag]; + expect(elements.some((tag) => tag.includes("ANALYTICS_MASK_CLASS"))).toBe(true); + }); + + it("finds the portaled content of connection and account surfaces", () => { + expect(CONNECTION_PORTALS.length).toBeGreaterThan(40); + }); + + it.each(CONNECTION_PORTALS)("masks the portal at $file:$line", ({ tag }) => { + expect(tag).toMatch(/ANALYTICS_MASK_CLASS|ANALYTICS_NO_CAPTURE_CLASS/); + }); + + it("never lets autocapture record element text or attribute values", () => { + expect(options.mask_all_text).toBe(true); + expect(options.mask_all_element_attributes).toBe(true); + }); +}); diff --git a/ui/src/lib/analytics/replay-recording.test-utils.ts b/ui/src/lib/analytics/replay-recording.test-utils.ts new file mode 100644 index 00000000000..c8ee19cf7f9 --- /dev/null +++ b/ui/src/lib/analytics/replay-recording.test-utils.ts @@ -0,0 +1,38 @@ +import { ANALYTICS_MASK_TEXT_SELECTOR, ANALYTICS_NO_CAPTURE_CLASS } from "./privacy"; + +const BLOCK_SELECTOR = `.${ANALYTICS_NO_CAPTURE_CLASS}`; + +export function recordedTextNode(node: Text): string { + const parent = node.parentElement; + if (parent?.closest(BLOCK_SELECTOR)) return ""; + if (parent?.closest(ANALYTICS_MASK_TEXT_SELECTOR)) return node.data.replace(/\S/g, "*"); + return node.data; +} + +export function recordedText(root: Node = document.body): string { + const doc = root.ownerDocument ?? (root as Document); + const walker = doc.createTreeWalker(root, NodeFilter.SHOW_TEXT); + let text = ""; + while (walker.nextNode()) text += recordedTextNode(walker.currentNode as Text); + return text; +} + +export function replayLeaks(sensitive: string, root: Node = document.body): { rendered: boolean; recorded: boolean } { + return { + rendered: (root.textContent ?? "").includes(sensitive), + recorded: recordedText(root).includes(sensitive), + }; +} + +export function isBlockedFromReplay(sensitive: string, root: Node = document.body): boolean { + const doc = root.ownerDocument ?? (root as Document); + const walker = doc.createTreeWalker(root, NodeFilter.SHOW_TEXT); + let found = false; + while (walker.nextNode()) { + const node = walker.currentNode as Text; + if (!node.data.includes(sensitive)) continue; + found = true; + if (!node.parentElement?.closest(BLOCK_SELECTOR)) return false; + } + return found; +} diff --git a/ui/src/lib/analytics/shared-chrome.test.tsx b/ui/src/lib/analytics/shared-chrome.test.tsx index 1dc07a6ffcd..f70e59695fe 100644 --- a/ui/src/lib/analytics/shared-chrome.test.tsx +++ b/ui/src/lib/analytics/shared-chrome.test.tsx @@ -7,16 +7,15 @@ import { Button } from "@/components/ui/button"; import { Label } from "@/components/ui/label"; import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { EmptyState } from "@/components/EmptyState"; -import { ANALYTICS_UNMASK_ATTRIBUTE, maskReplayText } from "./privacy"; - -// Shared components render customer text too (agent names, document titles), -// so none of them reveals replay text unless its caller opts in. +import { ANALYTICS_MASK_TEXT_SELECTOR } from "./privacy"; function textOf(html: string, text: string): string { document.body.innerHTML = html; const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT); while (walker.nextNode()) { - if (walker.currentNode.textContent === text) return maskReplayText(text, walker.currentNode.parentElement); + if (walker.currentNode.textContent === text) { + return walker.currentNode.parentElement?.closest(ANALYTICS_MASK_TEXT_SELECTOR) ? text.replace(/\S/g, "*") : text; + } } throw new Error(`text not rendered: ${text}`); } @@ -26,29 +25,13 @@ describe("shared components and session replay", () => { document.body.innerHTML = ""; }); - it("masks customer text in shared components by default", () => { + it("records the text of shared components as it is", () => { const html = renderToStaticMarkup( <div> - <Button>Open Acme Plan</Button> - <Label>Ada Agent</Label> - <Tabs><TabsList><TabsTrigger value="a">Q3 Board Deck</TabsTrigger></TabsList></Tabs> - <EmptyState icon={Bot} message="No costs for Ada Agent yet." /> - </div>, - ); - expect(html).not.toContain(ANALYTICS_UNMASK_ATTRIBUTE); - expect(textOf(html, "Open Acme Plan")).toBe("**** **** ****"); - expect(textOf(html, "Ada Agent")).toBe("*** *****"); - expect(textOf(html, "Q3 Board Deck")).toBe("** ***** ****"); - expect(textOf(html, "No costs for Ada Agent yet.")).toBe("** ***** *** *** ***** ****"); - }); - - it("shows fixed product copy when the caller opts in", () => { - const html = renderToStaticMarkup( - <div> - <Button analyticsChrome>New task</Button> - <Label analyticsChrome>Agent name</Label> - <Tabs><TabsList><TabsTrigger analyticsChrome value="a">Activity</TabsTrigger></TabsList></Tabs> - <EmptyState analyticsChrome icon={Bot} message="Inbox zero." /> + <Button>New task</Button> + <Label>Agent name</Label> + <Tabs><TabsList><TabsTrigger value="a">Activity</TabsTrigger></TabsList></Tabs> + <EmptyState icon={Bot} message="Inbox zero." /> </div>, ); expect(textOf(html, "New task")).toBe("New task"); diff --git a/ui/src/lib/analytics/unmask-allowlist.test.ts b/ui/src/lib/analytics/unmask-allowlist.test.ts deleted file mode 100644 index 6a710349bfa..00000000000 --- a/ui/src/lib/analytics/unmask-allowlist.test.ts +++ /dev/null @@ -1,102 +0,0 @@ -// @vitest-environment jsdom - -import { readdirSync, readFileSync } from "node:fs"; -import { join, relative } from "node:path"; -import { describe, expect, it } from "vitest"; -import { buildPostHogInitOptions } from "./product-analytics"; -import { maskReplayText } from "./privacy"; - -// Session replay masks all text by default. Text shows only inside the -// unmask allowlist, so this file is the review point for that allowlist. -// -// Connected-account content (Gmail bodies, Calendar events, Slack messages in -// tasks, chat, tool results and previews) is Google user data / Slack data: -// no human may read it in a replay (Google API Limited Use). It must never sit -// inside an unmasked element. Before adding any entry below, confirm the -// element renders fixed product copy only, never connected-account or other -// customer content. - -const UI_SRC = join(import.meta.dirname, "../.."); - -/** Files that may spread the unmask attribute: shared components, behind an opt-in prop. */ -const UNMASK_PROPS_FILES = [ - "components/EmptyState.tsx", - "components/SidebarNavItem.production.tsx", - "components/SidebarNavItem.tsx", - "components/ui/button.tsx", - "components/ui/label.tsx", - "components/ui/tabs.tsx", - "lib/analytics/privacy.ts", -]; - -/** - * Reviewed `analyticsChrome` opt-ins on Button, Label, TabsTrigger or - * EmptyState, as "file: component". Empty today: none opts in. - */ -const REVIEWED_CHROME_OPT_INS: string[] = []; - -function sourceFiles(dir: string): string[] { - return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { - const path = join(dir, entry.name); - if (entry.isDirectory()) return entry.name === "node_modules" ? [] : sourceFiles(path); - return /\.(ts|tsx)$/.test(entry.name) && !/\.(test|stories)\.tsx?$/.test(entry.name) ? [path] : []; - }); -} - -const files = sourceFiles(UI_SRC).map((path) => ({ name: relative(UI_SRC, path), source: readFileSync(path, "utf8") })); - -describe("session replay unmask allowlist", () => { - it("spreads the unmask attribute only in the reviewed shared components", () => { - const users = files - .filter((file) => /ANALYTICS_UNMASK_PROPS|data-analytics-unmask/.test(file.source)) - .map((file) => file.name) - .sort(); - expect(users).toEqual(UNMASK_PROPS_FILES); - }); - - it("opts in sidebar items only when the label is a fixed string", () => { - const offenders: string[] = []; - for (const file of files) { - for (const match of file.source.matchAll(/<SidebarNavItem\b[^>]*?\banalyticsChrome\b[\s\S]*?\/>/g)) { - if (!/\slabel="[^"]+"/.test(match[0])) offenders.push(`${file.name}: ${match[0].slice(0, 80)}`); - } - } - expect(offenders).toEqual([]); - }); - - it("has no unreviewed analyticsChrome opt-in on other shared components", () => { - const optIns: string[] = []; - for (const file of files) { - for (const match of file.source.matchAll(/<(Button|Label|TabsTrigger|EmptyState)\b[^>]*?\banalyticsChrome\b/g)) { - optIns.push(`${file.name}: ${match[1]}`); - } - } - expect(optIns.sort()).toEqual(REVIEWED_CHROME_OPT_INS); - }); - - it("masks connected-account content in replays and keeps it out of autocapture", () => { - document.body.innerHTML = ` - <nav data-analytics-unmask><span id="nav">Tasks</span></nav> - <div class="task-chat"> - <div class="tool-result"><p id="gmail">Re: Q3 contract — please sign by Friday</p></div> - <div class="tool-result"><p id="calendar">Board meeting with Acme, 3pm</p></div> - <div class="slack-preview"><p id="slack">#deals: we lost the Globex renewal</p></div> - </div>`; - const text = (id: string) => { - const element = document.getElementById(id)!; - return maskReplayText(element.textContent!, element); - }; - expect(text("nav")).toBe("Tasks"); - expect(text("gmail")).not.toMatch(/[A-Za-z0-9]/); - expect(text("calendar")).not.toMatch(/[A-Za-z0-9]/); - expect(text("slack")).not.toMatch(/[A-Za-z0-9]/); - // Autocapture never records element text or attribute values anywhere. - const options = buildPostHogInitOptions( - { token: "t", apiHost: "/_ph", uiHost: null, environment: "production", stackId: "s", replayEnabled: true }, - "acme.paperclip.app", - ); - expect(options.mask_all_text).toBe(true); - expect(options.mask_all_element_attributes).toBe(true); - document.body.innerHTML = ""; - }); -}); diff --git a/ui/src/pages/AgentDetail.production.tsx b/ui/src/pages/AgentDetail.production.tsx index b4531da983c..8353e42b6cc 100644 --- a/ui/src/pages/AgentDetail.production.tsx +++ b/ui/src/pages/AgentDetail.production.tsx @@ -129,6 +129,7 @@ export { heartbeatProgressLogLineKey, RunInvocationCard, } from "../components/run-log/RunDetails"; +import { ANALYTICS_NO_CAPTURE_CLASS, ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; const runStatusIcons: Record<string, { icon: typeof CheckCircle2; color: string }> = { succeeded: { icon: CheckCircle2, color: "text-green-600 dark:text-green-400" }, @@ -3077,12 +3078,12 @@ function RunDetail({ run: initialRun, agentRouteId, adapterType, adapterConfig } {claudeLoginResult && ( <> {!!claudeLoginResult.stdout && ( - <pre className="bg-neutral-100 dark:bg-neutral-950 rounded-md p-3 text-xs font-mono text-foreground overflow-x-auto whitespace-pre-wrap"> + <pre className={cn("bg-neutral-100 dark:bg-neutral-950 rounded-md p-3 text-xs font-mono text-foreground overflow-x-auto whitespace-pre-wrap", ANALYTICS_MASK_CLASS)}> {claudeLoginResult.stdout} </pre> )} {!!claudeLoginResult.stderr && ( - <pre className="bg-neutral-100 dark:bg-neutral-950 rounded-md p-3 text-xs font-mono text-red-700 dark:text-red-300 overflow-x-auto whitespace-pre-wrap"> + <pre className={cn("bg-neutral-100 dark:bg-neutral-950 rounded-md p-3 text-xs font-mono text-red-700 dark:text-red-300 overflow-x-auto whitespace-pre-wrap", ANALYTICS_MASK_CLASS)}> {claudeLoginResult.stderr} </pre> )} @@ -3236,7 +3237,7 @@ function RunDetail({ run: initialRun, agentRouteId, adapterType, adapterConfig } {run.stderrExcerpt && ( <div className="space-y-1"> <span className="text-xs font-medium text-red-600 dark:text-red-400">stderr</span> - <pre className="bg-neutral-100 dark:bg-neutral-950 rounded-md p-3 text-xs font-mono text-red-700 dark:text-red-300 overflow-x-auto whitespace-pre-wrap">{run.stderrExcerpt}</pre> + <pre className={cn("bg-neutral-100 dark:bg-neutral-950 rounded-md p-3 text-xs font-mono text-red-700 dark:text-red-300 overflow-x-auto whitespace-pre-wrap", ANALYTICS_MASK_CLASS)}>{run.stderrExcerpt}</pre> </div> )} @@ -3244,7 +3245,7 @@ function RunDetail({ run: initialRun, agentRouteId, adapterType, adapterConfig } {run.stdoutExcerpt && !run.logRef && ( <div className="space-y-1"> <span className="text-xs font-medium text-muted-foreground">stdout</span> - <pre className="bg-neutral-100 dark:bg-neutral-950 rounded-md p-3 text-xs font-mono text-foreground overflow-x-auto whitespace-pre-wrap">{run.stdoutExcerpt}</pre> + <pre className={cn("bg-neutral-100 dark:bg-neutral-950 rounded-md p-3 text-xs font-mono text-foreground overflow-x-auto whitespace-pre-wrap", ANALYTICS_MASK_CLASS)}>{run.stdoutExcerpt}</pre> </div> )} @@ -3318,7 +3319,7 @@ function KeysTab({ agentId, companyId }: { agentId: string; companyId?: string } API key created — copy it now, it will not be shown again. </p> <div className="flex items-center gap-2"> - <code className="flex-1 bg-neutral-100 dark:bg-neutral-950 rounded px-3 py-1.5 text-xs font-mono text-green-700 dark:text-green-300 truncate"> + <code className={cn("flex-1 bg-neutral-100 dark:bg-neutral-950 rounded px-3 py-1.5 text-xs font-mono text-green-700 dark:text-green-300 truncate", ANALYTICS_NO_CAPTURE_CLASS)}> {tokenVisible ? newToken : newToken.replace(/./g, "•")} </code> <Button diff --git a/ui/src/pages/AgentDetail.tsx b/ui/src/pages/AgentDetail.tsx index cee501f065e..b187295d035 100644 --- a/ui/src/pages/AgentDetail.tsx +++ b/ui/src/pages/AgentDetail.tsx @@ -189,6 +189,7 @@ export { heartbeatProgressLogLineKey, RunInvocationCard, } from "../components/run-log/RunDetails"; +import { ANALYTICS_MASK_CLASS, ANALYTICS_NO_CAPTURE_CLASS } from "@/lib/analytics/privacy"; const AgentAdvancedTab = lazy(() => import("./AgentAdvancedTab").then(module => ({ default: module.AgentAdvancedTab }))); @@ -2692,7 +2693,7 @@ export function PromptsTab({ className="inline-flex items-center gap-2 rounded-md border border-border px-3 py-2 text-sm text-muted-foreground hover:bg-accent hover:text-foreground"> <Copy className="h-3.5 w-3.5" />Copy preserved edits </CopyText> - <pre className="overflow-x-auto whitespace-pre-wrap break-words rounded-md border border-border bg-muted p-3 font-mono text-sm">{candidate.content}</pre> + <pre className={cn("overflow-x-auto whitespace-pre-wrap break-words rounded-md border border-border bg-muted p-3 font-mono text-sm", ANALYTICS_MASK_CLASS)}>{candidate.content}</pre> </div> )} </div> @@ -2702,7 +2703,7 @@ export function PromptsTab({ {candidateRunId && <div role="status" className="space-y-3"> <p className="text-sm text-muted-foreground">Reviewing preserved edits. Save to apply your resolved draft and close this preserved edit.</p> <details><summary className="cursor-pointer text-sm text-muted-foreground">Compare current instructions</summary> - <pre className="whitespace-pre-wrap break-words rounded-md border border-border p-3 font-mono text-sm">{currentContent}</pre> + <pre className={cn("whitespace-pre-wrap break-words rounded-md border border-border p-3 font-mono text-sm", ANALYTICS_MASK_CLASS)}>{currentContent}</pre> </details> {draftBaseRevisionRef.current !== (selectedFileDetail?.revision?.id ?? null) && <p className="text-sm text-destructive">The current instructions changed after this draft was loaded. Refresh the current revision, compare the instructions, and save your resolved draft again.</p>} {(resolveCandidate.error || draftBaseRevisionRef.current !== (selectedFileDetail?.revision?.id ?? null)) && <Button type="button" variant="outline" size="sm" disabled={isSaving} onClick={() => refreshCandidateBase.mutate()}>Refresh current revision</Button>} @@ -2753,7 +2754,7 @@ export function PromptsTab({ onKeyDown={(event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); setInstructionMode("edit"); } }}> {displayValue.trim() ? <pre data-testid="instructions-raw-source" - className="block min-h-(--sz-420px) w-full overflow-x-auto p-(--agent-identity-panel-gap) font-mono text-xs leading-5 whitespace-pre-wrap break-words text-muted-foreground" + className={cn("block min-h-(--sz-420px) w-full overflow-x-auto p-(--agent-identity-panel-gap) font-mono text-xs leading-5 whitespace-pre-wrap break-words text-muted-foreground", ANALYTICS_MASK_CLASS)} > {displayValue} </pre> : <p className="min-h-(--sz-420px) p-(--agent-identity-panel-gap) text-sm text-muted-foreground">This instruction file is empty.</p>} @@ -3314,7 +3315,7 @@ function RunDetail({ run: initialRun, agentRouteId, adapterType, adapterConfig } className="text-xs text-muted-foreground" > On behalf of{" "} - <span className="text-foreground"> + <span className={cn("text-foreground", ANALYTICS_MASK_CLASS)}> {responsibleUserName ?? responsibleUserLabel(null)} </span> </div> @@ -3322,7 +3323,7 @@ function RunDetail({ run: initialRun, agentRouteId, adapterType, adapterConfig } {Boolean(run.identityHistory?.length) && ( <details className="text-xs text-muted-foreground" data-testid="run-identity-history"> <summary className="cursor-pointer">GitHub identity history</summary> - <ol className="mt-2 space-y-2"> + <ol className={cn("mt-2 space-y-2", ANALYTICS_MASK_CLASS)}> {run.identityHistory!.map((identity) => { const person = userDirectory?.users.find((entry) => entry.principalId === identity.responsibleUserId); return ( @@ -3418,12 +3419,12 @@ function RunDetail({ run: initialRun, agentRouteId, adapterType, adapterConfig } {claudeLoginResult && ( <> {!!claudeLoginResult.stdout && ( - <pre className="bg-neutral-100 dark:bg-neutral-950 rounded-md p-3 text-xs font-mono text-foreground overflow-x-auto whitespace-pre-wrap"> + <pre className={cn("bg-neutral-100 dark:bg-neutral-950 rounded-md p-3 text-xs font-mono text-foreground overflow-x-auto whitespace-pre-wrap", ANALYTICS_MASK_CLASS)}> {claudeLoginResult.stdout} </pre> )} {!!claudeLoginResult.stderr && ( - <pre className="bg-neutral-100 dark:bg-neutral-950 rounded-md p-3 text-xs font-mono text-red-700 dark:text-red-300 overflow-x-auto whitespace-pre-wrap"> + <pre className={cn("bg-neutral-100 dark:bg-neutral-950 rounded-md p-3 text-xs font-mono text-red-700 dark:text-red-300 overflow-x-auto whitespace-pre-wrap", ANALYTICS_MASK_CLASS)}> {claudeLoginResult.stderr} </pre> )} @@ -3534,7 +3535,7 @@ function RunDetail({ run: initialRun, agentRouteId, adapterType, adapterConfig } {run.stderrExcerpt && ( <div className="space-y-1"> <span className="text-xs font-medium text-red-600 dark:text-red-400">stderr</span> - <pre className="bg-neutral-100 dark:bg-neutral-950 rounded-md p-3 text-xs font-mono text-red-700 dark:text-red-300 overflow-x-auto whitespace-pre-wrap">{run.stderrExcerpt}</pre> + <pre className={cn("bg-neutral-100 dark:bg-neutral-950 rounded-md p-3 text-xs font-mono text-red-700 dark:text-red-300 overflow-x-auto whitespace-pre-wrap", ANALYTICS_MASK_CLASS)}>{run.stderrExcerpt}</pre> </div> )} @@ -3542,7 +3543,7 @@ function RunDetail({ run: initialRun, agentRouteId, adapterType, adapterConfig } {run.stdoutExcerpt && !run.logRef && ( <div className="space-y-1"> <span className="text-xs font-medium text-muted-foreground">stdout</span> - <pre className="bg-neutral-100 dark:bg-neutral-950 rounded-md p-3 text-xs font-mono text-foreground overflow-x-auto whitespace-pre-wrap">{run.stdoutExcerpt}</pre> + <pre className={cn("bg-neutral-100 dark:bg-neutral-950 rounded-md p-3 text-xs font-mono text-foreground overflow-x-auto whitespace-pre-wrap", ANALYTICS_MASK_CLASS)}>{run.stdoutExcerpt}</pre> </div> )} @@ -3627,7 +3628,7 @@ export function KeysTab({ agentId, companyId }: { agentId: string; companyId?: s API key created — copy it now, it will not be shown again. </p> <div className="flex items-center gap-2"> - <code className="flex-1 bg-neutral-100 dark:bg-neutral-950 rounded px-3 py-1.5 text-xs font-mono text-green-700 dark:text-green-300 truncate"> + <code className={cn("flex-1 bg-neutral-100 dark:bg-neutral-950 rounded px-3 py-1.5 text-xs font-mono text-green-700 dark:text-green-300 truncate", ANALYTICS_NO_CAPTURE_CLASS)}> {tokenVisible ? newToken : newToken.replace(/./g, "•")} </code> <Button diff --git a/ui/src/pages/AgentToolsTab.tsx b/ui/src/pages/AgentToolsTab.tsx index 016565d5565..a26a98a4f29 100644 --- a/ui/src/pages/AgentToolsTab.tsx +++ b/ui/src/pages/AgentToolsTab.tsx @@ -25,6 +25,7 @@ import { import { cn } from "../lib/utils"; import { brandChipBadge } from "../lib/status-colors"; import { installPayload, installStateFrom, isAgentInstalled, INSTALLED_HINT } from "../lib/tool-installs"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; function isGitHubConnection(connection: ToolConnection): boolean { return (connection.config?.sourceTemplateKey ?? connection.transportConfig?.sourceTemplateKey) === "github"; @@ -236,7 +237,7 @@ function InstalledAppsSection({ /> <span className="min-w-0 flex-1"> <span className="flex flex-wrap items-center gap-2"> - <span className="truncate text-sm font-medium text-foreground">{connection.name}</span> + <span className={cn("truncate text-sm font-medium text-foreground", ANALYTICS_MASK_CLASS)}>{connection.name}</span> <InstallBadge installed={checked} installedForAll={installedForAll} permitted={permitted} /> {rowPending ? <span className="text-xs text-muted-foreground">Saving...</span> : null} </span> @@ -648,7 +649,7 @@ export function AgentToolsTab({ agent, companyId }: { agent: AgentDetailRecord; <td className="px-3 py-2"> <RiskBadge risk={tool.riskLevel} /> </td> - <td className="px-3 py-2 text-xs text-muted-foreground"> + <td className={cn("px-3 py-2 text-xs text-muted-foreground", ANALYTICS_MASK_CLASS)}> {connectionNameById.get(tool.connectionId) ?? "—"} </td> </tr> diff --git a/ui/src/pages/ApprovalDetail.tsx b/ui/src/pages/ApprovalDetail.tsx index f152c5a5bc7..8550bb91f83 100644 --- a/ui/src/pages/ApprovalDetail.tsx +++ b/ui/src/pages/ApprovalDetail.tsx @@ -17,6 +17,8 @@ import { Textarea } from "@/components/ui/textarea"; import { CheckCircle2, ChevronRight, Sparkles } from "lucide-react"; import type { ApprovalComment } from "@paperclipai/shared"; import { MarkdownBody } from "../components/MarkdownBody"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; export function ApprovalDetail() { const { approvalId } = useParams<{ approvalId: string }>(); @@ -231,7 +233,7 @@ export function ApprovalDetail() { See full request </button> {showRawPayload && ( - <pre className="text-xs bg-muted/40 rounded-md p-3 overflow-x-auto"> + <pre className={cn("text-xs bg-muted/40 rounded-md p-3 overflow-x-auto", ANALYTICS_MASK_CLASS)}> {JSON.stringify(payload, null, 2)} </pre> )} diff --git a/ui/src/pages/CaseDetail.tsx b/ui/src/pages/CaseDetail.tsx index 892d9218cd9..07bb4bc3a40 100644 --- a/ui/src/pages/CaseDetail.tsx +++ b/ui/src/pages/CaseDetail.tsx @@ -24,6 +24,8 @@ import { Button } from "@/components/ui/button"; import { formatDateTime } from "@/lib/utils"; import { queryKeys } from "@/lib/queryKeys"; import { caseAuditHref } from "./audit/audit-navigation"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; function CaseRelation({ item, search }: { item: Pick<CaseSummary, "id" | "identifier" | "title" | "caseType" | "status">; search: string }) { const caseHref = useCaseHref(); @@ -100,7 +102,7 @@ export function CaseDetail() { <span>{caseData.caseType}</span><CaseStatus status={caseData.status} /> </div> <h1 className="text-2xl font-semibold tracking-tight">{caseData.title}</h1> - {caseData.summary && <p className="max-w-3xl text-sm leading-relaxed text-muted-foreground">{caseData.summary}</p>} + {caseData.summary && <p className={cn("max-w-3xl text-sm leading-relaxed text-muted-foreground", ANALYTICS_MASK_CLASS)}>{caseData.summary}</p>} {caseData.labels.length > 0 && <div className="flex flex-wrap gap-1.5" aria-label="Case labels">{caseData.labels.map(label => <Badge key={label.id} variant="secondary" className="font-normal">{label.name}</Badge>)}</div>} </header> @@ -123,7 +125,7 @@ export function CaseDetail() { {caseData.attachments.length > 0 && <section className="space-y-3" aria-label="Case attachments"> <h2 className="text-sm font-semibold">Attachments</h2> {images.length > 0 && <CaseAttachmentsGallery attachments={images} />} - {files.length > 0 && <ul className="space-y-2">{files.map(attachment => <li key={attachment.id}><a href={caseAttachmentUrl(attachment)} target="_blank" rel="noreferrer" className="inline-flex max-w-full items-center gap-2 text-sm text-primary hover:underline"><FileText aria-hidden className="size-4 shrink-0" /><span className="truncate">{attachment.asset.originalFilename ?? "Download attachment"}</span></a></li>)}</ul>} + {files.length > 0 && <ul className={cn("space-y-2", ANALYTICS_MASK_CLASS)}>{files.map(attachment => <li key={attachment.id}><a href={caseAttachmentUrl(attachment)} target="_blank" rel="noreferrer" className="inline-flex max-w-full items-center gap-2 text-sm text-primary hover:underline"><FileText aria-hidden className="size-4 shrink-0" /><span className="truncate">{attachment.asset.originalFilename ?? "Download attachment"}</span></a></li>)}</ul>} </section>} {caseData.workIssueId && <CaseHandoffHistory caseId={caseData.id} task={caseData.workIssue} agents={agents} />} diff --git a/ui/src/pages/CompanyEnvironments.tsx b/ui/src/pages/CompanyEnvironments.tsx index 0055abfc6df..e37e31762f6 100644 --- a/ui/src/pages/CompanyEnvironments.tsx +++ b/ui/src/pages/CompanyEnvironments.tsx @@ -67,6 +67,8 @@ import { Field, ToggleField, } from "../components/agent-config-primitives"; +import { ANALYTICS_NO_CAPTURE_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; type EnvironmentFormState = { name: string; @@ -1207,7 +1209,7 @@ function EnvironmentImageTemplatePanel({ <summary className="cursor-pointer select-none font-medium text-foreground"> SSH command fallback </summary> - <code className="mt-2 block overflow-x-auto whitespace-nowrap text-(length:--text-micro) leading-5"> + <code className={cn("mt-2 block overflow-x-auto whitespace-nowrap text-(length:--text-micro) leading-5", ANALYTICS_NO_CAPTURE_CLASS)}> {connectionCommand} </code> </details> diff --git a/ui/src/pages/CompanyExport.tsx b/ui/src/pages/CompanyExport.tsx index d0d63bcfb66..9f593d2989a 100644 --- a/ui/src/pages/CompanyExport.tsx +++ b/ui/src/pages/CompanyExport.tsx @@ -59,6 +59,7 @@ import { } from "../components/FileTree"; import { describeError } from "@/api/errors"; import { companyProjectsQuery } from "@/lib/company-projects-query"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; /** * Extract the set of agent/project/task slugs that are "checked" based on @@ -572,7 +573,7 @@ function ExportPreviewPane({ <img src={imageSrc} alt={selectedFile} className="max-h-(--sz-480px) max-w-full object-contain" /> </div> ) : textContent !== null ? ( - <pre className="overflow-x-auto whitespace-pre-wrap break-words border-0 bg-transparent p-0 font-mono text-sm text-foreground"> + <pre className={cn("overflow-x-auto whitespace-pre-wrap break-words border-0 bg-transparent p-0 font-mono text-sm text-foreground", ANALYTICS_MASK_CLASS)}> <code>{textContent}</code> </pre> ) : ( diff --git a/ui/src/pages/CompanyImport.tsx b/ui/src/pages/CompanyImport.tsx index 67f264ce641..11db214522e 100644 --- a/ui/src/pages/CompanyImport.tsx +++ b/ui/src/pages/CompanyImport.tsx @@ -72,6 +72,7 @@ import { } from "../lib/import-job-watch"; import { Badge } from "@/components/ui/badge"; import { describeError } from "@/api/errors"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; // ── Import-specific helpers ─────────────────────────────────────────── @@ -275,7 +276,7 @@ function ImportPreviewPane({ <img src={imageSrc} alt={selectedFile} className="max-h-(--sz-480px) max-w-full object-contain" /> </div> ) : textContent !== null ? ( - <pre className="overflow-x-auto whitespace-pre-wrap break-words border-0 bg-transparent p-0 font-mono text-sm text-foreground"> + <pre className={cn("overflow-x-auto whitespace-pre-wrap break-words border-0 bg-transparent p-0 font-mono text-sm text-foreground", ANALYTICS_MASK_CLASS)}> <code>{textContent}</code> </pre> ) : ( diff --git a/ui/src/pages/CompanySkills.production.tsx b/ui/src/pages/CompanySkills.production.tsx index 45d60259f3c..1f8374c3ad9 100644 --- a/ui/src/pages/CompanySkills.production.tsx +++ b/ui/src/pages/CompanySkills.production.tsx @@ -172,6 +172,7 @@ import { import { GithubIcon } from "../components/icons/github-icon"; import type { FolderListItem, FolderListResult } from "@paperclipai/shared"; import { describeError } from "@/api/errors"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; type SkillTreeNode = { name: string; @@ -2027,7 +2028,7 @@ function CatalogDetailPane({ ) : fileQuery.data.markdown ? ( <MarkdownBody softBreaks={false} linkIssueReferences={false}>{body}</MarkdownBody> ) : ( - <pre className="overflow-x-auto whitespace-pre-wrap wrap-break-word border-0 bg-transparent p-0 font-mono text-sm text-foreground"> + <pre className={cn("overflow-x-auto whitespace-pre-wrap wrap-break-word border-0 bg-transparent p-0 font-mono text-sm text-foreground", ANALYTICS_MASK_CLASS)}> <code>{fileQuery.data.content}</code> </pre> )} @@ -2743,7 +2744,7 @@ function SkillVersionDiffDialog({ <span className="select-none border-r border-border/30 pr-3 text-right text-muted-foreground">{row.oldLineNumber ?? ""}</span> <span className="select-none border-r border-border/30 px-3 text-right text-muted-foreground">{row.newLineNumber ?? ""}</span> <span className="select-none px-3 text-center text-muted-foreground">{markerByKind[row.kind]}</span> - <pre className="overflow-x-auto whitespace-pre-wrap break-words px-3 py-0 text-inherit">{row.text.length > 0 ? row.text : " "}</pre> + <pre className={cn("overflow-x-auto whitespace-pre-wrap break-words px-3 py-0 text-inherit", ANALYTICS_MASK_CLASS)}>{row.text.length > 0 ? row.text : " "}</pre> </div> ))} </div> @@ -3128,7 +3129,7 @@ export function SkillDetailPage({ ) : file.markdown && viewMode === "preview" ? ( <MarkdownBody softBreaks={false} linkIssueReferences={false}>{body}</MarkdownBody> ) : ( - <pre className="overflow-x-auto whitespace-pre-wrap wrap-break-word border-0 bg-transparent p-0 font-mono text-sm text-foreground"> + <pre className={cn("overflow-x-auto whitespace-pre-wrap wrap-break-word border-0 bg-transparent p-0 font-mono text-sm text-foreground", ANALYTICS_MASK_CLASS)}> <code>{file.content}</code> </pre> )} @@ -4014,7 +4015,7 @@ function SkillPane({ ) : file.markdown && viewMode === "preview" ? ( <MarkdownBody softBreaks={false} linkIssueReferences={false}>{body}</MarkdownBody> ) : ( - <pre className="overflow-x-auto whitespace-pre-wrap wrap-break-word border-0 bg-transparent p-0 font-mono text-sm text-foreground"> + <pre className={cn("overflow-x-auto whitespace-pre-wrap wrap-break-word border-0 bg-transparent p-0 font-mono text-sm text-foreground", ANALYTICS_MASK_CLASS)}> <code>{file.content}</code> </pre> )} diff --git a/ui/src/pages/CompanySkills.tsx b/ui/src/pages/CompanySkills.tsx index d78d572aaa4..27273d6d456 100644 --- a/ui/src/pages/CompanySkills.tsx +++ b/ui/src/pages/CompanySkills.tsx @@ -181,6 +181,7 @@ import { import { GithubIcon } from "../components/icons/github-icon"; import type { FolderListItem, FolderListResult } from "@paperclipai/shared"; import { describeError } from "@/api/errors"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; type SkillTreeNode = { name: string; @@ -1937,7 +1938,7 @@ function CatalogDetailPane({ ) : fileQuery.data.markdown ? ( <MarkdownBody softBreaks={false} linkIssueReferences={false}>{body}</MarkdownBody> ) : ( - <pre className="overflow-x-auto whitespace-pre-wrap wrap-break-word border-0 bg-transparent p-0 font-mono text-sm text-foreground"> + <pre className={cn("overflow-x-auto whitespace-pre-wrap wrap-break-word border-0 bg-transparent p-0 font-mono text-sm text-foreground", ANALYTICS_MASK_CLASS)}> <code>{fileQuery.data.content}</code> </pre> )} @@ -2653,7 +2654,7 @@ function SkillVersionDiffDialog({ <span className="select-none border-r border-border/30 pr-3 text-right text-muted-foreground">{row.oldLineNumber ?? ""}</span> <span className="select-none border-r border-border/30 px-3 text-right text-muted-foreground">{row.newLineNumber ?? ""}</span> <span className="select-none px-3 text-center text-muted-foreground">{markerByKind[row.kind]}</span> - <pre className="overflow-x-auto whitespace-pre-wrap break-words px-3 py-0 text-inherit">{row.text.length > 0 ? row.text : " "}</pre> + <pre className={cn("overflow-x-auto whitespace-pre-wrap break-words px-3 py-0 text-inherit", ANALYTICS_MASK_CLASS)}>{row.text.length > 0 ? row.text : " "}</pre> </div> ))} </div> @@ -3049,7 +3050,7 @@ export function SkillDetailPage({ {body} </MarkdownBody> ) : ( - <pre className="overflow-x-auto whitespace-pre-wrap wrap-break-word border-0 bg-transparent p-0 font-mono text-sm text-foreground"> + <pre className={cn("overflow-x-auto whitespace-pre-wrap wrap-break-word border-0 bg-transparent p-0 font-mono text-sm text-foreground", ANALYTICS_MASK_CLASS)}> <code>{file.content}</code> </pre> )} @@ -3936,7 +3937,7 @@ function SkillPane({ ) : file.markdown && viewMode === "preview" ? ( <MarkdownBody softBreaks={false} linkIssueReferences={false}>{body}</MarkdownBody> ) : ( - <pre className="overflow-x-auto whitespace-pre-wrap wrap-break-word border-0 bg-transparent p-0 font-mono text-sm text-foreground"> + <pre className={cn("overflow-x-auto whitespace-pre-wrap wrap-break-word border-0 bg-transparent p-0 font-mono text-sm text-foreground", ANALYTICS_MASK_CLASS)}> <code>{file.content}</code> </pre> )} diff --git a/ui/src/pages/ExecutionWorkspaceDetail.tsx b/ui/src/pages/ExecutionWorkspaceDetail.tsx index def9dba1d24..9ee46119002 100644 --- a/ui/src/pages/ExecutionWorkspaceDetail.tsx +++ b/ui/src/pages/ExecutionWorkspaceDetail.tsx @@ -51,6 +51,7 @@ import { sortWorkspaceRoutinesByName, } from "../lib/workspace-routines"; import { useUpdateIssueMutation } from "../hooks/useUpdateIssueMutation"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; type WorkspaceFormState = { name: string; @@ -1566,9 +1567,9 @@ export function ExecutionWorkspaceDetail() { {operation.finishedAt ? ` → ${formatDateTime(operation.finishedAt)}` : ""} </div> {operation.stderrExcerpt ? ( - <div className="whitespace-pre-wrap break-words text-xs text-destructive">{operation.stderrExcerpt}</div> + <div className={cn("whitespace-pre-wrap break-words text-xs text-destructive", ANALYTICS_MASK_CLASS)}>{operation.stderrExcerpt}</div> ) : operation.stdoutExcerpt ? ( - <div className="whitespace-pre-wrap break-words text-xs text-muted-foreground">{operation.stdoutExcerpt}</div> + <div className={cn("whitespace-pre-wrap break-words text-xs text-muted-foreground", ANALYTICS_MASK_CLASS)}>{operation.stdoutExcerpt}</div> ) : null} </div> <StatusPill className="self-start">{operation.status}</StatusPill> diff --git a/ui/src/pages/InviteLanding.test.tsx b/ui/src/pages/InviteLanding.test.tsx index f257e249972..bf03fd47833 100644 --- a/ui/src/pages/InviteLanding.test.tsx +++ b/ui/src/pages/InviteLanding.test.tsx @@ -7,6 +7,7 @@ import { MemoryRouter, Route, Routes } from "react-router-dom"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { InviteLandingPage } from "./InviteLanding"; import { queryKeys } from "../lib/queryKeys"; +import { isBlockedFromReplay } from "@/lib/analytics/replay-recording.test-utils"; const getInviteMock = vi.hoisted(() => vi.fn()); const acceptInviteMock = vi.hoisted(() => vi.fn()); @@ -571,6 +572,40 @@ describe("InviteLandingPage", () => { }); }); + it("blocks the one-time claim secret and the tokenized onboarding URL from session replay", async () => { + acceptInviteMock.mockResolvedValue({ + id: "join-1", + companyId: "company-1", + requestType: "human", + status: "pending_approval", + claimSecret: "pcp_claim_Vb38nQe7Rw", + claimApiKeyPath: "/api/join-requests/join-1/claim-api-key", + onboarding: { textInstructions: { url: "https://paperclip.example.test/api/invites/pcp_invite_Hx9dLq/onboarding.txt" } }, + }); + getSessionMock.mockResolvedValue({ + session: { id: "session-1", userId: "user-1" }, + user: { id: "user-1", name: "Jane Example", email: "jane@example.com", image: null }, + }); + + const root = createRoot(container); + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + + await act(async () => { + renderInviteLanding(root, queryClient); + }); + await flushReact(); + await flushReact(); + await flushReact(); + await flushReact(); + + expect(isBlockedFromReplay("pcp_claim_Vb38nQe7Rw", container)).toBe(true); + expect(isBlockedFromReplay("pcp_invite_Hx9dLq", container)).toBe(true); + + await act(async () => { + root.unmount(); + }); + }); + it("auto-completes a previously accepted human invite after sign-in", async () => { getInviteMock.mockResolvedValue({ id: "invite-1", diff --git a/ui/src/pages/InviteLanding.tsx b/ui/src/pages/InviteLanding.tsx index b297bbfc5d8..0c86f7c6609 100644 --- a/ui/src/pages/InviteLanding.tsx +++ b/ui/src/pages/InviteLanding.tsx @@ -14,7 +14,8 @@ import { healthApi } from "../api/health"; import { getAdapterLabel } from "../adapters/adapter-display-registry"; import { clearPendingInviteToken, rememberPendingInviteToken } from "../lib/invite-memory"; import { queryKeys } from "../lib/queryKeys"; -import { formatDate } from "../lib/utils"; +import { cn, formatDate } from "../lib/utils"; +import { ANALYTICS_NO_CAPTURE_CLASS } from "@/lib/analytics/privacy"; type AuthMode = "sign_in" | "sign_up"; type AuthFeedback = { tone: "error" | "info"; message: string }; @@ -198,13 +199,13 @@ function AwaitingJoinApprovalPanel({ {claimSecret && claimApiKeyPath ? ( <div className="mt-4 space-y-1 border border-zinc-800 p-3 text-xs text-zinc-400"> <div className="text-zinc-200">Claim secret</div> - <div className="font-mono break-all">{claimSecret}</div> + <div className={cn("font-mono break-all", ANALYTICS_NO_CAPTURE_CLASS)}>{claimSecret}</div> <div className="font-mono break-all">POST {claimApiKeyPath}</div> </div> ) : null} {onboardingTextUrl ? ( <div className="mt-4 text-xs text-zinc-400"> - Onboarding: <span className="font-mono break-all">{onboardingTextUrl}</span> + Onboarding: <span className={cn("font-mono break-all", ANALYTICS_NO_CAPTURE_CLASS)}>{onboardingTextUrl}</span> </div> ) : null} </div> diff --git a/ui/src/pages/McpConnect.test.tsx b/ui/src/pages/McpConnect.test.tsx index db7e9bfc94e..9ac81610b3e 100644 --- a/ui/src/pages/McpConnect.test.tsx +++ b/ui/src/pages/McpConnect.test.tsx @@ -7,6 +7,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { beforeEach, expect, it, vi } from "vitest"; import { api } from "../api/client"; import { McpConnectPage, McpDevicePage } from "./McpConnect"; +import { isBlockedFromReplay } from "@/lib/analytics/replay-recording.test-utils"; const route = vi.hoisted(() => ({ id: "request-one", companyId: null as string | null, unavailable: false, canWrite: true, requestedWrite: true, requestedConfigure: false, agentConnection: false, requiresSignIn: false, clientName: "Assistant", clientOrigin: null as string | null, setupUrl: "https://my.paperclip.app/orgs/new", reverseCompanies: false, hideFirst: false })); vi.mock("@/lib/router", () => ({ @@ -48,6 +49,14 @@ function setup(device = false, agentPairingOnly = false) { }; } +it("blocks the device code being confirmed from session replay", async () => { + const page = setup(true); + try { + await vi.waitFor(() => expect(page.container.textContent).toContain("Confirm this matches the code shown by your assistant")); + expect(isBlockedFromReplay("MIST-YPED", page.container)).toBe(true); + } finally { page.cleanup(); } +}); + it("lets a person correct an invalid device code without reloading", async () => { vi.mocked(api.get).mockRejectedValueOnce(new Error("Invalid code")); const page = setup(true); diff --git a/ui/src/pages/McpConnect.tsx b/ui/src/pages/McpConnect.tsx index f20123e6d99..937b0d0e714 100644 --- a/ui/src/pages/McpConnect.tsx +++ b/ui/src/pages/McpConnect.tsx @@ -14,6 +14,8 @@ import { CompanyPatternIcon } from "@/components/CompanyPatternIcon"; import { useResilientFetch } from "@/hooks/useResilientFetch"; import { api } from "../api/client"; import { describeError } from "../api/errors"; +import { cn } from "@/lib/utils"; +import { ANALYTICS_NO_CAPTURE_CLASS } from "@/lib/analytics/privacy"; const PAIRING_CODE_PATTERN = /^[A-Za-z0-9_-]{32}$/; @@ -102,7 +104,7 @@ function McpConnectRequest({ id, device = false, agentPairingOnly = false, onEdi </div> {clientOrigin && <ClientOrigin key={clientOrigin} origin={clientOrigin} />} {!device && data?.redirectOrigin && data.redirectOrigin !== clientOrigin && <ClientOrigin key={data.redirectOrigin} origin={data.redirectOrigin} />} - {device && <p className="text-sm">Confirm this matches the code shown by your assistant: <strong className="font-mono">{id.toUpperCase()}</strong></p>} + {device && <p className="text-sm">Confirm this matches the code shown by your assistant: <strong className={cn("font-mono", ANALYTICS_NO_CAPTURE_CLASS)}>{id.toUpperCase()}</strong></p>} {(requestView.kind === "loading" || requestView.kind === "reconnecting") && <p role="status" className="text-sm text-muted-foreground">Loading connection request…</p>} {requestView.kind === "error" && <QueryErrorState error={requestView.error} action="load this connection request" onRetry={requestView.retry} retrying={requestView.isFetching} />} {requestView.kind === "error" && <p className="text-sm text-muted-foreground">Start a new connection from your assistant.</p>} diff --git a/ui/src/pages/PluginManager.tsx b/ui/src/pages/PluginManager.tsx index a7cdfa7679c..5049b34f1eb 100644 --- a/ui/src/pages/PluginManager.tsx +++ b/ui/src/pages/PluginManager.tsx @@ -30,6 +30,7 @@ import { } from "@/components/ui/dialog"; import { useToastActions } from "@/context/ToastContext"; import { cn } from "@/lib/utils"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; function firstNonEmptyLine(value: string | null | undefined): string | null { if (!value) return null; @@ -573,7 +574,7 @@ export function PluginManager() { </div> <div className="space-y-2"> <p className="text-sm font-medium">Full error output</p> - <pre className="max-h-(--sz-50vh) overflow-auto rounded-md border bg-muted/40 p-3 text-xs leading-5 whitespace-pre-wrap break-words"> + <pre className={cn("max-h-(--sz-50vh) overflow-auto rounded-md border bg-muted/40 p-3 text-xs leading-5 whitespace-pre-wrap break-words", ANALYTICS_MASK_CLASS)}> {errorDetailsPlugin?.lastError ?? "No stored error message."} </pre> </div> diff --git a/ui/src/pages/Secrets.tsx b/ui/src/pages/Secrets.tsx index ba88cc60ecd..c04a399d4e7 100644 --- a/ui/src/pages/Secrets.tsx +++ b/ui/src/pages/Secrets.tsx @@ -155,6 +155,7 @@ import { } from "./secrets/user-secret-presentation"; import type { MyUserSecretEntry } from "../api/secrets"; import { describeError } from "@/api/errors"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; type CreateMode = "managed" | "external"; // "value" writes a new secret value (for external references: through to the @@ -4274,7 +4275,7 @@ function AwsProviderVaultDiscoveryError({ <span className="font-medium text-muted-foreground">Safe request/error details</span> <CopyDetailsButton text={detailsText} /> </div> - <pre className="max-h-36 overflow-auto whitespace-pre-wrap break-words font-mono text-(length:--text-micro) leading-relaxed"> + <pre className={cn("max-h-36 overflow-auto whitespace-pre-wrap break-words font-mono text-(length:--text-micro) leading-relaxed", ANALYTICS_MASK_CLASS)}> {detailsText} </pre> </div> @@ -4367,7 +4368,7 @@ function SecretCreateError({ <span className="font-medium text-muted-foreground">Safe request/error details</span> <CopyDetailsButton text={detailsText} /> </div> - <pre className="max-h-36 overflow-auto whitespace-pre-wrap break-words font-mono text-(length:--text-micro) leading-relaxed"> + <pre className={cn("max-h-36 overflow-auto whitespace-pre-wrap break-words font-mono text-(length:--text-micro) leading-relaxed", ANALYTICS_MASK_CLASS)}> {detailsText} </pre> </div> diff --git a/ui/src/pages/SkillStudio.tsx b/ui/src/pages/SkillStudio.tsx index fe70fa2510e..c62d0af5f7f 100644 --- a/ui/src/pages/SkillStudio.tsx +++ b/ui/src/pages/SkillStudio.tsx @@ -179,6 +179,7 @@ import { type RunTemplateSelection, type SavedInputDraftState, } from "@/lib/skill-studio"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; const PANE_STORAGE_KEY = "skillStudio.paneSizes"; const RUN_TEMPLATE_STORAGE_KEY_PREFIX = "skillStudio.runTemplate"; @@ -2877,7 +2878,7 @@ function RunTemplateAdvancedPanel({ {selectedTemplate.description ? ( <p className="text-xs text-muted-foreground">{selectedTemplate.description}</p> ) : null} - <pre className="max-h-(--sz-240px) overflow-auto whitespace-pre-wrap rounded-md border border-border bg-muted/30 p-3 text-xs leading-5 text-muted-foreground"> + <pre className={cn("max-h-(--sz-240px) overflow-auto whitespace-pre-wrap rounded-md border border-border bg-muted/30 p-3 text-xs leading-5 text-muted-foreground", ANALYTICS_MASK_CLASS)}> {selectedTemplate.body} </pre> </div> @@ -3610,7 +3611,7 @@ function VersionHistorySheet({ <div className="border-b border-border px-3 py-1.5 text-xs text-muted-foreground"> Diff v{left?.revisionNumber} → v{right?.revisionNumber} </div> - <pre className="max-h-64 overflow-auto p-2 text-xs"> + <pre className={cn("max-h-64 overflow-auto p-2 text-xs", ANALYTICS_MASK_CLASS)}> {diff.map((row, i) => ( <div key={i} diff --git a/ui/src/pages/StatusCards/StatusCardDetailDrawer.tsx b/ui/src/pages/StatusCards/StatusCardDetailDrawer.tsx index 643a3c7f76d..b43566b230f 100644 --- a/ui/src/pages/StatusCards/StatusCardDetailDrawer.tsx +++ b/ui/src/pages/StatusCards/StatusCardDetailDrawer.tsx @@ -41,6 +41,7 @@ import { } from "./format"; import type { StatusCardView } from "./types"; import { taskStatusIconProps } from "@/lib/task-status-presentation"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; export function StatusCardDetailDrawer({ card, @@ -518,7 +519,7 @@ function QueryDebugSection({ card }: { card: StatusCardView }) { <ChevronDown className="h-4 w-4 text-muted-foreground transition-transform group-data-[state=open]:rotate-180" /> </CollapsibleTrigger> <CollapsibleContent className="space-y-2 border-t border-border px-3 py-3"> - <pre className="max-h-64 overflow-auto rounded-md bg-muted p-3 font-mono text-xs text-foreground"> + <pre className={cn("max-h-64 overflow-auto rounded-md bg-muted p-3 font-mono text-xs text-foreground", ANALYTICS_MASK_CLASS)}> {card.queries.length > 0 ? queryJson : "// query not compiled yet"} </pre> <p className="text-xs text-muted-foreground"> diff --git a/ui/src/pages/TeamCatalog.tsx b/ui/src/pages/TeamCatalog.tsx index b3dbe952d5b..a7c3f5f386a 100644 --- a/ui/src/pages/TeamCatalog.tsx +++ b/ui/src/pages/TeamCatalog.tsx @@ -114,6 +114,7 @@ import { XOctagon, } from "lucide-react"; import { GithubIcon } from "../components/icons/github-icon"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; // Matches design §11 breakpoints. Module-level so stories and the page agree. const DESKTOP_MIN = 1024; @@ -853,7 +854,7 @@ export function TeamDetailPane({ <MarkdownBody>{fileContent}</MarkdownBody> </div> ) : ( - <pre className="whitespace-pre-wrap break-words font-mono text-xs">{fileContent}</pre> + <pre className={cn("whitespace-pre-wrap break-words font-mono text-xs", ANALYTICS_MASK_CLASS)}>{fileContent}</pre> )} </div> </div> diff --git a/ui/src/pages/apps/AggregatorAppManager.tsx b/ui/src/pages/apps/AggregatorAppManager.tsx index 64d4f58a7d1..5e6a0ed9001 100644 --- a/ui/src/pages/apps/AggregatorAppManager.tsx +++ b/ui/src/pages/apps/AggregatorAppManager.tsx @@ -12,6 +12,8 @@ import { QueryErrorState, useQueryView } from "@/components/QueryView"; import { Button } from "@/components/ui/button"; import { Label } from "@/components/ui/label"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; export function AggregatorAppManager({ app, connections, initialConnectionId, onClose }: { app: AggregatorAppCatalogEntry; connections: ToolConnection[]; initialConnectionId?: string; onClose: () => void; @@ -19,12 +21,12 @@ export function AggregatorAppManager({ app, connections, initialConnectionId, on const [connectionId, setConnectionId] = useState(initialConnectionId ?? connections[0]?.id ?? ""); const connection = connections.find(candidate => candidate.id === connectionId); const provider = connection?.config?.sourceTemplateKey; - return <Dialog open onOpenChange={open => { if (!open) onClose(); }}><DialogContent> + return <Dialog open onOpenChange={open => { if (!open) onClose(); }}><DialogContent className={ANALYTICS_MASK_CLASS}> <DialogHeader><DialogTitle>Manage {app.name}</DialogTitle> <DialogDescription>Accounts and sign-in are managed in {isAppAggregator(provider) ? AGGREGATOR_NAMES[provider] : "the provider"}.</DialogDescription> </DialogHeader> {connections.length > 1 ? <div className="space-y-2"><Label htmlFor="manage-aggregator-gateway">Connection</Label> - <select id="manage-aggregator-gateway" className="h-9 w-full rounded-md border border-input bg-background px-3 text-sm" value={connectionId} onChange={event => setConnectionId(event.target.value)}> + <select id="manage-aggregator-gateway" className={cn("h-9 w-full rounded-md border border-input bg-background px-3 text-sm", ANALYTICS_MASK_CLASS)} value={connectionId} onChange={event => setConnectionId(event.target.value)}> {connections.map(candidate => <option key={candidate.id} value={candidate.id}>{candidate.name}</option>)} </select></div> : null} {connection ? <AccountObservations key={connection.id} app={app} connection={connection} onClose={onClose} /> : <p role="alert">This connection is no longer available.</p>} @@ -48,11 +50,11 @@ function AccountObservations({ app, connection, onClose }: { app: AggregatorAppC {refresh.error || query.data?.sync.status === "error" ? <p role="alert" className="text-sm text-destructive">Couldn’t check {name}. Last known accounts are shown.</p> : null} {query.isLoading || queryView.kind === "reconnecting" ? <p role="status" className="text-sm text-muted-foreground">Loading accounts…</p> : accounts.length ? <div className="divide-y divide-border"> {accounts.map(({ account, snapshot }) => <div key={`${snapshot.toolkit}:${account.id}`} className="py-3"> - <p className="text-sm font-medium">{account.alias || `${app.name} account`}</p> + <p className={cn("text-sm font-medium", ANALYTICS_MASK_CLASS)}>{account.alias || `${app.name} account`}</p> <p className="text-xs text-muted-foreground">{snapshot.freshness === "stale" || snapshot.errorAt || Date.now() - new Date(snapshot.checkedAt).getTime() > 5 * 60_000 || account.status === "UNVERIFIED" ? "Not verified" : account.status === "ACTIVE" ? "Connected" : account.status === "INITIATED" ? "Waiting for sign-in" : "Needs sign-in"}</p> </div>)} </div> : <p className="text-sm text-muted-foreground">{query.data?.discovery.message ?? `No connected ${app.name} accounts.`}</p>} - <p className="text-xs text-muted-foreground">Via <Link to={`/apps/${connection.id}/permissions`} onClick={onClose} className="underline underline-offset-2">“{connection.name}”</Link></p> + <p className="text-xs text-muted-foreground">Via <Link to={`/apps/${connection.id}/permissions`} onClick={onClose} className={cn("underline underline-offset-2", ANALYTICS_MASK_CLASS)}>“{connection.name}”</Link></p> <DialogFooter className="sm:justify-between"><Button variant="ghost" onClick={onClose}>Close</Button><div className="flex flex-wrap items-center gap-2"> <Button variant="ghost" disabled={!settled || refresh.isPending || query.data?.discovery.availability !== "available"} onClick={() => refresh.mutate()}>Refresh</Button> {managementUrl ? <Button asChild><a href={managementUrl} target="_blank" rel="noopener noreferrer">Open in {name}<ExternalLink className="size-4" /></a></Button> : null} diff --git a/ui/src/pages/apps/AggregatorConnectDialog.tsx b/ui/src/pages/apps/AggregatorConnectDialog.tsx index c1bfe63eb7c..073db9b5b19 100644 --- a/ui/src/pages/apps/AggregatorConnectDialog.tsx +++ b/ui/src/pages/apps/AggregatorConnectDialog.tsx @@ -9,6 +9,8 @@ import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, D import { AppLogo } from "./AppLogo"; import { remoteMcpProviders } from "@/features/connections/remote-mcp/providers"; import { ComposioAppSetup } from "./ComposioAppSetup"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; export function aggregatorAppConnectHref(route: AggregatorAppRoute, connection?: ToolConnection) { const params = new URLSearchParams({ source: route.provider, targetToolkit: route.toolkit }); @@ -37,7 +39,7 @@ export function AggregatorConnectDialog({ app, connections, initialProvider, onC else setSelected(route); } return <Dialog open onOpenChange={(open) => { if (!open) onClose(); }}> - <DialogContent> + <DialogContent className={ANALYTICS_MASK_CLASS}> <DialogHeader> <DialogTitle>{provider ? `Connect ${app.name} through ${provider.name}` : `Connect ${app.name}`}</DialogTitle> <DialogDescription className={selected?.provider === "composio" ? "sr-only" : undefined}>{selected?.provider === "composio" @@ -59,7 +61,7 @@ export function AggregatorConnectDialog({ app, connections, initialProvider, onC </button>; })}</div> : <div className="space-y-4"> {selected.provider !== "composio" ? <div className="space-y-2"><Label htmlFor="aggregator-account">{provider!.name} account</Label> - <select id="aggregator-account" value={account?.id ?? ""} onChange={event => setSelectedAccountId(event.target.value)} className="h-9 w-full rounded-md border border-input bg-background px-3 text-sm"> + <select id="aggregator-account" value={account?.id ?? ""} onChange={event => setSelectedAccountId(event.target.value)} className={cn("h-9 w-full rounded-md border border-input bg-background px-3 text-sm", ANALYTICS_MASK_CLASS)}> {existing.map(connection => <option key={connection.id} value={connection.id}>{connection.name}</option>)} </select> </div> : null} diff --git a/ui/src/pages/apps/AppDetail.tsx b/ui/src/pages/apps/AppDetail.tsx index 155e9b7d902..2f74105c8d9 100644 --- a/ui/src/pages/apps/AppDetail.tsx +++ b/ui/src/pages/apps/AppDetail.tsx @@ -80,6 +80,7 @@ import { connectionOwnerProfile, } from "./connection-owner"; import { describeError } from "@/api/errors"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; export { connectionAddress, connectionTransportLabel }; @@ -547,7 +548,7 @@ function StandardAppDetail({ renderActions, renderAgentSettings, renderConnectio if (isRetiredComposioConnection(connection)) { return <div className="max-w-4xl space-y-6 pb-12"> - <h1 className="text-xl font-semibold">{appName}</h1> + <h1 className={cn("text-xl font-semibold", ANALYTICS_MASK_CLASS)}>{appName}</h1> <section role="status" className="space-y-3 rounded-lg border border-border bg-muted p-4"> <h2 className="text-sm font-semibold">Connection retired</h2> <p className="text-sm text-muted-foreground">{RETIRED_COMPOSIO_MESSAGE}</p> @@ -605,6 +606,7 @@ function StandardAppDetail({ renderActions, renderAgentSettings, renderConnectio else setRenaming(false); }} /> + <div className={cn("space-y-10", ANALYTICS_MASK_CLASS)}> {status.tone === "attention" && connection.requiresReauthorization === false && ( <AccessRetryBanner @@ -754,6 +756,7 @@ function StandardAppDetail({ renderActions, renderAgentSettings, renderConnectio </>} </div> )} + </div> </div> ); } @@ -828,7 +831,7 @@ export function AppDetailHeader({ </form> ) : ( <div className="flex items-center gap-1.5"> - <h1 className="truncate text-xl font-bold">{appName}</h1> + <h1 className={cn("truncate text-xl font-bold", ANALYTICS_MASK_CLASS)}>{appName}</h1> <Button variant="ghost" size="icon" diff --git a/ui/src/pages/apps/ArcadeDiscoverySetup.tsx b/ui/src/pages/apps/ArcadeDiscoverySetup.tsx index 10ff913ad56..7d5d6819865 100644 --- a/ui/src/pages/apps/ArcadeDiscoverySetup.tsx +++ b/ui/src/pages/apps/ArcadeDiscoverySetup.tsx @@ -9,6 +9,7 @@ import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import type { ToolConnection } from "@paperclipai/shared"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; export function ArcadeDiscoverySetup({ connection, onClose }: { connection: ToolConnection; onClose: () => void }) { const [apiKey, setApiKey] = useState(""); @@ -21,9 +22,9 @@ export function ArcadeDiscoverySetup({ connection, onClose }: { connection: Tool }, onSuccess: onClose, }); - return <Dialog open onOpenChange={open => { if (!open && !save.isPending) onClose(); }}><DialogContent> + return <Dialog open onOpenChange={open => { if (!open && !save.isPending) onClose(); }}><DialogContent className={ANALYTICS_MASK_CLASS}> <DialogHeader><DialogTitle>Sync Arcade accounts</DialogTitle> - <DialogDescription>See apps available through “{connection.name}”. Your gateway works without account sync.</DialogDescription> + <DialogDescription>See apps available through <span className={ANALYTICS_MASK_CLASS}>“{connection.name}”</span>. Your gateway works without account sync.</DialogDescription> </DialogHeader> <form className="space-y-4" onSubmit={event => { event.preventDefault(); save.mutate(); }}> <div className="space-y-2"><Label htmlFor="arcade-discovery-key">Project API key</Label> diff --git a/ui/src/pages/apps/AssistantConnection.tsx b/ui/src/pages/apps/AssistantConnection.tsx index 743aae282cf..0d8c3dc31e0 100644 --- a/ui/src/pages/apps/AssistantConnection.tsx +++ b/ui/src/pages/apps/AssistantConnection.tsx @@ -15,6 +15,8 @@ import { OpenCodeLogoIcon } from "@/components/OpenCodeLogoIcon"; import { CompanyPatternIcon } from "@/components/CompanyPatternIcon"; import { Button } from "@/components/ui/button"; import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; export const ASSISTANT_CONNECTION_PATH = "/apps/assistant-connection"; const connectionsKey = ["mcp-connections"]; @@ -75,7 +77,7 @@ function CopyValue({ value, label }: { value: string; label: string }) { useEffect(() => { setCopied(false); setError(false); }, [value]); return <div className="space-y-2"> <div className="flex items-start gap-3 rounded-md border border-border bg-muted/30 p-3"> - <pre className="min-w-0 flex-1 overflow-x-auto whitespace-pre-wrap break-words font-mono text-xs leading-relaxed">{value}</pre> + <pre className={cn("min-w-0 flex-1 overflow-x-auto whitespace-pre-wrap break-words font-mono text-xs leading-relaxed", ANALYTICS_MASK_CLASS)}>{value}</pre> <Button type="button" variant="ghost" size="icon" className="size-8 shrink-0" aria-label={`Copy ${label}`} onClick={async () => { try { await copyTextToClipboard(value); setCopied(true); setError(false); } catch { setError(true); } diff --git a/ui/src/pages/apps/Browse.test.tsx b/ui/src/pages/apps/Browse.test.tsx index 34ad747dc3a..f0016c757c5 100644 --- a/ui/src/pages/apps/Browse.test.tsx +++ b/ui/src/pages/apps/Browse.test.tsx @@ -11,6 +11,7 @@ import { queryKeys } from "@/lib/queryKeys"; import { TooltipProvider } from "@/components/ui/tooltip"; import type { AiManagedConnectionSummary } from "@paperclipai/shared"; import type { AggregatorAppCatalogEntry } from "@paperclipai/shared/aggregator-app-catalog"; +import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils"; const aggregatorCatalogMock = vi.hoisted(() => [] as AggregatorAppCatalogEntry[]); // Counts identity normalizations made by the page (not by the catalog module itself), as a @@ -107,8 +108,8 @@ vi.mock("@/api/access", () => ({ })); vi.mock("@/lib/router", () => ({ - Link: ({ children, to }: { children: React.ReactNode; to: string }) => ( - <a href={to}>{children}</a> + Link: ({ children, to, className }: { children: React.ReactNode; to: string; className?: string }) => ( + <a href={to} className={className}>{children}</a> ), useNavigate: () => navigateMock, })); @@ -585,6 +586,8 @@ describe("Connectors landing page", () => { expect(document.querySelector('[role="dialog"]')?.textContent).toContain('“Composio account”'); expect(document.querySelector('[role="dialog"]')?.textContent).toContain("Accounts and sign-in are managed in Composio."); expect(document.querySelectorAll('[role="dialog"] a[href="/apps/conn-notion/permissions"]')).toHaveLength(1); + expect(replayLeaks("Meeting notes", document.querySelector('[role="dialog"]')!)).toEqual({ rendered: true, recorded: false }); + expect(replayLeaks("Composio account", document.querySelector('[role="dialog"]')!)).toEqual({ rendered: true, recorded: false }); expect(openNewIssueMock).not.toHaveBeenCalled(); }); @@ -1253,8 +1256,11 @@ describe("Connectors landing page", () => { expect([...row.querySelectorAll("button")].some(button => /^(Connect|Add connection|Reconnect|Finish setup)$/.test(button.textContent?.trim() ?? ""))).toBe(false); await act(() => { row.querySelector<HTMLButtonElement>('button[aria-label^="Manage "]')!.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true })); }); await flushReact(); + expect(replayLeaks("Notebook account", row)).toEqual({ rendered: true, recorded: false }); await act(() => { [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(item => item.textContent?.trim() === "Remove connection")!.click(); }); await flushReact(); + const removeDialog = document.querySelector('[role="alertdialog"]')!; + expect(replayLeaks("Notebook account", removeDialog)).toEqual({ rendered: true, recorded: false }); await act(() => { [...document.querySelectorAll("button")].find(button => button.textContent?.trim() === "Remove connection")!.click(); }); await flushReact(); expect(archiveConnectionMock).toHaveBeenCalledWith("saved-notebook"); diff --git a/ui/src/pages/apps/Browse.tsx b/ui/src/pages/apps/Browse.tsx index 8e47e351cb6..87f489b1f89 100644 --- a/ui/src/pages/apps/Browse.tsx +++ b/ui/src/pages/apps/Browse.tsx @@ -121,6 +121,8 @@ import { connectionOwnerProfile, type ConnectionOwnerProfile, } from "./connection-owner"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; type ConnectorRowModel = { key: string; @@ -1052,7 +1054,7 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne <Button variant="outline" size="sm" onClick={() => changeQuery("")}>Clear search</Button> </div> ) : ( - <div className="space-y-3" role="list" aria-label="Connector list"> + <div className={cn("space-y-3", ANALYTICS_MASK_CLASS)} role="list" aria-label="Connector list"> {showAssistantConnection && <AssistantConnectionCard onNavigate={navigate} />} {paginatedRows.map((row) => ( row.networkConnections ? <TailscaleConnectorCard key={row.key} onNavigate={navigate} /> : <ConnectorCard @@ -1113,9 +1115,9 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne } }} > - <AlertDialogContent> + <AlertDialogContent className={ANALYTICS_MASK_CLASS}> <AlertDialogHeader> - <AlertDialogTitle> + <AlertDialogTitle className={ANALYTICS_MASK_CLASS}> Remove {connectionToRemove?.accountName ?? "this"} connection? </AlertDialogTitle> <AlertDialogDescription> @@ -1284,7 +1286,7 @@ export function ConnectorCard({ <button type="button" aria-label={label} onClick={() => managed ? onManageAggregator?.(row.aggregatorApp!, managedSnapshot?.connectionId) : onConnectAggregator?.(row.aggregatorApp!)} className="rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"> <AppLogo name={providerName} brandKey={route.provider} size={16} compact /> </button> - </TooltipTrigger><TooltipContent>{label}</TooltipContent></Tooltip>; + </TooltipTrigger><TooltipContent className={ANALYTICS_MASK_CLASS}>{label}</TooltipContent></Tooltip>; })} </div> <p className="mt-0.5 text-xs text-muted-foreground"> @@ -1375,10 +1377,10 @@ export function ConnectorCard({ const managementUrl = aggregatorManagementUrl(provider, account.managementUrl ?? (typeof connection.config?.managementUrl === "string" ? connection.config?.managementUrl : null)); const manage = () => onManageAggregator?.(row.upstreamCatalogApp!, connection.id); return <ConnectionAccountRowLayout key={`${connection.id}:${snapshot.toolkit}:${account.id}`} state={state} accountName={name} - source={<><AppLogo name={providerName} brandKey={provider} size={16} compact /><span>Managed by {providerName} ·</span><button type="button" className="max-w-full truncate hover:underline" onClick={() => onNavigate(`/apps/${connection.id}/permissions`)}>“{connection.name}”</button></>} + source={<><AppLogo name={providerName} brandKey={provider} size={16} compact /><span>Managed by {providerName} ·</span><button type="button" className={cn("max-w-full truncate hover:underline", ANALYTICS_MASK_CLASS)} onClick={() => onNavigate(`/apps/${connection.id}/permissions`)}>“{connection.name}”</button></>} onOpen={manage} openLabel={`Manage ${name}`}> <DropdownMenu><DropdownMenuTrigger asChild><Button type="button" variant="ghost" size="icon-sm" aria-label={`Manage ${name} connection`}><MoreHorizontal className="h-4 w-4" /></Button></DropdownMenuTrigger> - <DropdownMenuContent align="end"> + <DropdownMenuContent className={ANALYTICS_MASK_CLASS} align="end"> {managementUrl ? <DropdownMenuItem asChild><a href={managementUrl} target="_blank" rel="noopener noreferrer">Open in {providerName}<ExternalLink className="size-4" /></a></DropdownMenuItem> : <DropdownMenuItem disabled title="Set the management URL on this gateway to open its console">Open in {providerName}<ExternalLink className="size-4" /></DropdownMenuItem>} </DropdownMenuContent> @@ -1440,7 +1442,7 @@ export function ConnectorCard({ <MoreHorizontal className="h-4 w-4" /> </Button> </DropdownMenuTrigger> - <DropdownMenuContent align="end"> + <DropdownMenuContent className={ANALYTICS_MASK_CLASS} align="end"> <DropdownMenuItem onSelect={() => onNavigate(`/apps/chat/${endpoint.id}/settings`)}> Manage </DropdownMenuItem> @@ -1540,7 +1542,7 @@ function ConnectionAccountRow({ <MoreHorizontal className="h-4 w-4" /> </Button> </DropdownMenuTrigger> - <DropdownMenuContent align="end"> + <DropdownMenuContent className={ANALYTICS_MASK_CLASS} align="end"> {account?.canSetDefault && aiDefaults && !aiDefaults.accounts.error && <AiDefaultMenuItem account={account} pending={aiDefaults.pending(account.provider)} onSelect={() => aiDefaults.choose(account)} />} <DropdownMenuItem @@ -1578,7 +1580,7 @@ function ConnectionAccountRowLayout({ state, accountName, afterName, owner, sour <div className="min-w-0"> <div className="flex min-w-0 items-center gap-2"><button type="button" - className="block max-w-full cursor-pointer truncate text-left text-sm font-medium text-foreground hover:underline focus-visible:underline" + className={cn("block max-w-full cursor-pointer truncate text-left text-sm font-medium text-foreground hover:underline focus-visible:underline", ANALYTICS_MASK_CLASS)} aria-label={openLabel} onClick={onOpen} > diff --git a/ui/src/pages/apps/ComposioAppManager.tsx b/ui/src/pages/apps/ComposioAppManager.tsx index 3d4ea8ef440..a5649fa6dcd 100644 --- a/ui/src/pages/apps/ComposioAppManager.tsx +++ b/ui/src/pages/apps/ComposioAppManager.tsx @@ -12,16 +12,18 @@ import { Button } from "@/components/ui/button"; import { Label } from "@/components/ui/label"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { describeError } from "@/api/errors"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; export function ComposioAppManager({ app, connections, initialConnectionId, onClose }: { app: AggregatorAppCatalogEntry; connections: ToolConnection[]; initialConnectionId?: string; onClose: () => void; }) { const [connectionId, setConnectionId] = useState(initialConnectionId ?? connections[0]?.id ?? ""); const connection = connections.find(candidate => candidate.id === connectionId); - return <Dialog open onOpenChange={open => { if (!open) onClose(); }}><DialogContent> + return <Dialog open onOpenChange={open => { if (!open) onClose(); }}><DialogContent className={ANALYTICS_MASK_CLASS}> <DialogHeader><DialogTitle>Manage {app.name}</DialogTitle><DialogDescription>Accounts and sign-in are managed in Composio.</DialogDescription></DialogHeader> {connections.length > 1 ? <div className="space-y-2"><Label htmlFor="composio-manage-gateway">Composio account</Label> - <select id="composio-manage-gateway" value={connectionId} onChange={event => setConnectionId(event.target.value)} className="h-9 w-full rounded-md border border-input bg-background px-3 text-sm"> + <select id="composio-manage-gateway" value={connectionId} onChange={event => setConnectionId(event.target.value)} className={cn("h-9 w-full rounded-md border border-input bg-background px-3 text-sm", ANALYTICS_MASK_CLASS)}> {connections.map(candidate => <option key={candidate.id} value={candidate.id}>{candidate.name}</option>)} </select></div> : null} {connection ? <ComposioAccountObservations key={connection.id} app={app} connection={connection} onClose={onClose} /> : <p role="alert">This Composio connection is no longer available.</p>} @@ -53,13 +55,13 @@ function ComposioAccountObservations({ app, connection, onClose }: { app: Aggreg {accountsView.kind === "error" ? <QueryErrorState error={accountsQuery.error} action="load Composio accounts" onRetry={accountsView.retry} retrying={accountsView.isFetching} /> : null} {accountsQuery.isLoading || accountsView.kind === "reconnecting" ? <p role="status" className="text-sm text-muted-foreground">Loading accounts…</p> : accounts.length === 0 ? <p className="text-sm text-muted-foreground">No connected {app.name} accounts.</p> : <div className="divide-y divide-border"> {accounts.map(({ account, snapshot }) => <div key={`${snapshot.toolkit}:${account.id}`} className="py-3"> - <p className="truncate text-sm font-medium">{account.alias || `${app.name} account`}</p> + <p className={cn("truncate text-sm font-medium", ANALYTICS_MASK_CLASS)}>{account.alias || `${app.name} account`}</p> <p className="text-xs text-muted-foreground">{snapshot.errorAt || Date.now() - new Date(snapshot.checkedAt).getTime() > 5 * 60_000 ? "Last known account · Refresh to verify" : account.status === "ACTIVE" ? "Connected" : account.status === "INITIATED" ? "Waiting for sign-in" : "Needs sign-in"}{account.isDefault ? " · Default" : ""}</p> </div>)} </div>} <div className="space-y-1 text-xs text-muted-foreground"> - <p>Via <Link to={`/apps/${connection.id}/permissions`} onClick={onClose} className="underline underline-offset-2">“{connection.name}”</Link></p> + <p>Via <Link to={`/apps/${connection.id}/permissions`} onClick={onClose} className={cn("underline underline-offset-2", ANALYTICS_MASK_CLASS)}>“{connection.name}”</Link></p> <p>Composio permissions apply to all apps on this connection.</p> </div> <DialogFooter className="sm:items-center sm:justify-between"><Button variant="ghost" onClick={onClose}>Close</Button> diff --git a/ui/src/pages/apps/ComposioAppSetup.tsx b/ui/src/pages/apps/ComposioAppSetup.tsx index 6a7c6c4722e..d9ea4d7b50e 100644 --- a/ui/src/pages/apps/ComposioAppSetup.tsx +++ b/ui/src/pages/apps/ComposioAppSetup.tsx @@ -9,6 +9,8 @@ import { Button } from "@/components/ui/button"; import { Label } from "@/components/ui/label"; import { useToast } from "@/context/ToastContext"; import { describeError } from "@/api/errors"; +import { cn } from "@/lib/utils"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; /** Provider authorization is performed by the backend; no task or agent run. */ export function ComposioAppSetup({ name, toolkit, connections, onClose, onBack, onConnectNew }: { @@ -49,7 +51,7 @@ export function ComposioAppSetup({ name, toolkit, connections, onClose, onBack, <Label htmlFor="composio-app-account">Composio account</Label> <select id="composio-app-account" value={connectionId} disabled={busy} onChange={event => { setConnectionId(event.target.value); setResult(null); setError(null); - }} className="h-9 w-full rounded-md border border-input bg-background px-3 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"> + }} className={cn("h-9 w-full rounded-md border border-input bg-background px-3 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", ANALYTICS_MASK_CLASS)}> {connections.map(candidate => <option key={candidate.id} value={candidate.id}>{candidate.name}</option>)} <option value="__new__">Connect a new account…</option> </select> diff --git a/ui/src/pages/apps/Connections.tsx b/ui/src/pages/apps/Connections.tsx index 3cca6d5cd69..75b1a2d7d19 100644 --- a/ui/src/pages/apps/Connections.tsx +++ b/ui/src/pages/apps/Connections.tsx @@ -54,6 +54,7 @@ import { type ConnectionOwnerProfile, } from "./connection-owner"; import { describeError } from "@/api/errors"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; const BROWSE_HREF = "/apps"; @@ -405,7 +406,7 @@ export function Connections() { </button> )} - <div className="overflow-hidden rounded-lg border border-border"> + <div className={cn("overflow-hidden rounded-lg border border-border", ANALYTICS_MASK_CLASS)}> <table className="w-full text-sm"> <thead> <tr className="border-b border-border bg-muted/40 text-left text-(length:--text-micro) font-semibold uppercase tracking-wide text-muted-foreground"> @@ -464,7 +465,7 @@ export function Connections() { /> <div className="min-w-0"> <div className="flex flex-wrap items-center gap-2"> - <span className="font-medium text-foreground">{row.displayName}</span> + <span className={cn("font-medium text-foreground", ANALYTICS_MASK_CLASS)}>{row.displayName}</span> <ConnectionProvenanceChip connection={row.connection} /> </div> {hint && ( @@ -553,7 +554,7 @@ export function Connections() { if (!open && !deleteConnection.isPending) setConnectionToDelete(null); }} > - <AlertDialogContent> + <AlertDialogContent className={ANALYTICS_MASK_CLASS}> <AlertDialogHeader> <AlertDialogTitle> Delete {connectionToDelete?.appName ?? "this"} connection? diff --git a/ui/src/pages/apps/ExecutorManagementSetup.tsx b/ui/src/pages/apps/ExecutorManagementSetup.tsx index 38f598c35b0..b76cfb6db7b 100644 --- a/ui/src/pages/apps/ExecutorManagementSetup.tsx +++ b/ui/src/pages/apps/ExecutorManagementSetup.tsx @@ -10,6 +10,7 @@ import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; export function ExecutorManagementSetup({ connection, onClose }: { connection: ToolConnection; onClose: () => void }) { const [url, setUrl] = useState(typeof connection.config?.managementUrl === "string" ? connection.config?.managementUrl : ""); @@ -23,8 +24,8 @@ export function ExecutorManagementSetup({ connection, onClose }: { connection: T const result = await toolsApi.syncAggregatorApps(connection.id, true); queries.setQueryData(queryKeys.tools.aggregatorApps(connection.id, userId), result); }, onSuccess: async () => { await queries.invalidateQueries({ queryKey: queryKeys.tools.connections(connection.companyId) }); onClose(); } }); - return <Dialog open onOpenChange={open => { if (!open && !save.isPending) onClose(); }}><DialogContent> - <DialogHeader><DialogTitle>Executor console</DialogTitle><DialogDescription>Choose where to manage accounts for “{connection.name}”. Include your workspace path.</DialogDescription></DialogHeader> + return <Dialog open onOpenChange={open => { if (!open && !save.isPending) onClose(); }}><DialogContent className={ANALYTICS_MASK_CLASS}> + <DialogHeader><DialogTitle>Executor console</DialogTitle><DialogDescription>Choose where to manage accounts for <span className={ANALYTICS_MASK_CLASS}>“{connection.name}”</span>. Include your workspace path.</DialogDescription></DialogHeader> <form className="space-y-4" onSubmit={event => { event.preventDefault(); save.mutate(); }}> <div className="space-y-2"><Label htmlFor="executor-console-url">Console URL</Label><Input id="executor-console-url" type="url" required value={url} onChange={event => setUrl(event.target.value)} /></div> {save.error ? <p role="alert" className="text-sm text-destructive">{describeError(save.error).body}</p> : null} diff --git a/ui/src/pages/apps/TailscaleConnector.test.tsx b/ui/src/pages/apps/TailscaleConnector.test.tsx index e4929353b5f..4350429d9c5 100644 --- a/ui/src/pages/apps/TailscaleConnector.test.tsx +++ b/ui/src/pages/apps/TailscaleConnector.test.tsx @@ -6,6 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { TailscaleConnector, TailscaleConnectorCard } from "./TailscaleConnector"; import { ApiError } from "@/api/client"; import { shouldRetryRequest } from "@/lib/query-client"; +import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils"; const fixture = vi.hoisted(() => ({ companyId: "company-1", search: "", navigate: vi.fn(), access: vi.fn(), list: vi.fn(), connect: vi.fn(), deviceLogin: vi.fn(), disconnect: vi.fn(), breadcrumbs: vi.fn() })); vi.mock("@/api/access", () => ({ accessApi: { getCurrentBoardAccess: fixture.access } })); @@ -79,6 +80,7 @@ describe("Tailscale network connector", () => { expect(fixture.list).toHaveBeenCalledWith("company-1"); expect(container.textContent).toContain("Home tailnet"); expect(container.textContent).toContain("any harness supported"); + expect(replayLeaks("Home tailnet", container)).toEqual({ rendered: true, recorded: false }); expect(container.textContent).not.toContain("Claude"); expect(container.querySelector('a[href="/company/settings/instance/environments/new?tailscale_connection=tailnet-1"]')?.textContent).toBe("Create SSH environment"); expect(fixture.connect).not.toHaveBeenCalled(); diff --git a/ui/src/pages/apps/TailscaleConnector.tsx b/ui/src/pages/apps/TailscaleConnector.tsx index 378456fe71b..cc2a1859999 100644 --- a/ui/src/pages/apps/TailscaleConnector.tsx +++ b/ui/src/pages/apps/TailscaleConnector.tsx @@ -10,6 +10,8 @@ import { Link, useSearchParams } from "@/lib/router"; import { useAuthorizationWindow } from "@/hooks/useAuthorizationWindow"; import { AppLogo } from "./AppLogo"; import { TailscaleDeviceSignIn } from "./TailscaleDeviceSignIn"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; export const TAILSCALE_CONNECTOR_PATH = "/apps/tailscale"; @@ -27,7 +29,7 @@ export function TailscaleConnectorCard({ onNavigate }: { onNavigate: (href: stri </div> <Button type="button" size="sm" variant="outline" onClick={() => onNavigate(TAILSCALE_CONNECTOR_PATH)} aria-label={`${connected.length ? "Manage" : "Connect"} Tailscale`}>{connected.length ? "Manage" : "Connect"}</Button> </div> - {connected.length > 0 && <p className="border-t border-border px-4 py-3 text-sm text-muted-foreground">{connected.map(connection => connection.name).join(", ")} · Connected</p>} + {connected.length > 0 && <p className="border-t border-border px-4 py-3 text-sm text-muted-foreground"><span className={ANALYTICS_MASK_CLASS}>{connected.map(connection => connection.name).join(", ")}</span> · Connected</p>} {connections.error && <p role="alert" className="border-t border-border px-4 py-3 text-sm text-destructive">{describeError(connections.error, { action: "load Tailscale connections" }).body}</p>} </div>; } @@ -77,13 +79,13 @@ export function TailscaleConnector() { {connections.isPending && <p className="text-sm text-muted-foreground">Loading tailnet connections…</p>} {returnError && <div role="alert" className="space-y-3"><p className="text-sm text-destructive">{returnError}</p>{retryConnection && <Button variant="outline" disabled={connect.isPending} onClick={() => start(retryConnection.id)}>Try again</Button>}</div>} {error && <div role="alert" className="space-y-3"><p className="text-sm text-destructive">{describeError(error, { action: "connect Tailscale" }).body}</p><Button variant="outline" onClick={() => void connections.refetch()}>Refresh connections</Button></div>} - <div className="divide-y divide-border">{(connections.data ?? []).map(connection => <div key={connection.id} className="flex flex-wrap items-center justify-between gap-3 py-3"> - <div className="min-w-0 flex-1 space-y-1"><p className="font-medium">{connection.name}</p><p className="text-sm text-muted-foreground">{connection.status === "connected" ? "Connected" : connection.status === "authorizing" ? "Waiting for sign-in" : connection.status === "connecting" ? "Connecting" : connection.status === "disconnected" ? "Disconnected" : connection.status === "expired" ? "Sign-in expired" : "Authorization not completed"}</p></div> + <div className={cn("divide-y divide-border", ANALYTICS_MASK_CLASS)}>{(connections.data ?? []).map(connection => <div key={connection.id} className="flex flex-wrap items-center justify-between gap-3 py-3"> + <div className="min-w-0 flex-1 space-y-1"><p className={cn("font-medium", ANALYTICS_MASK_CLASS)}>{connection.name}</p><p className="text-sm text-muted-foreground">{connection.status === "connected" ? "Connected" : connection.status === "authorizing" ? "Waiting for sign-in" : connection.status === "connecting" ? "Connecting" : connection.status === "disconnected" ? "Disconnected" : connection.status === "expired" ? "Sign-in expired" : "Authorization not completed"}</p></div> {connection.status === "connected" ? <> <Button variant="outline" asChild><Link to={`/company/settings/instance/environments/new?tailscale_connection=${encodeURIComponent(connection.id)}`}>Create SSH environment</Link></Button> - <Button variant="ghost" disabled={disconnect.isPending} onClick={() => disconnect.mutate(connection.id)}>Disconnect {connection.name}</Button> + <Button variant="ghost" disabled={disconnect.isPending} onClick={() => disconnect.mutate(connection.id)}>Disconnect <span className={ANALYTICS_MASK_CLASS}>{connection.name}</span></Button> </> : connection.status === "authorizing" ? <TailscaleDeviceSignIn key={`${selectedCompanyId}:${connection.id}`} connection={connection} cancel={() => disconnect.mutate(connection.id)} disabled={disconnect.isPending} /> - : <Button variant="outline" disabled={connect.isPending} onClick={() => start(connection.id)}>Reconnect {connection.name}</Button>} + : <Button variant="outline" disabled={connect.isPending} onClick={() => start(connection.id)}>Reconnect <span className={ANALYTICS_MASK_CLASS}>{connection.name}</span></Button>} </div>)}</div> <footer className="flex items-center justify-between gap-3 border-t border-border pt-4"> <Button variant="ghost" asChild><Link to="/apps">Back to connectors</Link></Button> diff --git a/ui/src/pages/apps/app-detail/ActionTestDialog.test.tsx b/ui/src/pages/apps/app-detail/ActionTestDialog.test.tsx index 87ef3ee641d..63f270db535 100644 --- a/ui/src/pages/apps/app-detail/ActionTestDialog.test.tsx +++ b/ui/src/pages/apps/app-detail/ActionTestDialog.test.tsx @@ -7,6 +7,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { ToolCatalogEntry } from "@paperclipai/shared"; import { ActionTestDialog, errorHints } from "./ActionTestDialog"; +import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils"; const listTestAgentsMock = vi.hoisted(() => vi.fn()); const getTestAgentAccessMock = vi.hoisted(() => vi.fn()); @@ -332,8 +333,11 @@ describe("Permissions action Test dialog", () => { expect(document.body.querySelector("table")?.textContent).toContain("Q4 launch"); expect(document.body.textContent).not.toContain("structuredContent"); const raw = [...document.body.querySelectorAll("button")].find((button) => button.textContent?.trim() === "Show raw response"); + expect(replayLeaks("Customer onboarding", document.body)).toEqual({ rendered: true, recorded: false }); await act(() => raw!.click()); expect(document.body.textContent).toContain("structuredContent"); + expect(replayLeaks("structuredContent", document.body)).toEqual({ rendered: true, recorded: false }); + expect(replayLeaks("Customer onboarding", document.body).recorded).toBe(false); }); it("parses JSON text when structured content is absent", async () => { diff --git a/ui/src/pages/apps/app-detail/ActionTestDialog.tsx b/ui/src/pages/apps/app-detail/ActionTestDialog.tsx index ce974d67416..859f7381f8e 100644 --- a/ui/src/pages/apps/app-detail/ActionTestDialog.tsx +++ b/ui/src/pages/apps/app-detail/ActionTestDialog.tsx @@ -45,6 +45,7 @@ import { } from "@/components/JsonSchemaForm"; import { cn, relativeTime } from "@/lib/utils"; import { appTabHref } from "../app-tabs"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; // --------------------------------------------------------------------------- // Small format helpers @@ -131,7 +132,7 @@ export function ActionTestDialog({ return ( <Dialog open={open} onOpenChange={onOpenChange}> - <DialogContent className="max-h-(--sz-85vh) overflow-y-auto sm:max-w-2xl"> + <DialogContent className={cn("max-h-(--sz-85vh) overflow-y-auto sm:max-w-2xl", ANALYTICS_MASK_CLASS)}> <DialogHeader> <DialogTitle>Test {title}</DialogTitle> <DialogDescription> @@ -264,7 +265,7 @@ function AgentPicker({ <ChevronsUpDown className="h-3.5 w-3.5 text-muted-foreground" /> </button> </PopoverTrigger> - <PopoverContent align="start" className="w-80 p-0" disablePortal> + <PopoverContent align="start" className={cn("w-80 p-0", ANALYTICS_MASK_CLASS)} disablePortal> <div className="border-b border-border p-2"> <div className="relative"> <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" /> @@ -862,7 +863,7 @@ function AllowedResult({ const value = outcome.result.result; const preview = resultPreview(value); return ( - <div className="rounded-md border border-emerald-500/40 bg-emerald-500/5 p-4"> + <div className={cn("rounded-md border border-emerald-500/40 bg-emerald-500/5 p-4", ANALYTICS_MASK_CLASS)}> <div className="flex items-center gap-2"> <Check className="h-4 w-4 text-emerald-600 dark:text-emerald-400" /> <span className="text-sm font-medium text-foreground">{successHeadline(preview.summary, entry, appName)}</span> @@ -948,7 +949,7 @@ function PrettyPreview({ value }: { value: unknown }) { ); } if (typeof value === "string") { - return <pre className="max-h-64 overflow-auto whitespace-pre-wrap rounded-md border border-border bg-background p-3 text-xs text-foreground">{value}</pre>; + return <pre className={cn("max-h-64 overflow-auto whitespace-pre-wrap rounded-md border border-border bg-background p-3 text-xs text-foreground", ANALYTICS_MASK_CLASS)}>{value}</pre>; } if (value && typeof value === "object" && !Array.isArray(value)) { return ( @@ -963,7 +964,7 @@ function PrettyPreview({ value }: { value: unknown }) { ); } return ( - <pre className="max-h-64 overflow-auto rounded-md border border-border bg-background p-3 text-xs text-foreground"> + <pre className={cn("max-h-64 overflow-auto rounded-md border border-border bg-background p-3 text-xs text-foreground", ANALYTICS_MASK_CLASS)}> {safeStringify(collapseDeep(value, 2))} </pre> ); @@ -1036,7 +1037,7 @@ function RawResponseDisclosure({ value, initiallyOpen = false }: { value: unknow {showRaw ? "Hide raw response" : "Show raw response"} </button> {showRaw && ( - <pre className="mt-2 max-h-64 overflow-auto rounded-md border border-border bg-background p-3 text-xs text-foreground"> + <pre className={cn("mt-2 max-h-64 overflow-auto rounded-md border border-border bg-background p-3 text-xs text-foreground", ANALYTICS_MASK_CLASS)}> {safeStringify(value)} </pre> )} @@ -1061,7 +1062,7 @@ function ErrorResult({ const hints = errorHints(toolErrorMessage, error.reasonCode); const needsReconnect = isReconnectError(error.reasonCode); return ( - <div className="rounded-md border border-amber-500/40 bg-amber-500/5 p-4"> + <div className={cn("rounded-md border border-amber-500/40 bg-amber-500/5 p-4", ANALYTICS_MASK_CLASS)}> <div className="flex items-center gap-2"> <AlertTriangle className="h-4 w-4 text-amber-600 dark:text-amber-400" /> <span className="text-sm font-medium text-foreground">It didn't work.</span> diff --git a/ui/src/pages/apps/app-detail/ConnectedAggregatorApps.tsx b/ui/src/pages/apps/app-detail/ConnectedAggregatorApps.tsx index 45b45a2844d..57aa5638d68 100644 --- a/ui/src/pages/apps/app-detail/ConnectedAggregatorApps.tsx +++ b/ui/src/pages/apps/app-detail/ConnectedAggregatorApps.tsx @@ -10,6 +10,7 @@ import { QueryErrorState, useQueryView } from "@/components/QueryView"; import { Button } from "@/components/ui/button"; import { queryKeys } from "@/lib/queryKeys"; import { AppLogo } from "../AppLogo"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; const catalogBySlug = new Map(AGGREGATOR_APP_CATALOG.map(app => [app.slug, app])); @@ -89,7 +90,7 @@ export function ConnectedAggregatorApps({ connection }: { connection: ToolConnec <div className="min-w-0 flex-1"> <p className="truncate text-sm font-medium" title={app.appName}>{app.appName}</p> {accounts.length > 1 ? <p className="text-xs text-muted-foreground">{accounts.length} accounts</p> - : accounts[0]?.alias ? <p className="truncate text-xs text-muted-foreground">{accounts[0].alias}</p> : null} + : accounts[0]?.alias ? <p className={`truncate text-xs text-muted-foreground ${ANALYTICS_MASK_CLASS}`}>{accounts[0].alias}</p> : null} </div> <span className="flex shrink-0 items-center gap-1.5 text-xs text-muted-foreground"> {connected ? <Check className="size-4 text-(--status-task-done)" aria-hidden="true" /> : null} diff --git a/ui/src/pages/apps/app-detail/IdentitiesSection.tsx b/ui/src/pages/apps/app-detail/IdentitiesSection.tsx index 7edb74d16e2..97fa89d5d5f 100644 --- a/ui/src/pages/apps/app-detail/IdentitiesSection.tsx +++ b/ui/src/pages/apps/app-detail/IdentitiesSection.tsx @@ -44,6 +44,7 @@ import { personalGrantFor, type GrantStatusTone, } from "../connection-identity"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; const STATUS_CHIP: Record<GrantStatusTone, string> = { connected: brandChipBadge.green, @@ -179,7 +180,7 @@ export function IdentitiesSection({ <h2 className="text-sm font-semibold text-foreground">GitHub identity</h2> <p className="text-sm text-muted-foreground">This agent uses this GitHub account for everyone’s work, instead of the person giving instructions.</p> <IdentityRow - title={github ? `@${github.login}` : "Dedicated GitHub account"} + title={github ? <span className={ANALYTICS_MASK_CLASS}>@{github.login}</span> : "Dedicated GitHub account"} status={agentGrant?.status ?? null} detail={dedicatedAgent ? ( <Link @@ -312,7 +313,7 @@ function GitHubConnectionSummary({ <div className="divide-y divide-border border-y border-border"> <div className="py-3"> <div className="text-sm font-medium text-foreground">GitHub account</div> - <a className="text-sm text-muted-foreground hover:underline" href={`https://github.com/${encodeURIComponent(github.login)}`} target="_blank" rel="noreferrer"> + <a className={cn("text-sm text-muted-foreground hover:underline", ANALYTICS_MASK_CLASS)} href={`https://github.com/${encodeURIComponent(github.login)}`} target="_blank" rel="noreferrer"> @{github.login} </a> </div> @@ -354,7 +355,7 @@ function GitHubConnectionSummary({ </div> </div> {github.repositories ? ( - github.repositories.length ? <ul aria-label="Accessible GitHub repositories" tabIndex={0} className="max-h-(--sz-github-repository-list) space-y-2 overflow-y-auto text-sm"> + github.repositories.length ? <ul aria-label="Accessible GitHub repositories" tabIndex={0} className={cn("max-h-(--sz-github-repository-list) space-y-2 overflow-y-auto text-sm", ANALYTICS_MASK_CLASS)}> {github.repositories.map((repository) => ( <li key={repository.id}> <a className="flex items-center gap-2 text-muted-foreground hover:underline" href={`https://github.com/${repository.fullName.split("/").map(encodeURIComponent).join("/")}`} target="_blank" rel="noreferrer"> @@ -438,7 +439,7 @@ function HumanAccessCards({ /> {connectedName && status !== null ? ( <div className="flex flex-wrap items-center gap-2"> - <Identity name={connectedName} avatarUrl={connectedImage} /> + <Identity name={connectedName} avatarUrl={connectedImage} className={ANALYTICS_MASK_CLASS} /> {status === "active" ? null : <StatusText status={status} />} </div> ) : null} @@ -454,7 +455,7 @@ function IdentityRow({ actions, }: { id?: string; - title: string; + title: ReactNode; status: ConnectionGrant["status"] | null; detail: ReactNode; actions: ReactNode; @@ -508,10 +509,10 @@ export function AudienceDialog({ return ( <Dialog open onOpenChange={(open) => { if (!open) onCancel(); }}> - <DialogContent> + <DialogContent className={ANALYTICS_MASK_CLASS}> <DialogHeader> <DialogTitle>Who can use this identity</DialogTitle> - <DialogDescription> + <DialogDescription className={ANALYTICS_MASK_CLASS}> {grantAccountLabel(grant)} · {appName} </DialogDescription> </DialogHeader> @@ -622,9 +623,9 @@ export function RevokeGrantDialog({ return ( <AlertDialog open onOpenChange={(open) => { if (!open) onCancel(); }}> - <AlertDialogContent> + <AlertDialogContent className={ANALYTICS_MASK_CLASS}> <AlertDialogHeader> - <AlertDialogTitle>{title}</AlertDialogTitle> + <AlertDialogTitle className={ANALYTICS_MASK_CLASS}>{title}</AlertDialogTitle> <AlertDialogDescription>{description ?? body}</AlertDialogDescription> </AlertDialogHeader> {children} diff --git a/ui/src/pages/apps/app-detail/PermissionsPanel.tsx b/ui/src/pages/apps/app-detail/PermissionsPanel.tsx index 388cc481f6e..96056d2d2bd 100644 --- a/ui/src/pages/apps/app-detail/PermissionsPanel.tsx +++ b/ui/src/pages/apps/app-detail/PermissionsPanel.tsx @@ -21,6 +21,7 @@ function NoIcon() { return null; } import type { AccessDraft, AppDetailSectionProps } from "./types"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; type ActionPermission = "off" | "ask" | "allowed"; type ActionKindFilter = "all" | "read" | "write"; @@ -568,7 +569,7 @@ const ActionRow = memo(function ActionRow({ <Icon className="h-3.5 w-3.5" /> </button> </TooltipTrigger> - <TooltipContent side="top"> + <TooltipContent className={ANALYTICS_MASK_CLASS} side="top"> <span className="font-medium">{option.label}</span> — {option.description} </TooltipContent> </Tooltip> diff --git a/ui/src/pages/apps/app-detail/StoredContentDeletion.tsx b/ui/src/pages/apps/app-detail/StoredContentDeletion.tsx index b7b46f24210..85350e614ce 100644 --- a/ui/src/pages/apps/app-detail/StoredContentDeletion.tsx +++ b/ui/src/pages/apps/app-detail/StoredContentDeletion.tsx @@ -18,6 +18,7 @@ import { import { useToast } from "@/context/ToastContext"; import { queryKeys } from "@/lib/queryKeys"; import { relativeTime } from "@/lib/utils"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; function plural(count: number, one: string, many: string) { return `${count.toLocaleString()} ${count === 1 ? one : many}`; @@ -123,7 +124,7 @@ export function StoredContentDeletionDialog({ return ( <AlertDialog open onOpenChange={(next) => { if (!next) onClose(); }}> - <AlertDialogContent> + <AlertDialogContent className={ANALYTICS_MASK_CLASS}> <AlertDialogHeader> <AlertDialogTitle>{`Delete data read through ${appName}?`}</AlertDialogTitle> <AlertDialogDescription> diff --git a/ui/src/pages/apps/chat/ChatConversationList.tsx b/ui/src/pages/apps/chat/ChatConversationList.tsx index ae3f51f34c9..b1fd0fbaea0 100644 --- a/ui/src/pages/apps/chat/ChatConversationList.tsx +++ b/ui/src/pages/apps/chat/ChatConversationList.tsx @@ -5,6 +5,8 @@ import { StatusBadge } from "@/components/StatusBadge"; import { Link } from "@/lib/router"; import { formatDateTime } from "@/lib/utils"; import { AppLogo } from "../AppLogo"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; export function conversationDestination( row: ChatConversation, @@ -87,12 +89,12 @@ export function ChatConversationList({ href={row.externalUrl} target="_blank" rel="noreferrer" - className="break-words hover:text-foreground hover:underline" + className={cn("break-words hover:text-foreground hover:underline", ANALYTICS_MASK_CLASS)} > {conversationDestination(row, provider)} </a> ) : ( - <span className="break-all">{row.externalLabel}</span> + <span className={cn("break-all", ANALYTICS_MASK_CLASS)}>{row.externalLabel}</span> )} {row.updatedAt && ( <time dateTime={row.updatedAt}> diff --git a/ui/src/pages/apps/chat/ChatEndpointDetail.replay.test.tsx b/ui/src/pages/apps/chat/ChatEndpointDetail.replay.test.tsx new file mode 100644 index 00000000000..b3e2544c92e --- /dev/null +++ b/ui/src/pages/apps/chat/ChatEndpointDetail.replay.test.tsx @@ -0,0 +1,59 @@ +// @vitest-environment jsdom +import { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { ChatEndpointDetail } from "./ChatEndpointDetail"; +import { TooltipProvider } from "@/components/ui/tooltip"; +import { isBlockedFromReplay, replayLeaks } from "@/lib/analytics/replay-recording.test-utils"; + +const mocks = vi.hoisted(() => ({ + get: vi.fn(), listPrincipals: vi.fn(), createLinkIntent: vi.fn(), agents: vi.fn(), navigate: vi.fn(), +})); +vi.mock("@/api/chatEndpoints", () => ({ chatEndpointsApi: { + get: mocks.get, listPrincipals: mocks.listPrincipals, createLinkIntent: mocks.createLinkIntent, + listConversations: vi.fn().mockResolvedValue([]), listActivityPage: vi.fn().mockResolvedValue({ items: [], nextCursor: null }), + listResources: vi.fn().mockResolvedValue([]), +} })); +vi.mock("@/api/agents", () => ({ agentsApi: { list: mocks.agents } })); +vi.mock("./SlackTestMessageButton", () => ({ SlackTestMessageButton: () => null })); +vi.mock("@/context/BreadcrumbContext", () => ({ useBreadcrumbs: () => ({ setBreadcrumbs: () => {} }) })); +vi.mock("@/context/ToastContext", () => ({ useToast: () => ({ pushToast: () => {} }) })); +vi.mock("@/lib/router", () => ({ + useLocation: () => ({ state: null }), + useParams: () => ({ endpointId: "slack-bot", tab: "access" }), useNavigate: () => mocks.navigate, + Link: ({ children, to, ...props }: React.ComponentProps<"a"> & { to: string }) => <a href={to} {...props}>{children}</a>, + Navigate: () => null, +})); + +let root: Root; +let container: HTMLDivElement; +let client: QueryClient; +beforeEach(() => { + vi.clearAllMocks(); + mocks.get.mockResolvedValue({ id: "slack-bot", companyId: "company", provider: "slack", assignedAgentId: "maya", assignedAgentName: "Maya", + allowUnlinkedPeople: false, status: "active", providerAccountLabel: "Globex Workspace", setup: { step: "complete" } }); + mocks.agents.mockResolvedValue([{ id: "maya", name: "Maya", status: "idle" }]); + mocks.listPrincipals.mockResolvedValue([ + { id: "l1", principalId: "p1", status: "linked", externalLabel: "jane.doe (Globex)", paperclipUserLabel: "Jane Doe" }, + { id: "l2", principalId: "p2", status: "pending", externalLabel: "sam@globex.com", paperclipUserLabel: null }, + ]); + mocks.createLinkIntent.mockResolvedValue({ confirmationUrl: "/chat-link/confirm?token=ctok_live_9f2a" }); + container = document.createElement("div"); document.body.append(container); root = createRoot(container); + client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }); +}); +afterEach(async () => { await act(async () => root.unmount()); client.clear(); container.remove(); }); + +it("masks linked people and blocks the identity confirmation link in session replay", async () => { + await act(async () => root.render(<QueryClientProvider client={client}><TooltipProvider><ChatEndpointDetail /></TooltipProvider></QueryClientProvider>)); + await vi.waitFor(() => expect(container.textContent).toContain("sam@globex.com"), { timeout: 3000 }); + expect(replayLeaks("Globex Workspace", container)).toEqual({ rendered: true, recorded: false }); + expect(replayLeaks("Jane Doe", container)).toEqual({ rendered: true, recorded: false }); + expect(replayLeaks("jane.doe (Globex)", container)).toEqual({ rendered: true, recorded: false }); + expect(replayLeaks("sam@globex.com", container)).toEqual({ rendered: true, recorded: false }); + const create = [...container.querySelectorAll("button")].find((button) => button.textContent?.includes("Create confirmation link")); + await act(async () => create!.click()); + await vi.waitFor(() => expect(container.textContent).toContain("ctok_live_9f2a"), { timeout: 3000 }); + expect(isBlockedFromReplay("ctok_live_9f2a", container)).toBe(true); + expect(replayLeaks("Confirm sam@globex.com", container)).toEqual({ rendered: true, recorded: false }); +}); diff --git a/ui/src/pages/apps/chat/ChatEndpointDetail.tsx b/ui/src/pages/apps/chat/ChatEndpointDetail.tsx index 476173a6cb9..f0ae77b72b1 100644 --- a/ui/src/pages/apps/chat/ChatEndpointDetail.tsx +++ b/ui/src/pages/apps/chat/ChatEndpointDetail.tsx @@ -72,6 +72,8 @@ import { queryKeys } from "@/lib/queryKeys"; import { copyTextToClipboard } from "@/lib/clipboard"; import { Link, Navigate, useLocation, useNavigate, useParams } from "@/lib/router"; import { describeError } from "@/api/errors"; +import { ANALYTICS_MASK_CLASS, ANALYTICS_NO_CAPTURE_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; const tabs = ["settings", "access", "reviews", "conversations", "activity"] as const; type ChatTab = (typeof tabs)[number]; @@ -341,7 +343,7 @@ export function ChatEndpointDetail() { {endpoint.provider === "speko" && <AppLogo name="Speko" brandKey="speko" size={36} />} {endpoint.provider === "github" ? (endpoint.botLabel ?? endpoint.assignedAgentName) : endpoint.assignedAgentName}{endpoint.provider === "speko" ? " in Speko" : ""} </h1> - <p className="mt-1 flex flex-wrap items-center gap-2 text-sm text-muted-foreground"> + <p className={cn("mt-1 flex flex-wrap items-center gap-2 text-sm text-muted-foreground", ANALYTICS_MASK_CLASS)}> {endpoint.provider === "github" ? <><AppLogo name="GitHub" brandKey="github" compact className="size-4! rounded-sm bg-transparent" /><Link to={`/agents/${endpoint.assignedAgentId}`} className="hover:underline">{endpoint.assignedAgentName}</Link>{endpoint.providerAccountLabel && <span>· {endpoint.providerAccountLabel}</span>}</> : endpoint.providerAccountLabel ?? (endpoint.provider === "agentmail" ? endpoint.botExternalId ?? "Email connection" : "Chat connection")} </p> {endpoint.provider === "github" && <div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1"> @@ -379,6 +381,7 @@ export function ChatEndpointDetail() { {endpoint.status !== "active" && <StatusBadge status={endpoint.status} className={endpoint.provider === "speko" ? "text-foreground" : undefined} />} </div> </header> + <div className={cn("space-y-6", ANALYTICS_MASK_CLASS)}> {endpoint.provider === "github" && <GitHubConnectionRecoveryNotice endpoint={endpoint} />} {activeTab === "settings" && endpoint.provider === "speko" && endpoint.status === "active" && <div className="space-y-6"><SpekoPhoneCallback companyId={endpoint.companyId} endpointId={endpoint.id} /><SpekoPhoneLine companyId={endpoint.companyId} endpointId={endpoint.id} /><SpekoIncomingCalls companyId={endpoint.companyId} endpointId={endpoint.id} agentId={endpoint.assignedAgentId} /></div>} {endpoint.provider === "slack" && <SlackTestMessageButton key={endpoint.id} endpointId={endpoint.id} />} @@ -422,6 +425,7 @@ export function ChatEndpointDetail() { onCloseAutoFocus={() => heading.current?.focus()} /> )} + </div> </div> ); } @@ -558,7 +562,7 @@ function Settings({ {destinationResources.map((resource) => ( <div key={resource.id} className="py-3 space-y-3"> <div className="flex items-center gap-3"> - <div className="min-w-0 flex-1"> + <div className={cn("min-w-0 flex-1", ANALYTICS_MASK_CLASS)}> <p className="truncate text-sm font-medium"> {resource.label} </p> @@ -746,7 +750,7 @@ function Access({ <h2 className="text-lg font-semibold">People</h2> {endpoint.provider === "slack" && <Dialog> <DialogTrigger asChild><Button>Invite people</Button></DialogTrigger> - <DialogContent> + <DialogContent className={ANALYTICS_MASK_CLASS}> <DialogHeader> <DialogTitle>Invite people to talk to {endpoint.assignedAgentName}</DialogTitle> <DialogDescription>Share these instructions with someone in your Slack workspace.</DialogDescription> @@ -774,9 +778,9 @@ function Access({ <p className="text-sm text-muted-foreground">People with linked accounts use their own Paperclip permissions. <Link className="underline underline-offset-4" to="/company/settings/members">Manage members</Link></p> {confirmationUrl && ( <div className="space-y-2 border-y border-border py-3"> - <p className="text-sm font-medium">Confirm {confirmationFor ?? "this account"}</p> + <p className={cn("text-sm font-medium", ANALYTICS_MASK_CLASS)}>Confirm {confirmationFor ?? "this account"}</p> <p className="text-xs text-muted-foreground">Share only with this person. They must sign in and confirm their own account.</p> - <p className="break-all text-xs text-muted-foreground"> + <p className={cn("break-all text-xs text-muted-foreground", ANALYTICS_NO_CAPTURE_CLASS)}> {confirmationUrl} </p> <Button @@ -821,7 +825,7 @@ function Access({ {link.paperclipUserImage && <AvatarImage src={link.paperclipUserImage} alt="" />} <AvatarFallback>{deriveInitials(link.paperclipUserLabel ?? link.externalLabel)}</AvatarFallback> </Avatar> - <div className="min-w-0"> + <div className={cn("min-w-0", ANALYTICS_MASK_CLASS)}> <p className="truncate text-sm" title={link.paperclipUserLabel ?? link.externalLabel}>{link.paperclipUserLabel ?? link.externalLabel}</p> {(link.status !== "linked" || link.externalLabel !== link.paperclipUserLabel) && <p className="text-xs text-muted-foreground"> {link.status === "revoked" ? "Disconnected" : link.status === "linked" @@ -1311,7 +1315,7 @@ function Activity({ open={resolutionItem !== null} onOpenChange={(open) => !open && setResolutionItem(null)} > - <AlertDialogContent> + <AlertDialogContent className={ANALYTICS_MASK_CLASS}> <AlertDialogHeader> <AlertDialogTitle> {resolutionItem?.actionType === "slash_task_start" @@ -1399,7 +1403,7 @@ function Activity({ </AlertDialogContent> </AlertDialog> <AlertDialog open={removeOpen} onOpenChange={setRemoveOpen}> - <AlertDialogContent> + <AlertDialogContent className={ANALYTICS_MASK_CLASS}> <AlertDialogHeader> <AlertDialogTitle>Remove this connection?</AlertDialogTitle> <AlertDialogDescription> diff --git a/ui/src/pages/apps/chat/ChatEndpointSetup.tsx b/ui/src/pages/apps/chat/ChatEndpointSetup.tsx index 2f546d2a497..af200181ddd 100644 --- a/ui/src/pages/apps/chat/ChatEndpointSetup.tsx +++ b/ui/src/pages/apps/chat/ChatEndpointSetup.tsx @@ -56,6 +56,8 @@ import { readGitHubPrivateKeyFile, } from "./github-private-key-file"; import { describeError } from "@/api/errors"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; const providerNames: Record<ChatProvider, string> = { speko: "Speko", @@ -1618,7 +1620,7 @@ function ProviderConnectStep({ View Slack App Manifest </Button> </DialogTrigger> - <DialogContent className="sm:max-w-2xl"> + <DialogContent className={cn("sm:max-w-2xl", ANALYTICS_MASK_CLASS)}> <DialogHeader> <DialogTitle>Slack app manifest</DialogTitle> <DialogDescription> diff --git a/ui/src/pages/apps/chat/ChatIdentityConfirm.tsx b/ui/src/pages/apps/chat/ChatIdentityConfirm.tsx index dfc83b7c5dd..f6c8054d154 100644 --- a/ui/src/pages/apps/chat/ChatIdentityConfirm.tsx +++ b/ui/src/pages/apps/chat/ChatIdentityConfirm.tsx @@ -8,6 +8,8 @@ import { Button } from "@/components/ui/button"; import { QueryErrorState, useQueryView } from "@/components/QueryView"; import { queryKeys } from "@/lib/queryKeys"; import { Navigate, useSearchParams } from "@/lib/router"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; const providerNames: Record<ChatProvider, string> = { speko: "Speko", @@ -101,7 +103,7 @@ export function ChatIdentityConfirm() { <CheckCircle2 className="h-8 w-8" /> <div> <h1 className="text-xl font-bold">Identity linked</h1> - <p className="mt-1 text-sm text-muted-foreground"> + <p className={cn("mt-1 text-sm text-muted-foreground", ANALYTICS_MASK_CLASS)}> Future messages from {identity.externalLabel} use your current Paperclip permissions in {identity.companyName}. </p> @@ -116,7 +118,7 @@ export function ChatIdentityConfirm() { <p className="text-sm text-muted-foreground">{identity.companyName}</p> <h1 className="mt-1 text-xl font-bold">Link your external identity</h1> </div> - <dl className="divide-y divide-border border-y border-border"> + <dl className={cn("divide-y divide-border border-y border-border", ANALYTICS_MASK_CLASS)}> <div className="flex items-center justify-between gap-4 py-3"> <dt className="text-sm text-muted-foreground">Provider</dt> <dd className="text-sm font-medium"> @@ -125,7 +127,7 @@ export function ChatIdentityConfirm() { </div> <div className="flex items-center justify-between gap-4 py-3"> <dt className="text-sm text-muted-foreground">External identity</dt> - <dd className="text-right text-sm font-medium"> + <dd className={cn("text-right text-sm font-medium", ANALYTICS_MASK_CLASS)}> {identity.externalLabel} {identity.externalDetail ? ` · ${identity.externalDetail}` : ""} </dd> diff --git a/ui/src/pages/apps/chat/EmailEndpointSetup.tsx b/ui/src/pages/apps/chat/EmailEndpointSetup.tsx index b4aeca4eaf6..9a0c4ed3034 100644 --- a/ui/src/pages/apps/chat/EmailEndpointSetup.tsx +++ b/ui/src/pages/apps/chat/EmailEndpointSetup.tsx @@ -51,6 +51,8 @@ import type { EmailEndpointSummary, } from "@paperclipai/shared"; import { companyProjectsQuery } from "@/lib/company-projects-query"; +import { cn } from "@/lib/utils"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; const selectClass = "w-full rounded-md border border-input bg-background px-3 py-2 text-sm"; @@ -382,13 +384,13 @@ function EmailEndpointSetupForm({ companyId }: { companyId: string }) { <Input id="email-name" className="min-w-0" value={username} maxLength={64} autoComplete="off" spellCheck={false} disabled={busy} aria-invalid={!!addressError} aria-describedby={addressError ? "email-address-error" : "email-address-status"} onChange={event => { setUsername(event.target.value.toLowerCase()); setup.reset(); }} /> - <select id="email-domain" aria-label="Email domain" className={`${selectClass} max-w-1/2 shrink-0`} value={domain} + <select id="email-domain" aria-label="Email domain" className={cn(selectClass, "max-w-1/2 shrink-0", ANALYTICS_MASK_CLASS)} value={domain} disabled={busy || !inspected.data} onChange={event => { setDomainSelected(true); setDomain(event.target.value); setup.reset(); }}> {[...new Set([...customDomains, "agentmail.to", domain])] .map(value => <option key={value} value={value}>@{value}</option>)} </select> </div> - </> : <select id="email-existing" className={selectClass} value={pendingAddress ?? inboxId} disabled={busy || scopedKey || !!pendingAddress} + </> : <select id="email-existing" className={cn(selectClass, ANALYTICS_MASK_CLASS)} value={pendingAddress ?? inboxId} disabled={busy || scopedKey || !!pendingAddress} aria-invalid={!!addressError} aria-describedby={addressError ? "email-address-error" : undefined} onChange={event => { setInboxId(event.target.value); setup.reset(); }}> <option value="">Choose an inbox</option> @@ -456,7 +458,7 @@ function EmailEndpointSetupForm({ companyId }: { companyId: string }) { </div> </div>} <Dialog open={trustOpen} onOpenChange={setTrustOpen}> - <DialogContent className="max-h-screen overflow-y-auto sm:max-w-2xl"> + <DialogContent className={cn("max-h-screen overflow-y-auto sm:max-w-2xl", ANALYTICS_MASK_CLASS)}> <DialogHeader> <DialogTitle>Trust settings · {chosen?.name}</DialogTitle> <DialogDescription> diff --git a/ui/src/pages/apps/chat/GitHubBotConfiguration.tsx b/ui/src/pages/apps/chat/GitHubBotConfiguration.tsx index 8ed4286eec0..98defa04506 100644 --- a/ui/src/pages/apps/chat/GitHubBotConfiguration.tsx +++ b/ui/src/pages/apps/chat/GitHubBotConfiguration.tsx @@ -51,6 +51,8 @@ import { TooltipTrigger, } from "@/components/ui/tooltip"; import { describeError } from "@/api/errors"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; export const githubSelectClass = "w-full rounded-md border border-input bg-background px-3 py-2 text-sm"; @@ -82,7 +84,7 @@ function GitHubHelp({ <HelpCircle className="size-4" /> </button> </TooltipTrigger> - <TooltipContent className="max-w-xs">{children}</TooltipContent> + <TooltipContent className={cn("max-w-xs", ANALYTICS_MASK_CLASS)}>{children}</TooltipContent> </Tooltip> ); } @@ -707,7 +709,7 @@ export function GitHubAccessEditor({ className="flex flex-wrap items-center gap-x-4 gap-y-3 py-4" > <div className="min-w-0 flex-1 basis-32"> - <p className="break-words text-sm font-medium">@{person.login}</p> + <p className={cn("break-words text-sm font-medium", ANALYTICS_MASK_CLASS)}>@{person.login}</p> <p className="text-xs text-muted-foreground"> {person.kind === "guest" ? `Sponsored by ${memberName(person.sponsorUserId)}` @@ -754,7 +756,7 @@ export function GitHubAccessEditor({ <MoreHorizontal className="size-4" /> </Button> </DropdownMenuTrigger> - <DropdownMenuContent align="end"> + <DropdownMenuContent className={ANALYTICS_MASK_CLASS} align="end"> {removable && ( <DropdownMenuItem onClick={() => removePerson(person)}> Remove access @@ -956,7 +958,7 @@ export function GitHubAccessEditor({ if (!open) setDialog(null); }} > - <DialogContent> + <DialogContent className={ANALYTICS_MASK_CLASS}> <DialogHeader> <DialogTitle> {dialog === "member" @@ -1053,7 +1055,7 @@ export function GitHubAccessEditor({ /> </div> {candidate && ( - <p role="status" className="text-sm"> + <p role="status" className={cn("text-sm", ANALYTICS_MASK_CLASS)}> {configuration.people.some( (p) => p.githubUserId === candidate.githubUserId, ) || diff --git a/ui/src/pages/apps/chat/GitHubBotManagement.tsx b/ui/src/pages/apps/chat/GitHubBotManagement.tsx index 1a590e0609e..1851205283e 100644 --- a/ui/src/pages/apps/chat/GitHubBotManagement.tsx +++ b/ui/src/pages/apps/chat/GitHubBotManagement.tsx @@ -39,6 +39,7 @@ import { } from "./GitHubBotConfiguration"; import { ChatExecutionDefaults } from "./ChatExecutionDefaults"; import { describeError } from "@/api/errors"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; export function GitHubRepositoryAccess({ endpointId, @@ -96,7 +97,7 @@ export function GitHubRepositoryAccess({ <MoreHorizontal className="size-4" /> </Button> </DropdownMenuTrigger> - <DropdownMenuContent align="end"> + <DropdownMenuContent className={ANALYTICS_MASK_CLASS} align="end"> <DropdownMenuItem asChild> <a href={managementUrl} target="_blank" rel="noreferrer"> Manage on GitHub diff --git a/ui/src/pages/apps/chat/GitHubChatSetup.test.tsx b/ui/src/pages/apps/chat/GitHubChatSetup.test.tsx index 4086c83caa8..df5e5270607 100644 --- a/ui/src/pages/apps/chat/GitHubChatSetup.test.tsx +++ b/ui/src/pages/apps/chat/GitHubChatSetup.test.tsx @@ -14,6 +14,7 @@ import { githubChatApi } from "@/api/githubChat"; import { projectsApi } from "@/api/projects"; import { toolsApi } from "@/api/tools"; import { copyTextToClipboard } from "@/lib/clipboard"; +import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils"; const fixture = vi.hoisted(() => ({ agents: [] as any[], @@ -684,6 +685,7 @@ describe("GitHub App wizard", () => { await render("resume=draft-1"); expect((container.querySelector("#github-owner-type") as HTMLSelectElement).value).toBe("organization:saved-org"); expect(container.textContent).toContain("Could not load some connected GitHub accounts"); + expect(replayLeaks("saved-org", container.querySelector("#github-owner-type")!)).toEqual({ rendered: true, recorded: false }); await click("Save & exit"); expect(githubChatApi.saveDraft).toHaveBeenCalledWith("draft-1", { name: "Saved App", ownerType: "organization", ownerLogin: "saved-org", diff --git a/ui/src/pages/apps/chat/GitHubChatSetup.tsx b/ui/src/pages/apps/chat/GitHubChatSetup.tsx index b670e77c33b..55a0e58fe79 100644 --- a/ui/src/pages/apps/chat/GitHubChatSetup.tsx +++ b/ui/src/pages/apps/chat/GitHubChatSetup.tsx @@ -27,6 +27,8 @@ import { queryKeys } from "@/lib/queryKeys"; import { GITHUB_APP_CREDENTIAL_FIELDS, GitHubAppRecovery } from "./GitHubConnectionRecovery"; import type { GitHubConnectionCompleteLocationState } from "./GitHubConnectionComplete"; import { describeError } from "@/api/errors"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; /** Restrict native manifest submission to GitHub registration endpoints. */ export function gitHubAppManifestAction( @@ -315,6 +317,7 @@ export function GitHubChatSetup() { ? "Connect your account" : reconnect && existing ? "Reconnect GitHub" : "Connect GitHub"} </h1> + <div className={cn("space-y-6", ANALYTICS_MASK_CLASS)}> {error ? ( <p role="alert" className="text-sm text-destructive"> {error} @@ -422,7 +425,7 @@ export function GitHubChatSetup() { {identityOnly && identityLinked ? ( <> <p role="status" className="text-sm"> - GitHub account <strong>{legacyIdentity?.login}</strong>{" "} + GitHub account <strong className={ANALYTICS_MASK_CLASS}>{legacyIdentity?.login}</strong>{" "} connected. You can now mention this bot on GitHub. </p> {footer()} @@ -430,7 +433,7 @@ export function GitHubChatSetup() { ) : state?.identity ? ( <> <p className="text-sm"> - Connect GitHub account <strong>{state.identity.login}</strong>{" "} + Connect GitHub account <strong className={ANALYTICS_MASK_CLASS}>{state.identity.login}</strong>{" "} to your Paperclip account. </p> {footer("Confirm my account", async () => { @@ -454,7 +457,7 @@ export function GitHubChatSetup() { </Label> <select id="github-personal-account" - className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm" + className={cn("w-full rounded-md border border-input bg-background px-3 py-2 text-sm", ANALYTICS_MASK_CLASS)} value={legacyAccount} onChange={(event) => { setLegacyAccount(event.target.value); @@ -479,7 +482,7 @@ export function GitHubChatSetup() { </select> {legacyIdentity && ( <p className="text-sm"> - GitHub account: <strong>{legacyIdentity.login}</strong> + GitHub account: <strong className={ANALYTICS_MASK_CLASS}>{legacyIdentity.login}</strong> </p> )} </> @@ -611,7 +614,7 @@ export function GitHubChatSetup() { <Label htmlFor="github-owner-type">GitHub account</Label> <select id="github-owner-type" - className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm" + className={cn("w-full rounded-md border border-input bg-background px-3 py-2 text-sm", ANALYTICS_MASK_CLASS)} value={accountChoice} disabled={busy || !!state?.registration} onChange={(event) => { @@ -681,6 +684,7 @@ export function GitHubChatSetup() { )} </> )} + </div> </div> ); } diff --git a/ui/src/pages/apps/chat/GitHubConnectionComplete.tsx b/ui/src/pages/apps/chat/GitHubConnectionComplete.tsx index 782581035a8..fce691977ec 100644 --- a/ui/src/pages/apps/chat/GitHubConnectionComplete.tsx +++ b/ui/src/pages/apps/chat/GitHubConnectionComplete.tsx @@ -12,6 +12,8 @@ import { Dialog, DialogContent, DialogFooter, DialogTitle } from "@/components/u import { agentAvatarUrl } from "@/lib/agent-avatar-url"; import { Link } from "@/lib/router"; import { GitHubAppBranding, gitHubBotMention } from "./GitHubAppIdentity"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; export type GitHubConnectionCompleteLocationState = { githubConnectionComplete?: { @@ -45,7 +47,7 @@ export function GitHubConnectionComplete({ return ( <Dialog open onOpenChange={(open) => { if (!open) onClose(); }}> <DialogContent - className="max-h-(--sz-85dvh) overflow-y-auto sm:max-w-xl" + className={cn("max-h-(--sz-85dvh) overflow-y-auto sm:max-w-xl", ANALYTICS_MASK_CLASS)} aria-describedby={undefined} onCloseAutoFocus={onCloseAutoFocus ? (event) => { event.preventDefault(); @@ -70,7 +72,7 @@ export function GitHubConnectionComplete({ </Link> {endpoint.providerAccountLabel && <> <span aria-hidden="true">·</span> - <span className="inline-flex items-center gap-1.5"> + <span className={cn("inline-flex items-center gap-1.5", ANALYTICS_MASK_CLASS)}> <AppLogo name="GitHub" brandKey="github" compact className="size-4! rounded-sm bg-transparent" /> {endpoint.providerAccountLabel} </span> diff --git a/ui/src/pages/apps/chat/GitHubConnectionRecovery.tsx b/ui/src/pages/apps/chat/GitHubConnectionRecovery.tsx index 23709cef990..6294be859ba 100644 --- a/ui/src/pages/apps/chat/GitHubConnectionRecovery.tsx +++ b/ui/src/pages/apps/chat/GitHubConnectionRecovery.tsx @@ -10,6 +10,8 @@ import { Label } from "@/components/ui/label"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; import { Link } from "@/lib/router"; import { gitHubAppSettingsUrl } from "./GitHubAppIdentity"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; export function GitHubConnectionRecoveryNotice({ endpoint }: { endpoint: ChatEndpoint }) { if (!["attention", "revoked"].includes(endpoint.status)) return null; @@ -40,7 +42,7 @@ function CredentialLabel({ id, label, help }: { id: string; label: string; help: <Label htmlFor={id}>{label}</Label> <Tooltip><TooltipTrigger asChild><button type="button" aria-label={`Help with ${label}`} className="rounded-sm text-muted-foreground hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"> <CircleHelp className="size-3.5" aria-hidden="true" /> - </button></TooltipTrigger><TooltipContent className="max-w-xs">{help}</TooltipContent></Tooltip> + </button></TooltipTrigger><TooltipContent className={cn("max-w-xs", ANALYTICS_MASK_CLASS)}>{help}</TooltipContent></Tooltip> </div>; } diff --git a/ui/src/pages/apps/chat/SlackAppDetails.tsx b/ui/src/pages/apps/chat/SlackAppDetails.tsx index 56a5dad0f6c..b03fb94becd 100644 --- a/ui/src/pages/apps/chat/SlackAppDetails.tsx +++ b/ui/src/pages/apps/chat/SlackAppDetails.tsx @@ -3,6 +3,8 @@ import { ChevronRight, CircleHelp } from "lucide-react"; import { slackAppConfigurationSchema, type SlackAppConfiguration } from "@paperclipai/shared"; import { Input } from "@/components/ui/input"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; export function SlackSetupAdvanced({ children, label = "Advanced" }: { children: ReactNode; label?: string }) { return <details className="group text-sm"> @@ -30,7 +32,7 @@ export function SlackAppDetails({ value, readOnly, onChange, onBlur }: { <label htmlFor={`slack-${key}`}>{label}</label> <Tooltip><TooltipTrigger asChild><button type="button" aria-label={`Help with ${label.toLowerCase()}`} className="rounded-sm text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"> <CircleHelp className="size-3.5" aria-hidden="true" /> - </button></TooltipTrigger><TooltipContent className="max-w-xs">{help}</TooltipContent></Tooltip> + </button></TooltipTrigger><TooltipContent className={cn("max-w-xs", ANALYTICS_MASK_CLASS)}>{help}</TooltipContent></Tooltip> </div> <Input id={`slack-${key}`} value={value[key]} maxLength={maxLength} readOnly={readOnly} aria-invalid={!validation.success && validation.error.issues.some(issue => issue.path[0] === key)} diff --git a/ui/src/pages/apps/chat/SlackIdentityStep.tsx b/ui/src/pages/apps/chat/SlackIdentityStep.tsx index 24f69fdd9a9..3b5ab26b251 100644 --- a/ui/src/pages/apps/chat/SlackIdentityStep.tsx +++ b/ui/src/pages/apps/chat/SlackIdentityStep.tsx @@ -8,6 +8,8 @@ import { Button } from "@/components/ui/button"; import { useQueryView } from "@/components/QueryView"; import { copyTextToClipboard } from "@/lib/clipboard"; import { queryKeys } from "@/lib/queryKeys"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; export function SlackIdentityStep({ endpointId, command, testStartedAt, onConnected, onSaveExit }: { endpointId: string; @@ -77,7 +79,7 @@ export function SlackIdentityStep({ endpointId, command, testStartedAt, onConnec const mine = identity.status === "linked" && identity.paperclipUserId === userId; return ( <div key={identity.principalId} className="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border p-3"> - <div className="min-w-0"> + <div className={cn("min-w-0", ANALYTICS_MASK_CLASS)}> <p className="text-sm font-medium">{identity.externalLabel}</p> <p className="text-xs text-muted-foreground">{identity.externalDetail}</p> </div> diff --git a/ui/src/pages/apps/chat/SlackTestMessageButton.test.tsx b/ui/src/pages/apps/chat/SlackTestMessageButton.test.tsx new file mode 100644 index 00000000000..74b18c94aeb --- /dev/null +++ b/ui/src/pages/apps/chat/SlackTestMessageButton.test.tsx @@ -0,0 +1,37 @@ +// @vitest-environment jsdom +import { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { SlackTestMessageButton } from "./SlackTestMessageButton"; +import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils"; + +const mocks = vi.hoisted(() => ({ sendSlackTestMessage: vi.fn(), listPrincipals: vi.fn() })); +vi.mock("@/api/chatEndpoints", () => ({ chatEndpointsApi: mocks })); +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +let root: Root; +let container: HTMLDivElement; +let client: QueryClient; +beforeEach(() => { + container = document.createElement("div"); + document.body.append(container); + root = createRoot(container); + client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }); +}); +afterEach(async () => { + await act(async () => root.unmount()); + container.remove(); + client.clear(); + vi.clearAllMocks(); +}); + +it("masks Slack account names and ids in session replay", async () => { + mocks.sendSlackTestMessage.mockResolvedValue({ status: "connection_required", nextCursor: null, + accounts: [{ id: "U0PELLWORTH", name: "Delphine Pellworth" }] }); + await act(async () => root.render(<QueryClientProvider client={client}><SlackTestMessageButton endpointId="endpoint" /></QueryClientProvider>)); + await act(async () => [...container.querySelectorAll("button")].find(button => button.textContent === "Send me a test message")!.click()); + expect(replayLeaks("Delphine Pellworth", document.body)).toEqual({ rendered: true, recorded: false }); + expect(replayLeaks("U0PELLWORTH", document.body)).toEqual({ rendered: true, recorded: false }); + expect(replayLeaks("Connect your Slack account", document.body)).toEqual({ rendered: true, recorded: false }); +}); diff --git a/ui/src/pages/apps/chat/SlackTestMessageButton.tsx b/ui/src/pages/apps/chat/SlackTestMessageButton.tsx index fd9c1523e42..5ffc9de8464 100644 --- a/ui/src/pages/apps/chat/SlackTestMessageButton.tsx +++ b/ui/src/pages/apps/chat/SlackTestMessageButton.tsx @@ -8,6 +8,7 @@ import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { Input } from "@/components/ui/input"; import { queryKeys } from "@/lib/queryKeys"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; export function SlackTestMessageButton({ endpointId }: { endpointId: string }) { const queryClient = useQueryClient(); @@ -63,7 +64,7 @@ export function SlackTestMessageButton({ endpointId }: { endpointId: string }) { {describeError(send.error).body} <button className="underline" onClick={reset}>Dismiss</button> </div>} <Dialog open={accounts !== null} onOpenChange={(open) => { if (!open && !send.isPending) setAccounts(null); }}> - <DialogContent> + <DialogContent className={ANALYTICS_MASK_CLASS}> <DialogHeader> <DialogTitle>Connect your Slack account</DialogTitle> <DialogDescription>Choose your account. Messages to this agent will use your Paperclip permissions.</DialogDescription> @@ -73,7 +74,7 @@ export function SlackTestMessageButton({ endpointId }: { endpointId: string }) { {accounts?.filter(account => `${account.name} ${account.id}`.toLowerCase().includes(search.toLowerCase())).map(account => <label key={account.id} className="flex cursor-pointer items-center gap-3 rounded-md border border-border p-3 text-sm"> <input type="radio" name="slack-account" value={account.id} checked={selected === account.id} onChange={() => setSelected(account.id)} /> - <span>{account.name} <span className="text-muted-foreground">({account.id})</span></span> + <span className={ANALYTICS_MASK_CLASS}>{account.name} <span className="text-muted-foreground">({account.id})</span></span> </label>)} {accounts?.length === 0 && <p className="text-sm text-muted-foreground">No available accounts found in this Slack workspace.</p>} </div> diff --git a/ui/src/pages/apps/chat/slack/ManagedSlackSetup.test.tsx b/ui/src/pages/apps/chat/slack/ManagedSlackSetup.test.tsx index 2e17a139361..fd3fadc13bf 100644 --- a/ui/src/pages/apps/chat/slack/ManagedSlackSetup.test.tsx +++ b/ui/src/pages/apps/chat/slack/ManagedSlackSetup.test.tsx @@ -5,6 +5,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { beforeEach, afterEach, expect, it, vi } from "vitest"; import type { ChatEndpoint } from "@/api/chatEndpoints"; import { ManagedSlackSetup } from "./ManagedSlackSetup"; +import { replayLeaks } from "@/lib/analytics/replay-recording.test-utils"; const api = vi.hoisted(() => ({ slackSetupOptions: vi.fn(), provisionManagedSlack: vi.fn(), authorizeSlackManager: vi.fn(), get: vi.fn() })); vi.mock("@/api/chatEndpoints", () => ({ chatEndpointsApi: api })); @@ -161,3 +162,17 @@ it.each(["popup", "fallback"])("continues after manager authorization returns th expect(api.authorizeSlackManager).toHaveBeenCalledTimes(1); expect(api.provisionManagedSlack).toHaveBeenCalledWith("endpoint", expect.objectContaining({ grantId: "grant" })); }); +it("keeps the chosen workspace name out of session replay in the closed picker", async () => { + api.slackSetupOptions.mockResolvedValue({ managedAvailable: true, workspaces: [{ grantId: "one", workspaceName: "Globex Sales" }, { grantId: "two", workspaceName: "Initech Ops" }] }); + endpoint.setup!.slackRegistration = { status: "failed", managerGrantId: "two" } as NonNullable<ChatEndpoint["setup"]>["slackRegistration"]; + await render(); + const trigger = container.querySelector('[aria-label="Slack workspace"]'); + expect(trigger?.textContent).toContain("Initech Ops"); + expect(replayLeaks("Initech Ops", document.body)).toEqual({ rendered: true, recorded: false }); +}); +it("keeps the only workspace name out of session replay", async () => { + api.slackSetupOptions.mockResolvedValue({ managedAvailable: true, workspaces: [{ grantId: "grant", workspaceName: "Globex Sales" }] }); + endpoint.setup!.slackRegistration = { status: "failed" } as NonNullable<ChatEndpoint["setup"]>["slackRegistration"]; + await render(); + expect(replayLeaks("Globex Sales", document.body)).toEqual({ rendered: true, recorded: false }); +}); diff --git a/ui/src/pages/apps/chat/slack/ManagedSlackSetup.tsx b/ui/src/pages/apps/chat/slack/ManagedSlackSetup.tsx index 45e92ca4974..d871fe75996 100644 --- a/ui/src/pages/apps/chat/slack/ManagedSlackSetup.tsx +++ b/ui/src/pages/apps/chat/slack/ManagedSlackSetup.tsx @@ -12,6 +12,8 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@ import { SetupWizardFooter } from "@/components/SetupWizard"; import type { OwnSlackAppSetup } from "./OwnSlackAppSetup"; import { sanitizedSetupErrorMessage } from "../chat-setup-error"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; export function ManagedSlackSetup({ endpoint, disabled, saveDetails, onSaved, onBusy, onSaveExit, autoStart = false, reconnect = false }: ComponentProps<typeof OwnSlackAppSetup> & { autoStart?: boolean; reconnect?: boolean }) { const client = useQueryClient(); @@ -126,10 +128,10 @@ export function ManagedSlackSetup({ endpoint, disabled, saveDetails, onSaved, on {busy || choices.isPending || creating ? <p role="status" className="flex items-center gap-2 text-sm text-muted-foreground"><Loader2 className="size-4 animate-spin" />{busy ? needsAuthorization ? "Opening Slack…" : "Connecting your agent…" : creating ? "Setting up your Slack app…" : "Loading Slack…"}</p> : !choices.data?.managedAvailable ? <p className="text-sm">Managed Slack setup is unavailable. Try again later.</p> : reconnectWorkspace ? null : <> - {workspaces.length === 1 && <p className="text-sm">Add <strong>{endpoint.assignedAgentName}</strong> to <strong>{workspaces[0]!.workspaceName}</strong>.</p>} + {workspaces.length === 1 && <p className={cn("text-sm", ANALYTICS_MASK_CLASS)}>Add <strong>{endpoint.assignedAgentName}</strong> to <strong>{workspaces[0]!.workspaceName}</strong>.</p>} {workspaces.length > 1 && <Select value={grantId ?? ""} onValueChange={setSelectedGrant} disabled={busy || started}> - <SelectTrigger aria-label="Slack workspace"><SelectValue placeholder="Choose a Slack workspace" /></SelectTrigger> - <SelectContent>{workspaces.map(workspace => <SelectItem key={workspace.grantId} value={workspace.grantId}>{workspace.workspaceName}</SelectItem>)}</SelectContent> + <SelectTrigger className={ANALYTICS_MASK_CLASS} aria-label="Slack workspace"><SelectValue placeholder="Choose a Slack workspace" /></SelectTrigger> + <SelectContent className={ANALYTICS_MASK_CLASS}>{workspaces.map(workspace => <SelectItem key={workspace.grantId} value={workspace.grantId}>{workspace.workspaceName}</SelectItem>)}</SelectContent> </Select>} {!started && workspaces.length > 0 && <div><Button variant="link" className="h-auto p-0" disabled={busy} onClick={() => void run(authorize)}>Connect another Slack workspace</Button></div>} </>} diff --git a/ui/src/pages/apps/gateways/ConnectClientDialog.tsx b/ui/src/pages/apps/gateways/ConnectClientDialog.tsx index f4ba5000d0c..1aa69e58ca6 100644 --- a/ui/src/pages/apps/gateways/ConnectClientDialog.tsx +++ b/ui/src/pages/apps/gateways/ConnectClientDialog.tsx @@ -40,6 +40,7 @@ import { } from "./gateway-helpers"; import { gatewaysQueryKey } from "./NewGatewayDialog"; import { describeError } from "@/api/errors"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; type PanelKey = string; type ClientIcon = ComponentType<{ className?: string }>; @@ -178,7 +179,7 @@ export function ConnectClientDialog({ return ( <Dialog open={open} onOpenChange={onOpenChange}> - <DialogContent className="sm:max-w-2xl"> + <DialogContent className={cn("sm:max-w-2xl", ANALYTICS_MASK_CLASS)}> <DialogHeader> <DialogTitle className="flex items-center gap-2"> Client snippets @@ -188,7 +189,7 @@ export function ConnectClientDialog({ <HelpCircle className="h-4 w-4" /> </button> </TooltipTrigger> - <TooltipContent className="max-w-xs text-xs"> + <TooltipContent className={cn("max-w-xs text-xs", ANALYTICS_MASK_CLASS)}> Give this MCP gateway configuration to your tool. It does not give it access to Paperclip or skills; it only gateways calls between the client and the tools exposed here. </TooltipContent> diff --git a/ui/src/pages/apps/gateways/EditGatewayDialog.tsx b/ui/src/pages/apps/gateways/EditGatewayDialog.tsx index 2556ff8f449..317ba013559 100644 --- a/ui/src/pages/apps/gateways/EditGatewayDialog.tsx +++ b/ui/src/pages/apps/gateways/EditGatewayDialog.tsx @@ -16,6 +16,8 @@ import { useToast } from "@/context/ToastContext"; import { allowedToolsLabel } from "./gateway-helpers"; import { gatewaysQueryKey } from "./NewGatewayDialog"; import { describeError } from "@/api/errors"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; export function EditGatewayDialog({ companyId, @@ -73,7 +75,7 @@ export function EditGatewayDialog({ return ( <Dialog open={open} onOpenChange={onOpenChange}> - <DialogContent className="sm:max-w-lg"> + <DialogContent className={cn("sm:max-w-lg", ANALYTICS_MASK_CLASS)}> <DialogHeader> <DialogTitle>Edit gateway</DialogTitle> <DialogDescription> diff --git a/ui/src/pages/apps/gateways/NewGatewayDialog.tsx b/ui/src/pages/apps/gateways/NewGatewayDialog.tsx index 2998bd363e4..0e65361ffa1 100644 --- a/ui/src/pages/apps/gateways/NewGatewayDialog.tsx +++ b/ui/src/pages/apps/gateways/NewGatewayDialog.tsx @@ -16,6 +16,8 @@ import { useToast } from "@/context/ToastContext"; import { queryKeys } from "@/lib/queryKeys"; import { allowedToolsLabel } from "./gateway-helpers"; import { describeError } from "@/api/errors"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; export const gatewaysQueryKey = (companyId: string) => ["tools", "gateways", companyId] as const; @@ -91,7 +93,7 @@ export function NewGatewayDialog({ return ( <Dialog open={open} onOpenChange={onOpenChange}> - <DialogContent className="sm:max-w-lg"> + <DialogContent className={cn("sm:max-w-lg", ANALYTICS_MASK_CLASS)}> <DialogHeader> <DialogTitle>New gateway</DialogTitle> <DialogDescription> diff --git a/ui/src/pages/apps/gateways/panels/GatewayActivityPanel.tsx b/ui/src/pages/apps/gateways/panels/GatewayActivityPanel.tsx index 84e07426d92..df8381a5d3a 100644 --- a/ui/src/pages/apps/gateways/panels/GatewayActivityPanel.tsx +++ b/ui/src/pages/apps/gateways/panels/GatewayActivityPanel.tsx @@ -9,6 +9,8 @@ import { Skeleton } from "@/components/ui/skeleton"; import { StatusBadge } from "@/components/StatusBadge"; import { queryKeys } from "@/lib/queryKeys"; import { RelativeTime } from "@/pages/tools/shared"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; const PAGE_SIZE = 25; @@ -120,7 +122,7 @@ function ActivityRow({ event }: { event: ToolGatewayActivityEvent }) { {argumentsText ? ( <div className="mt-2 space-y-1"> <div className="text-muted-foreground">Arguments (redacted)</div> - <pre className="overflow-x-auto whitespace-pre-wrap break-words rounded-md border border-border bg-background p-3 font-mono text-xs text-foreground"> + <pre className={cn("overflow-x-auto whitespace-pre-wrap break-words rounded-md border border-border bg-background p-3 font-mono text-xs text-foreground", ANALYTICS_MASK_CLASS)}> {argumentsText} </pre> </div> @@ -128,7 +130,7 @@ function ActivityRow({ event }: { event: ToolGatewayActivityEvent }) { {resultText ? ( <div className="mt-3 space-y-1"> <div className="text-muted-foreground">Result (redacted)</div> - <pre className="overflow-x-auto whitespace-pre-wrap break-words rounded-md border border-border bg-background p-3 font-mono text-xs text-foreground"> + <pre className={cn("overflow-x-auto whitespace-pre-wrap break-words rounded-md border border-border bg-background p-3 font-mono text-xs text-foreground", ANALYTICS_MASK_CLASS)}> {resultText} </pre> </div> diff --git a/ui/src/pages/apps/gateways/panels/GatewayAdvancedPanel.tsx b/ui/src/pages/apps/gateways/panels/GatewayAdvancedPanel.tsx index 8522dd083cd..27c007c7a71 100644 --- a/ui/src/pages/apps/gateways/panels/GatewayAdvancedPanel.tsx +++ b/ui/src/pages/apps/gateways/panels/GatewayAdvancedPanel.tsx @@ -10,6 +10,8 @@ import { useToast } from "@/context/ToastContext"; import { copyTextToClipboard } from "@/lib/clipboard"; import { gatewaysQueryKey } from "../NewGatewayDialog"; import { describeError } from "@/api/errors"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; /** * Advanced tab — raw protocol/transport details, config JSON and the archive @@ -102,7 +104,7 @@ export function GatewayAdvancedPanel({ Copy JSON </Button> </div> - <pre className="max-h-96 overflow-auto whitespace-pre-wrap break-words rounded-md bg-muted p-3 font-mono text-xs text-muted-foreground"> + <pre className={cn("max-h-96 overflow-auto whitespace-pre-wrap break-words rounded-md bg-muted p-3 font-mono text-xs text-muted-foreground", ANALYTICS_MASK_CLASS)}> {rawConfig} </pre> </section> diff --git a/ui/src/pages/apps/gateways/panels/TokensPanel.test.tsx b/ui/src/pages/apps/gateways/panels/TokensPanel.test.tsx index 31c1695430c..85594f4c769 100644 --- a/ui/src/pages/apps/gateways/panels/TokensPanel.test.tsx +++ b/ui/src/pages/apps/gateways/panels/TokensPanel.test.tsx @@ -7,6 +7,7 @@ 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()); @@ -210,6 +211,7 @@ describe("TokensPanel", () => { 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"); @@ -229,6 +231,7 @@ describe("TokensPanel", () => { 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 () => { diff --git a/ui/src/pages/apps/gateways/panels/TokensPanel.tsx b/ui/src/pages/apps/gateways/panels/TokensPanel.tsx index f763c3f64a0..e8a695b625f 100644 --- a/ui/src/pages/apps/gateways/panels/TokensPanel.tsx +++ b/ui/src/pages/apps/gateways/panels/TokensPanel.tsx @@ -30,6 +30,7 @@ import { type TokenStatus, } from "../gateway-helpers"; import { describeError } from "@/api/errors"; +import { ANALYTICS_NO_CAPTURE_CLASS } from "@/lib/analytics/privacy"; const DEFAULT_ACTIONS: ToolMcpGatewayTokenAction[] = ["tools/list", "tools/call"]; const TOKEN_PAGE_SIZE = 10; @@ -310,7 +311,7 @@ export function TokensPanel({ </Button> </div> <div className="flex items-center gap-2"> - <code className="min-w-0 flex-1 truncate rounded bg-muted px-3 py-2 font-mono text-xs text-foreground"> + <code className={cn("min-w-0 flex-1 truncate rounded bg-muted px-3 py-2 font-mono text-xs text-foreground", ANALYTICS_NO_CAPTURE_CLASS)}> {revealed ? created.token : maskedTokenLabel(created)} </code> {revealed ? ( diff --git a/ui/src/pages/skills/SkillPackagePreview.tsx b/ui/src/pages/skills/SkillPackagePreview.tsx index 620f00f98e7..f61fe609e14 100644 --- a/ui/src/pages/skills/SkillPackagePreview.tsx +++ b/ui/src/pages/skills/SkillPackagePreview.tsx @@ -10,6 +10,8 @@ import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } f import { Button } from '@/components/ui/button'; import { Link } from '@/lib/router'; import type { SkillTreeCandidate } from './SkillSourceTree'; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; export function SkillPackagePreview({ companyId, repository, commitSha, skill, initialFile, repositoryPackage, onClose }: { companyId: string; repository: SkillSourceDiscoveryRequest; commitSha: string | null; @@ -71,7 +73,7 @@ export function SkillPackagePreview({ companyId, repository, commitSha, skill, i {previewView.kind === 'error' && <div className="space-y-2 text-sm"><QueryErrorState size="inline" error={preview.error} action="load the preview" onRetry={previewView.retry} retrying={previewView.isFetching} /> <Link to="/apps" className="underline">Manage GitHub access</Link></div>} {skill.error && <p className="text-sm text-muted-foreground">Preview unavailable for a package that failed validation.</p>} {preview.data?.file.encoding === 'base64' && <div className="flex flex-col items-center gap-3 py-8 text-sm text-muted-foreground"><FileImage className="size-6" /><p>Binary asset · included without changes</p><p className="text-xs">Open on GitHub to preview or download this file.</p></div>} - {preview.data?.content !== null && preview.data?.content !== undefined && <pre className="whitespace-pre-wrap break-words font-mono text-xs leading-relaxed">{preview.data.content}</pre>} + {preview.data?.content !== null && preview.data?.content !== undefined && <pre className={cn("whitespace-pre-wrap break-words font-mono text-xs leading-relaxed", ANALYTICS_MASK_CLASS)}>{preview.data.content}</pre>} {preview.data?.truncated && <p className="mt-3 text-xs text-muted-foreground">Showing the first 64 KB. The complete file is imported.</p>} </div> </div> diff --git a/ui/src/pages/tools/AuditTab.tsx b/ui/src/pages/tools/AuditTab.tsx index 0186c7024f0..50c87edb211 100644 --- a/ui/src/pages/tools/AuditTab.tsx +++ b/ui/src/pages/tools/AuditTab.tsx @@ -25,6 +25,7 @@ import { import { agentsApi } from "@/api/agents"; import { AgentSelect } from "@/components/AgentMultiSelect"; import { ToolsPageHeader, LoadingState, RelativeTime } from "./shared"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; const PAGE_SIZE = 50; const ALL = "__all"; @@ -299,7 +300,7 @@ function ActivityRow({ return connectionId ? ( <div key={connectionId} className="flex gap-2"> <span className="shrink-0 text-muted-foreground">Not installed</span> - <Link to={`/apps/${connectionId}/permissions`} className="font-medium text-primary hover:underline"> + <Link to={`/apps/${connectionId}/permissions`} className={cn("font-medium text-primary hover:underline", ANALYTICS_MASK_CLASS)}> {connectionName} </Link> </div> @@ -310,7 +311,7 @@ function ActivityRow({ {argumentsText ? ( <div className="space-y-1"> <span className="text-muted-foreground">Parameters (redacted)</span> - <pre className="whitespace-pre-wrap break-words rounded-md border border-border bg-background p-3 font-mono text-xs text-foreground"> + <pre className={cn("whitespace-pre-wrap break-words rounded-md border border-border bg-background p-3 font-mono text-xs text-foreground", ANALYTICS_MASK_CLASS)}> {argumentsText} </pre> </div> diff --git a/ui/src/pages/tools/GatewaysTab.test.tsx b/ui/src/pages/tools/GatewaysTab.test.tsx index 11d89d32e98..6ef2d55dd65 100644 --- a/ui/src/pages/tools/GatewaysTab.test.tsx +++ b/ui/src/pages/tools/GatewaysTab.test.tsx @@ -9,19 +9,21 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { ApiError } from "@/api/client"; import { GatewaysTab } from "./GatewaysTab"; import { RelativeTime } from "./shared"; +import { isBlockedFromReplay } from "@/lib/analytics/replay-recording.test-utils"; const listGatewaysMock = vi.hoisted(() => vi.fn()); const listProfilesMock = vi.hoisted(() => vi.fn()); const listAgentsMock = vi.hoisted(() => vi.fn()); const listProjectsMock = vi.hoisted(() => vi.fn()); const pushToastMock = vi.hoisted(() => vi.fn()); +const createGatewayTokenMock = vi.hoisted(() => vi.fn()); vi.mock("@/api/tools", () => ({ toolsApi: { listGateways: (companyId: string) => listGatewaysMock(companyId), listProfiles: (companyId: string) => listProfilesMock(companyId), createGateway: vi.fn(), - createGatewayToken: vi.fn(), + createGatewayToken: (...args: unknown[]) => createGatewayTokenMock(...args), revokeGatewayToken: vi.fn(), }, })); @@ -309,4 +311,45 @@ describe("GatewaysTab", () => { expect(container.querySelector('[data-query-view="error"]')).toBeNull(); expect(container.textContent).toContain("Dotta's MacBook"); }); + + it("blocks the new bearer token and client snippets from session replay", async () => { + listGatewaysMock.mockResolvedValue({ + gateways: [ + gateway({ + clientSnippets: [{ + client: "cursor", + label: "Cursor", + config: { mcpServers: { paperclip: { headers: { Authorization: "Bearer pcgw_snip_R7tY2wQx" } } } }, + notes: [], + }], + }), + ], + }); + createGatewayTokenMock.mockResolvedValue({ ...token({ name: "Laptop token" }), token: "pcgw_live_9KdmZ3qVt8" }); + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + await render( + <QueryClientProvider client={client}> + <GatewaysTab companyId="company-1" /> + </QueryClientProvider>, + ); + expect(isBlockedFromReplay("pcgw_snip_R7tY2wQx", container)).toBe(true); + + await act(async () => { + [...container.querySelectorAll("button")].find((button) => button.textContent === "Issue token")!.click(); + }); + const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!; + for (const placeholder of ["Dotta's MacBook", "Cursor on work laptop", "Who owns this token and why it exists"]) { + await act(async () => { + const input = container.querySelector<HTMLInputElement>(`input[placeholder="${placeholder}"]`)!; + setValue.call(input, "Laptop"); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + } + await act(async () => { + container.querySelector<HTMLFormElement>("form:has(input[placeholder=\"Dotta's MacBook\"])")!.requestSubmit(); + }); + await flushReact(); + expect(createGatewayTokenMock).toHaveBeenCalled(); + expect(isBlockedFromReplay("pcgw_live_9KdmZ3qVt8", container)).toBe(true); + }); }); diff --git a/ui/src/pages/tools/GatewaysTab.tsx b/ui/src/pages/tools/GatewaysTab.tsx index 8478304b773..cef5a0f3bbd 100644 --- a/ui/src/pages/tools/GatewaysTab.tsx +++ b/ui/src/pages/tools/GatewaysTab.tsx @@ -18,6 +18,8 @@ import { queryKeys } from "@/lib/queryKeys"; import { copyTextToClipboard } from "@/lib/clipboard"; import { LoadingState, RelativeTime, ToolsPageHeader } from "./shared"; import { describeError } from "@/api/errors"; +import { ANALYTICS_NO_CAPTURE_CLASS } from "@/lib/analytics/privacy"; +import { cn } from "@/lib/utils"; type CreateGatewayDraft = { name: string; @@ -525,7 +527,7 @@ export function GatewaysTab({ companyId }: { companyId: string }) { Copy token </Button> </div> - <div className="break-all rounded bg-background px-3 py-2 font-mono text-xs text-muted-foreground"> + <div className={cn("break-all rounded bg-background px-3 py-2 font-mono text-xs text-muted-foreground", ANALYTICS_NO_CAPTURE_CLASS)}> {createdToken.token} </div> </div> @@ -642,7 +644,7 @@ export function GatewaysTab({ companyId }: { companyId: string }) { Copy </Button> </summary> - <pre className="mt-2 max-h-56 overflow-auto whitespace-pre-wrap break-words rounded bg-background p-3 text-xs text-muted-foreground"> + <pre className={cn("mt-2 max-h-56 overflow-auto whitespace-pre-wrap break-words rounded bg-background p-3 text-xs text-muted-foreground", ANALYTICS_NO_CAPTURE_CLASS)}> {formatSnippetConfig(snippet.config)} </pre> {snippet.notes.length > 0 ? ( diff --git a/ui/src/pages/tools/connection-dialogs.tsx b/ui/src/pages/tools/connection-dialogs.tsx index d7726e6764f..dbb9794a685 100644 --- a/ui/src/pages/tools/connection-dialogs.tsx +++ b/ui/src/pages/tools/connection-dialogs.tsx @@ -38,6 +38,7 @@ import { QuarantineBadge, } from "./shared"; import { describeError } from "@/api/errors"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; export const TRANSPORT_LABEL: Record<string, string> = { mcp_remote: "remote http", @@ -78,7 +79,7 @@ export function CatalogDialog({ connection, onClose }: { connection: ToolConnect <Dialog open onOpenChange={(o) => !o && onClose()}> <DialogContent className="max-w-2xl"> <DialogHeader> - <DialogTitle>Tool catalog — {connection.name}</DialogTitle> + <DialogTitle>Tool catalog — <span className={ANALYTICS_MASK_CLASS}>{connection.name}</span></DialogTitle> </DialogHeader> {catalog.isLoading || catalogView.kind === "reconnecting" ? ( <LoadingState /> diff --git a/ui/src/pages/tools/profiles/ProfileDetail.tsx b/ui/src/pages/tools/profiles/ProfileDetail.tsx index 2edf663ace6..0ef3f19c7ff 100644 --- a/ui/src/pages/tools/profiles/ProfileDetail.tsx +++ b/ui/src/pages/tools/profiles/ProfileDetail.tsx @@ -33,6 +33,7 @@ import { LoadingState, RelativeTime, ToolsPageHeader } from "../shared"; import { ProfileActionDialog, type ProfileActionDialogKind } from "./ProfileActionDialog"; import { allowsLabel, STATUS_LABEL } from "./profile-summary"; import { useProfilesData } from "./useProfilesData"; +import { ANALYTICS_MASK_CLASS } from "@/lib/analytics/privacy"; type DialogKind = "edit" | "duplicate" | "archive" | "delete" | "restore" | null; @@ -422,7 +423,7 @@ function NewToolsReviewDialog({ {tool.description ? ( <p className="mt-1 text-sm text-muted-foreground">{tool.description}</p> ) : null} - <p className="mt-1 text-xs text-muted-foreground"> + <p className={cn("mt-1 text-xs text-muted-foreground", ANALYTICS_MASK_CLASS)}> {tool.applicationName ?? tool.connectionName ?? "App tool"} · added {formatShortDate(tool.addedAt)} </p> </div>