Files
PaperClipAI/ui/src/lib/analytics/replay-masking.test.tsx
T
5a9c06b315 feat(analytics): make replay work content a deployment opt-in (#22820)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Hosts can enable PostHog browser analytics and session replay
through deployment configuration.
> - Replay masks work content, which makes task and artifact flows hard
to understand.
> - Hosts must decide whether their deployment may show this content.
> - This pull request adds an explicit deployment opt-in, with work
content masked by default.
> - Eligible companies can show work content after that opt-in, while
connected-account checks and secret masking still apply.

## Linked Issues or Issue Description

No public issue exists. This change follows the enhancement template.

**What existing behavior does this improve?**

Session replay masks task descriptions, document bodies and artifact
previews. A host cannot choose to show eligible work content
independently of enabling replay.

**Subsystem affected**

Browser session replay, deployment analytics configuration, and the
authenticated session contract.

**Current behavior**

Work content stays masked in every company. Task and artifact titles
already show. PostHog project masking settings cannot override the
options supplied by the board UI.

**Proposed behavior**

Keep work content masked by default. Set
`PAPERCLIP_POSTHOG_REPLAY_WORK_CONTENT_ENABLED=1` in deployment
configuration to allow it for eligible companies. Unset, `0`, and other
values keep it masked. Browser analytics and replay must also be
enabled. A host can keep replay enabled while work content stays masked.

**Reason and benefit**

Hosts control their recording policy without editing Core source. An
eligible company's replay can show the task flow after the host opts in.

**Breaking changes**

None relative to the base branch. Self-hosted analytics remain disabled
by the existing analytics gate. Existing deployments retain work-content
masking unless they explicitly opt in. The session gains an optional
boolean and the tool connection list gains an optional `hiddenCount`
field. Missing fields fail closed.

## What Changed

- Add `PAPERCLIP_POSTHOG_REPLAY_WORK_CONTENT_ENABLED`, default off.
Resolve it in the existing server analytics configuration and send the
effective boolean as `browserAnalytics.replayWorkContentEnabled`. The
shared session schema preserves the field and accepts older servers that
omit it.
- Require both replay and the work-content opt-in before the UI queries
company sources or permits visibility. Removing the opt-in from a
refreshed session masks content even when eligible source answers remain
cached.
- Preserve the original company checks: complete tool connection and
chat endpoint lists, no Google or Slack source, no known aggregator or
router, and the selected company's route. Unknown, failed, invalidated,
or hidden source data keeps content masked. Live source changes reset
the check.
- Mark task descriptions, document bodies, attachment and artifact
previews, and file viewers as work content. Customer content, editors,
comments, chat, run output and connected-account surfaces remain masked.
Secrets remain blocked or redacted. Input and attribute values remain
masked.
- Preserve credential punctuation in task previews by reusing the shared
Markdown plain-text helper. Bound conversion to the first 2,048 source
characters, and always mask source-capped previews to protect incomplete
credentials. Scan complete command-line flag names once before
classifying secrets and reading their values. A 512 KiB hyphen input and
long flag names have regression coverage.
- Mask surfaces that show cut or rewritten work content, where the
redaction cannot work. A cut task preview masks when the text before its
180-character limit holds a credential. The document card preview (first
4,000 characters) masks when the cut changes what the redaction masks
before it. The text preview on an artifact card always masks, because
the server strips hyphens and underscores from it and cuts it at 280
characters. Quoted flag values run past escaped quotes, and flag names
can hold an underscore. An unquoted token that starts with `--` is read
as the next flag, not as a value, so `--auth
--tlsCertificateKeyFilePassword hunter2` masks `hunter2`.
- Refresh the recording once when a company's work content first becomes
visible. Keep the existing autocapture text and attribute masking.
- Add tests for deployment switches, session parsing and exposure,
disabled source requests, older servers, and withdrawal with cached
data. Retain the original masking, company, secret, and source-change
tests.
- Document configuration, rollback, restart and tab-reload steps,
residual recording risks, and the board-only `hiddenCount` API field
with absent-on-older-server semantics. Refresh the shared-source pins
with the maintained generator; runtime and compiler pins stay unchanged.

The original implementation and commits are preserved from @nguyenm7.
The deployment configuration follow-up adds the host opt-in.

When squash-merging, preserve the follow-up author's credit in the
squash commit body:

```text
Co-Authored-By: Devin Foley <devinfoley@users.noreply.github.com>
```

## Verification

Current head `2ce967f1e1`: CI has 43 checks passed and four skipped,
with none failed or pending. The Greptile review on this head is 5/5,
and both findings from its previous review are fixed. No person has
approved the pull request yet. The evidence below was recorded on
earlier heads and is kept as the record of how the change was verified.

Greptile apex review: 5/5 on `45023e6`, with no unresolved review
threads. CI on that head is green: 76 checks passed and four skipped,
with no failed or pending checks. The branch has no merge conflicts with
master.

On the final source change, locally:

- `cd ui && pnpm exec vitest run src/lib/analytics
src/context/LiveUpdatesProvider.test.ts
src/lib/markdown-plain-text.test.ts`: 10 files, 520 tests pass. The
secret-redaction cases are in `replay-secret-redaction.test.tsx`, so
`replay-masking.test.tsx` stays under 1,000 lines (701).
- `cd server && pnpm exec vitest run
src/__tests__/cloud-posthog-config.test.ts
src/__tests__/cloud-posthog-browser.test.ts
src/__tests__/auth-routes.test.ts
src/__tests__/posthog-direct-transport.test.ts`: 4 files, 124 tests
pass.
- `cd packages/shared && pnpm exec vitest run
src/validators/access.test.ts`: 22 tests pass.
- `pnpm exec vitest run -c tests/runner-e2e/vitest.config.ts
source-sdk-public-inputs`: 13 tests pass.
- Shared, server and UI package typechecks pass. Server and UI builds
pass.
- Token gates, module boundaries, the test budget check for changed
suites, and `git diff --check` pass.
- Long-preview regression proof: four rendered tests initially fail on
`9f2039d` because it passes 128,005 characters to conversion. They now
verify a 2,048-character input bound while calling the real helper, a
maximum 180-character summary, and complete replay masking for capped
sources. Inputs include backticks, stars, underscores and brackets. The
earlier short-preview credential tests still pass.
- Review regression proof: three rendered task-preview tests expose
GitLab, GitHub and OpenAI fixture credentials on `7533fbe`; they pass
after preserving token punctuation. An 80,000-hyphen input took about
3.25 seconds on that head and failed the 500 ms bound. The single-pass
flag scan passes the guard with a 512 KiB prefix followed by a real
password flag.
- Regression proof: the added tests first failed on the prior
implementation, including work content visible with a missing or false
opt-in and after withdrawal. They pass with the new gate.
- `pnpm verify`: exit 2, broader verification required because the
analytics document is a global CI input. Required CI supplies
repository-wide coverage. An earlier exit 1 identified stale
shared-source pins; the maintained generator refreshed them and the 13
pin tests pass.
- Direct UI `tsc --noEmit` initially lacked generated Storybook catalogs
in the fresh checkout. The maintained UI typecheck generates those files
and passes. A preliminary Vitest `--project ui` invocation matched no
named project; the commands above use the package configuration.
- Secret scan reviewed the commit diff. Gitleaks reports two generic-key
matches in the generated source-pin registry; both equal the
corresponding Git blob hashes. The remaining commit content scans clean.
No run artifacts or private deployment data are committed.

CI follow-up on `45023e6`: [server shard
10/20](https://github.com/paperclipai/paperclip/actions/runs/45560174673/job/139021948661)
timed out twice at the existing 15-second limit in
`issue-document-batch.integration.test.ts`, test "rejects many large
documents using a size-only query before loading any bodies". The test
prepares 200 half-MiB documents and later rewrites them. The same test
and server code are unchanged from `9f2039d`, where [the same shard
passed](https://github.com/paperclipai/paperclip/actions/runs/45558505382/job/139016469065)
and this test took 8.39 seconds. The intervening commit changes UI and
documentation only.

The exact failing case passes locally on the current head with `cd
server && pnpm exec vitest run
src/services/native-runtime/issue-document-batch.integration.test.ts -t
'rejects many large documents using a size-only query before loading any
bodies'` (one passed, 15 skipped). This shows local recovery; it does
not establish the cause of the CI timeout. A targeted shard rerun was
requested, but GitHub refused because the workflow is still running. No
test limits or product code have been changed to hide the failure. This
initial failure is retained here as evidence; the successful
second-attempt outcome is recorded below.

CI follow-up, second shard: [server shard
13/20](https://github.com/paperclipai/paperclip/actions/runs/45560174673/job/139021948654)
failed `ai-connections.test.ts`, test "requires sign-in after the
receiver process dies with an exchanged but unsaved token". The first
attempt failed its wait for one token exchange and an advisory-lock
waiter within 25 seconds. The automatic retry failed earlier because the
first attempt had already inserted the fixed membership fixture. The
suite, receiver helper and AI connection service are unchanged by this
work. The [original PR head passed this
shard](https://github.com/paperclipai/paperclip/actions/runs/45544519067/job/138970880217),
with the same test taking 21.06 seconds.

The exact case passes locally on `45023e6` with `cd server && pnpm exec
vitest run src/__tests__/ai-connections.test.ts -t 'requires sign-in
after the receiver process dies with an exchanged but unsaved token'`
(one passed, 164 skipped). The cause of the missed CI wait remains
unconfirmed. This local pass does not clear the failed CI result.
Targeted reruns were initially blocked by GitHub while the workflow was
running. See the successful second-attempt outcome below.

CI recovery: [workflow attempt
2](https://github.com/paperclipai/paperclip/actions/runs/45560174673/attempts/2)
completed successfully on unchanged head `45023e6`. Both previously
failed shards now pass. No source edits, timeout increases, or test
removals were needed. The original timeout and missed-wait causes remain
unconfirmed; the earlier failures and comparison evidence above are
preserved. Final acceptance uses the green current-head CI result
together with the local checks and 5/5 review.

Not run locally: repository-wide tests/builds or a live PostHog
recording. The tests exercise the masking callback and UI state, not the
externally loaded recorder.

After deployment, compare a masked replay with the work-content flag
unset against an opted-in eligible company. Then verify that
Google/Slack or a hidden source keeps the same surfaces masked. Restart
the server and reload open tabs after changing deployment environment
values.

## Risks

- The opt-in belongs to the host, not to the people who use the
deployment. Nothing in this pull request asks or tells a user. A host
that sets the flag must tell its users first. The plan for the hosted
service is in #23338.
- Enabling the new flag allows eligible work content to leave the
instance in replay data. Leave it unset or set it to `0` to keep work
content masked. No deployment or fleet policy is changed by this PR.
- The flag does not bypass company eligibility checks or secret masking.
Changing it affects future recording after the configuration reaches the
browser; it does not remove previously recorded content.
- Connection detection is a best effort. A custom MCP server with an
unrelated name and URL, or credentials used directly by an agent, can
carry Google or Slack data without appearing as a known source.
- Secret redaction is a best effort. Unknown or unlabeled secrets,
non-English labels, values on a later line or under a table header, and
values outside bounded line context can be missed. Some ordinary values
are over-masked.
- Source changes can race with recording until the live update arrives.
A missed update can extend that window to the five-minute refresh.
Connection count and list queries can disagree briefly and then mask
conservatively.
- Hidden drafts and aggregators can keep harmless content masked. Text
rendered during a source recheck stays masked until it renders again.
The first visible state adds a full recording snapshot.
- Task previews now inspect at most 2,048 source characters before
conversion. Very long markup can produce an incomplete summary.
Source-capped previews stay fully masked; opening the full task keeps
the normal work-content policy.
- Artifact card text previews stay masked in every company. Document
card previews and cut task previews mask when a credential sits at or
before the cut, so some replays show stars there while the full document
shows.
- Task titles, names and other previously visible surfaces remain
visible and can contain copied customer text. New work-content surfaces
must preserve company scoping.

## Model Used

- Original implementation: Anthropic Claude Opus 5.5 (`claude-opus-5-5`)
and Claude Fable 5.2 (`claude-fable-5-2`) through Claude Code, with
shell, edits, tests and the original read-only exploration subagent.
- Deployment configuration follow-up: OpenAI `gpt-6.1-sol` through the
Codex, xhigh reasoning, shell, file edits and test tools. Context window
size is not exposed by the runtime. No additional subagents.

## 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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Devin Foley <devin@paperclip.ing>
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Dotta <bippadotta@protonmail.com>
2026-12-01 18:53:11 +00:00

702 lines
43 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// @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 { MemoryRouter } from "react-router-dom";
import type { ConnectionGrant, DocumentRevision } from "@paperclipai/shared";
import { afterEach, describe, expect, it, vi } from "vitest";
import { AccountQuotaPanels } from "@/components/AccountQuotaPanels";
import { AgentSetupPrompt } from "@/components/AgentSetupPrompt";
import { AiConnectionAccountControls } from "@/components/ai-connections/AiConnectionAccountControls";
import { AiConnectionIdentity } from "@/components/ai-connections/AiConnectionIdentity";
import { AiConnectionPicker } from "@/components/ai-connections/AiConnectionPicker";
import { AiConnectionPoolRunDetails } from "@/components/ai-connections/AiConnectionPoolRunDetails";
import { DocumentDiffModal } from "@/components/DocumentDiffModal";
import { CopyField } from "@/components/routine-triggers/WebhookFields";
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 { IssueQuicklookCard } from "@/components/IssueLinkQuicklook";
import { ArtifactPreview } from "@/components/artifacts/ArtifactCard";
import { DocumentCard } from "@/components/artifacts/RichArtifactCards";
import * as CompanyContext from "@/context/CompanyContext";
import * as MarkdownPlainText from "@/lib/markdown-plain-text";
import { buildPostHogInitOptions } from "./product-analytics";
import {
ANALYTICS_MASK_CLASS,
ANALYTICS_MASK_TEXT_SELECTOR,
ANALYTICS_NO_CAPTURE_CLASS,
ANALYTICS_WORK_CONTENT_CLASS,
REPLAY_WORK_CONTENT_ATTRIBUTE,
maskReplayText,
workContentClassForCompany,
} from "./privacy";
import { isBlockedFromReplay, recordedTextOf as recordedTextOfWith, replayLeaks, stars } 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;
// Like rrweb: text inside the selector goes through `maskTextFn`.
return masked ? options.session_recording.maskTextFn(node.data, parent) : node.data;
}
// Through the options PostHog gets, so these cases also cover that wiring.
const recordedTextOf = (html: string, text: string) => recordedTextOfWith(html, text, recordedText);
function renderTaskPreview(description: string): string {
return renderToStaticMarkup(
<MemoryRouter>
<IssueQuicklookCard
issue={{
id: "task-1", companyId: "co-1", title: "Review access", status: "todo",
priority: "medium", updatedAt: new Date(0), description,
}}
linkTo="/ACME/issues/ACME-1"
/>
</MemoryRouter>,
);
}
/**
* Work content: masked unless the company holds no Google or Slack data
* (`ANALYTICS_WORK_CONTENT_CLASS`). Task descriptions, document bodies and
* artifact contents.
*/
const WORK_CONTENT_SURFACES: Array<{ file: string; content: string }> = [
{ file: "components/IssueLinkQuicklook.tsx", content: "data-slot=\"task-preview-description\"" },
{ file: "components/task-side-panel/TaskAttachmentPanel.tsx", content: "File is empty." },
{ 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/FileViewerSheet.tsx", content: "{lines.map(" },
];
const MASKED_SURFACES: Array<{ file: string; content: string }> = [
// The server strips hyphens and underscores from this text and cuts it at
// 280 characters, so the board cannot find a credential in it.
{ file: "components/artifacts/ArtifactCard.tsx", content: "{preview}" },
{ file: "components/LinkPreview.tsx", content: "{preview.title}" },
{ file: "components/LinkPreview.tsx", content: "{target.canonicalUrl}" },
{ 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-2xl leading-8 font-semibold tracking-tight text-foreground\", 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/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("masks work content unless the page allows it", () => {
const html = `<div class="${ANALYTICS_WORK_CONTENT_CLASS}"><p>Ship the Q3 plan</p></div>`;
expect(recordedTextOf(html, "Ship the Q3 plan")).toBe("**** *** ** ****");
document.documentElement.setAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE, "visible");
try {
expect(recordedTextOf(html, "Ship the Q3 plan")).toBe("Ship the Q3 plan");
document.documentElement.setAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE, "pending");
expect(recordedTextOf(html, "Ship the Q3 plan")).toBe("**** *** ** ****");
} finally {
document.documentElement.removeAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE);
}
});
it("keeps strict markers inside visible work content masked", () => {
document.documentElement.setAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE, "visible");
try {
const work = (inner: string) => `<div class="${ANALYTICS_WORK_CONTENT_CLASS}"><p>Plan <span>${inner}</span></p></div>`;
expect(recordedTextOf(work(`</span><span class="${ANALYTICS_MASK_CLASS}">ana@acme.com`), "ana@acme.com")).toBe("************");
expect(recordedTextOf(work(`</span><span contenteditable="true">Draft`), "Draft")).toBe("*****");
expect(recordedTextOf(`<div class="${ANALYTICS_WORK_CONTENT_CLASS} ${ANALYTICS_MASK_CLASS}"><p>Both markers</p></div>`, "Both markers")).toBe("**** *******");
// A work row inside a masked container shows (the task chat description).
expect(recordedTextOf(`<div class="${ANALYTICS_MASK_CLASS}"><div class="${ANALYTICS_WORK_CONTENT_CLASS}"><p>Brief</p></div><p>Reply</p></div>`, "Brief")).toBe("Brief");
expect(recordedTextOf(`<div class="${ANALYTICS_MASK_CLASS}"><div class="${ANALYTICS_WORK_CONTENT_CLASS}"><p>Brief</p></div><p>Reply</p></div>`, "Reply")).toBe("*****");
} finally {
document.documentElement.removeAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE);
}
});
it("shows a task preview as work content only for the selected company's own task", () => {
// A preview loads a task by id, so it can belong to another company than
// the one whose source check set the page's visible flag.
expect(workContentClassForCompany("co-1", "co-1")).toBe(ANALYTICS_WORK_CONTENT_CLASS);
expect(workContentClassForCompany("co-2", "co-1")).toBe(ANALYTICS_MASK_CLASS);
expect(workContentClassForCompany(undefined, "co-1")).toBe(ANALYTICS_MASK_CLASS);
expect(workContentClassForCompany("co-1", null)).toBe(ANALYTICS_MASK_CLASS);
expect(workContentClassForCompany(null, null)).toBe(ANALYTICS_MASK_CLASS);
const quicklook = readFileSync(join(UI_SRC, "components/IssueLinkQuicklook.tsx"), "utf8");
expect(quicklook).toContain("workContentClassForCompany(issue.companyId, selectedCompanyId)");
});
it.each([
["glpat", "-", "AbCdEfGhIjKlMnOpQr12"],
["ghp", "_", "AbCdEfGhIjKlMnOpQr12"],
["sk-proj", "-", "AbCdEfGhIjKlMnOpQr12"],
])("masks a %s credential in the rendered task preview", (prefix, separator, value) => {
const token = [prefix, value].join(separator);
const company = vi.spyOn(CompanyContext, "useOptionalCompany").mockReturnValue({
selectedCompanyId: "co-1",
} as ReturnType<typeof CompanyContext.useOptionalCompany>);
document.documentElement.setAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE, "visible");
try {
const html = renderTaskPreview(`Use **${token}** for the review.`);
expect(recordedTextOf(html, value)).toBe(`Use ${stars(token)} for the review.`);
expect(document.querySelector('[data-slot="task-preview-description"]')?.textContent)
.toBe(`Use ${token} for the review.`);
} finally {
company.mockRestore();
document.documentElement.removeAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE);
}
});
it("always masks the text preview on an artifact card", () => {
// `normalizePreviewText` on the server turns `glpat-AbC...` into
// `glpat AbC...` and cuts the text, so no token format matches it.
document.documentElement.setAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE, "visible");
try {
for (const previewText of ["Use glpat AbCdEfGhIjKlMnOpQr12 for the review.", "Ship the Q3 launch plan by Friday"]) {
const html = renderToStaticMarkup(
<ArtifactPreview artifact={{ mediaKind: "document", contentPath: null, title: "Notes", source: "document", previewText }} />,
);
expect(recordedTextOf(html, previewText.slice(0, 8))).toBe(stars(previewText));
}
} finally {
document.documentElement.removeAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE);
}
});
it("masks a document card preview when its 4,000-character cut crosses a credential", () => {
const card = (body: string) => renderToStaticMarkup(
<DocumentCard title="Runbook" summary="Deploy steps" author="Ana" updatedAt="2026-11-30" filename="runbook.md" body={body} />,
);
const prose = "Deploy the staging cluster step by step. ";
const lead = prose.repeat(97).slice(0, 3_990);
document.documentElement.setAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE, "visible");
try {
// The preview ends inside the token: `ghp_abcdef` would record in clear.
expect(recordedTextOf(card(`${lead}ghp_abcdefghijklmnopqrstuvwxyz0123 and confirm.`), "Deploy the staging"))
.not.toMatch(/[A-Za-z]/);
// A long document with no credential at the cut still shows.
expect(recordedTextOf(card(prose.repeat(200)), "Deploy the staging")).toContain("Deploy the staging cluster");
} finally {
document.documentElement.removeAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE);
}
});
it("masks a cut task preview whose text holds a credential", () => {
// The preview shows 177 characters. A credential that crosses that cut is
// too short to match its format, so its first characters would record.
const lead = "Please rotate the deploy credential for the staging cluster before the Friday release and tell the team in the channel when it is done so nobody is blocked on it. ";
const company = vi.spyOn(CompanyContext, "useOptionalCompany").mockReturnValue({
selectedCompanyId: "co-1",
} as ReturnType<typeof CompanyContext.useOptionalCompany>);
document.documentElement.setAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE, "visible");
try {
for (const token of ["ghp_abcdefghijklmnopqrstuvwxyz0123", "sk-proj-AbCdEfGhIjKlMnOpQrStUvWx1234", "Xk9pQ2mZ7rT4vB8nL3wY6sD1fH5jK0aCXk9pQ2mZ7rT4"]) {
const html = renderTaskPreview(`${lead}${token} and confirm.`);
const rendered = document.createElement("div");
rendered.innerHTML = html;
const shown = rendered.querySelector('[data-slot="task-preview-description"]')?.textContent ?? "";
// The person sees the cut text, with the start of the credential.
expect(shown.endsWith("...")).toBe(true);
expect(shown).toContain(token.slice(0, 8));
// The replay records none of it.
expect(recordedTextOf(html, "Please rotate")).toBe(stars(shown));
}
// A cut preview with no credential still shows.
const plain = renderTaskPreview(`${lead}${lead}`);
expect(recordedTextOf(plain, "Please rotate")).toContain("Please rotate the deploy credential");
} finally {
company.mockRestore();
document.documentElement.removeAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE);
}
});
it.each(["`", "*", "_", "["])("bounds %s runs before converting a task preview", (marker) => {
const convert = MarkdownPlainText.markdownToPlainText;
const conversion = vi.spyOn(MarkdownPlainText, "markdownToPlainText").mockImplementation((markdown) => {
expect(markdown.length).toBeLessThanOrEqual(2_048);
return convert(markdown);
});
const company = vi.spyOn(CompanyContext, "useOptionalCompany").mockReturnValue({
selectedCompanyId: "co-1",
} as ReturnType<typeof CompanyContext.useOptionalCompany>);
document.documentElement.setAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE, "visible");
try {
const html = renderTaskPreview(`Use ${marker.repeat(128_000)}x`);
const recorded = recordedTextOf(html, "Use");
const rendered = document.querySelector('[data-slot="task-preview-description"]')?.textContent ?? "";
expect(conversion).toHaveBeenCalledTimes(1);
expect(rendered.length).toBeLessThanOrEqual(180);
expect(rendered).toContain("Use");
expect(recorded).toBe(stars(rendered));
} finally {
company.mockRestore();
conversion.mockRestore();
document.documentElement.removeAttribute(REPLAY_WORK_CONTENT_ATTRIBUTE);
}
});
it("sends the marker selector and the work content mask function to session replay", () => {
expect(options.session_recording.maskTextSelector).toBe(ANALYTICS_MASK_TEXT_SELECTOR);
expect(options.session_recording.maskTextFn).toBe(maskReplayText);
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.each([
{ file: "components/FileViewerSheet.tsx", content: "<WorkspaceFileMarkdownBody" },
])("renders Markdown work content with the work marker at $content in $file", ({ file, content }) => {
// An inner MarkdownBody without replayContent="work" carries the strict
// mask, which wins over a work marker on its wrapper.
const source = readFileSync(join(UI_SRC, file), "utf8");
const index = source.indexOf(content);
expect(index, `content not found in ${file}`).toBeGreaterThanOrEqual(0);
expect(source.slice(index, tagEnd(source, index + 1) + 1)).toContain("replayContent=\"work\"");
});
it.each(WORK_CONTENT_SURFACES)("keeps the work content 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];
// `workContentClassForCompany` picks the work marker for the selected company's own content.
expect(elements.some((tag) => tag.includes("ANALYTICS_WORK_CONTENT_CLASS") || tag.includes("workContentClassForCompany("))).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("masks the subscription account label in AccountQuotaPanels", () => {
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 });
});
it("blocks the webhook URL and secret in WebhookFields CopyField", () => {
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);
});
it("filters incompatible OpenRouter models and masks account labels in AiConnectionPicker", () => {
document.body.innerHTML = renderToStaticMarkup(<AiConnectionPicker
adapterType="opencode_local" model="zai/glm-5" requirement={{ companyId: "company", provider: "openrouter" }}
connections={[{ id: "router", grantId: "grant", companyId: "company", provider: "openrouter", method: "api_key",
name: "Shared router", ownership: "shared", status: "connected" }]}
currentUserId="user" agentId="agent" agentName="Nova" onChange={vi.fn()} onConnect={vi.fn()} />);
expect(document.body.textContent).not.toContain("Shared router");
expect(document.querySelector<HTMLButtonElement>('[aria-label="Responsible user’s connection"]')!.disabled).toBe(true);
expect(document.body.textContent).toContain("Incompatible with this harness and model");
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 });
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 });
});
it("masks account labels in AiConnectionAccountControls, AiConnectionIdentity, and AiConnectionPoolRunDetails", () => {
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 });
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 });
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 });
});
it("blocks the setup prompt preview carrying pairing tokens in AgentSetupPrompt", async () => {
const prevMatchMedia = window.matchMedia;
window.matchMedia = ((query: string) => ({
matches: query.includes("reduce"),
media: query,
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
addListener: vi.fn(),
removeListener: vi.fn(),
onchange: null,
dispatchEvent: vi.fn(),
})) as unknown as typeof window.matchMedia;
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText: vi.fn(async () => {}) } });
const host = document.createElement("div");
document.body.append(host);
const root = createRoot(host);
try {
const prompt = "Run: paperclipai pair --token pcp_pair_8f3kQz2LmWv";
await act(async () => root.render(<AgentSetupPrompt prompt={prompt} />));
await act(async () => host.querySelector<HTMLButtonElement>("button")!.click());
expect(document.querySelector("pre[aria-label='Setup prompt']")).not.toBeNull();
expect(isBlockedFromReplay("pcp_pair_8f3kQz2LmWv", document.body)).toBe(true);
} finally {
await act(async () => root.unmount());
host.remove();
window.matchMedia = prevMatchMedia;
Reflect.deleteProperty(navigator, "clipboard");
}
});
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);
});
});