mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 11:47:42 +01:00
## 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>
1142 lines
42 KiB
TypeScript
1142 lines
42 KiB
TypeScript
import { PatchLines } from "./PatchLines";
|
|
import {
|
|
parseJsonSchemaBlock,
|
|
parseSchemaFenceMeta,
|
|
SchemaBlockCard,
|
|
type ParsedFencedSchemaBlock,
|
|
} from "./SchemaBlockCard";
|
|
import { MarkdownWordStreaming, rehypeStreamingWords } from "./MarkdownWordStreaming";
|
|
import { isValidElement, memo, useContext, useCallback, useEffect, useId, useMemo, useRef, useState, type ReactNode } from "react";
|
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
|
import { Check, Copy, MessageCircle, WrapText } from "lucide-react";
|
|
import { useCoordinatorPresentation } from "./coordinator/CoordinatorPresentation";
|
|
import { useCoordinatorChatReference } from "./coordinator/CoordinatorChatReferences";
|
|
import { SidebarDocumentLink } from "./SidebarDocumentLink";
|
|
import { buildDocumentAnnotationHash, parseDocumentAnnotationHash } from "@/lib/document-annotation-hash";
|
|
import Markdown, { defaultUrlTransform, type Components, type Options } from "react-markdown";
|
|
import remarkGfm from "remark-gfm";
|
|
import { cn } from "../lib/utils";
|
|
import { ANALYTICS_MASK_CLASS, ANALYTICS_WORK_CONTENT_CLASS } from "@/lib/analytics/privacy";
|
|
import { MarkdownUrlLink } from "./MarkdownUrlLink";
|
|
import { recognizeLinkPreview, type LinkPreviewState } from "@paperclipai/shared";
|
|
import { Link, useCaseHref } from "@/lib/router";
|
|
import { useTheme } from "../context/ThemeContext";
|
|
import { useOptionalCompany } from "../context/CompanyContext";
|
|
import { mentionChipInlineStyle, parseMentionChipHref } from "../lib/mention-chips";
|
|
import { issuesApi } from "../api/issues";
|
|
import { ApiError } from "../api/client";
|
|
import { LockedIssueChip } from "./LockedIssueChip";
|
|
import { agentsApi } from "../api/agents";
|
|
import { getCachedIssueDetail } from "../lib/issueDetailCache";
|
|
import { queryKeys } from "../lib/queryKeys";
|
|
import { parseIssueReferenceFromHref, remarkLinkIssueReferences } from "../lib/issue-reference";
|
|
import { remarkLinkCaseReferences } from "../lib/case-reference";
|
|
|
|
const CASE_HREF_RE = /^\/cases\/([A-Z][A-Z0-9]*-C\d+)$/i;
|
|
|
|
/** Recover the case identifier from a `/cases/PAP-C7` href produced by the plugin. */
|
|
function caseIdentifierFromHref(href: string | undefined): string | null {
|
|
if (!href) return null;
|
|
const match = decodeURIComponent(href.trim()).match(CASE_HREF_RE);
|
|
return match ? match[1]!.toUpperCase() : null;
|
|
}
|
|
import {
|
|
createRemarkWorkspaceFileRefs,
|
|
parseWorkspaceFileHref,
|
|
WORKSPACE_FILE_HREF_PREFIX,
|
|
type WorkspaceFileRefResolver,
|
|
} from "../lib/remark-workspace-file-refs";
|
|
import { remarkSoftBreaks } from "../lib/remark-soft-breaks";
|
|
import { StatusIcon } from "./StatusIcon";
|
|
import { taskStatusIconProps } from "../lib/task-status-presentation";
|
|
import { WorkspaceFileLink } from "./WorkspaceFileLink";
|
|
import { ExternalObjectStatusIcon } from "./ExternalObjectStatusIcon";
|
|
import {
|
|
externalObjectDisplayStatusLabel,
|
|
externalObjectLivenessLabel,
|
|
externalObjectProviderLabel,
|
|
} from "../lib/external-objects";
|
|
import { normalizeExternalObjectHref } from "../lib/external-object-href";
|
|
import { safeNavigableUrl } from "../lib/safe-url";
|
|
import { copyTextToClipboard } from "../lib/clipboard";
|
|
import type {
|
|
Agent,
|
|
ExternalObjectLivenessState,
|
|
ExternalObjectStatusCategory,
|
|
} from "@paperclipai/shared";
|
|
|
|
function MarkdownAgentMention({ agentId, children, style }: {
|
|
agentId: string;
|
|
children: ReactNode;
|
|
style?: React.CSSProperties;
|
|
}) {
|
|
const companyId = useOptionalCompany()?.selectedCompanyId;
|
|
// All mentions share the company list cache; never fetch one agent per chip.
|
|
const { data: agents } = useQuery<Agent[]>({
|
|
queryKey: queryKeys.agents.list(companyId ?? "__none__"),
|
|
queryFn: () => agentsApi.list(companyId!),
|
|
enabled: Boolean(companyId),
|
|
staleTime: 60_000,
|
|
});
|
|
const appearance = agents?.find((agent) => agent.id === agentId)?.appearance;
|
|
return (
|
|
<a
|
|
href={`/agents/${agentId}`}
|
|
className="paperclip-mention-chip paperclip-mention-chip--agent"
|
|
data-mention-kind="agent"
|
|
style={{ ...mergeWrapStyle(style), ...mentionChipInlineStyle({ kind: "agent", agentId, icon: null, appearance }) }}
|
|
>
|
|
{children}
|
|
</a>
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Host-resolved external-object metadata for inline markdown decoration.
|
|
* The renderer only consumes the host normalized fields here — plugin React
|
|
* is never mounted inline (Phase 1B security review).
|
|
*/
|
|
export interface MarkdownExternalReference {
|
|
providerKey: string | null;
|
|
objectType: string | null;
|
|
displayKey?: string | null;
|
|
iconKey?: string | null;
|
|
statusCategory: ExternalObjectStatusCategory;
|
|
liveness: ExternalObjectLivenessState;
|
|
statusLabel?: string | null;
|
|
statusIconKey?: string | null;
|
|
displayTitle?: string | null;
|
|
}
|
|
|
|
export type MarkdownExternalReferenceMap = Record<string, MarkdownExternalReference>;
|
|
|
|
interface MarkdownBodyProps {
|
|
children: string;
|
|
className?: string;
|
|
style?: React.CSSProperties;
|
|
softBreaks?: boolean;
|
|
linkIssueReferences?: boolean;
|
|
/**
|
|
* Linkify bare case identifiers (`PAP-C7`) to the case detail page. Off by
|
|
* default; enabled on surfaces behind the experimental Cases flag (PAP-12969).
|
|
*/
|
|
linkCaseReferences?: boolean;
|
|
/** Opt into Obsidian-style [[target]] / [[target|label]] wikilinks. */
|
|
enableWikiLinks?: boolean;
|
|
/** Base href used for wikilinks when no resolver is supplied. */
|
|
wikiLinkRoot?: string;
|
|
/** Optional href resolver for wikilinks. Return null to leave a token as plain text. */
|
|
resolveWikiLinkHref?: (target: string, label: string) => string | null | undefined;
|
|
/**
|
|
* Optional map of `normalizeExternalObjectHref(href)` → host-resolved metadata.
|
|
* Hrefs in the markdown that resolve to one of these keys get the inline
|
|
* status icon prefix used by §2 of the UX spec.
|
|
*/
|
|
externalReferences?: MarkdownExternalReferenceMap;
|
|
/** Optional resolver for relative image paths (e.g. within export packages) */
|
|
resolveImageSrc?: (src: string) => string | null;
|
|
/** Resolve file links to app routes; null leaves the label without a link. */
|
|
resolveLinkHref?: (href: string) => string | null;
|
|
documentIssueId?: string;
|
|
/** Called when a user clicks an inline image */
|
|
onImageClick?: (src: string, image: HTMLImageElement) => void;
|
|
/** Keep media inert as references, or omit images in compact text previews. */
|
|
mediaMode?: "render" | "reference" | "omit";
|
|
/**
|
|
* Resolver that decides which inline-code workspace file paths may be linked
|
|
* to the issue file viewer. Omitting it (or returning null) leaves every
|
|
* path-shaped code span as ordinary inline code — the fail-closed default.
|
|
*
|
|
* Its identity must change when previously-pending references become
|
|
* openable, so the markdown re-parses with the new answers.
|
|
*/
|
|
resolveWorkspaceFileRef?: WorkspaceFileRefResolver;
|
|
/**
|
|
* How session replay treats this text. `customer` (default) always masks.
|
|
* `work` is for task descriptions, document bodies and artifact contents:
|
|
* it shows only when the company holds no Google or Slack data
|
|
* (`ANALYTICS_WORK_CONTENT_CLASS`).
|
|
*/
|
|
replayContent?: "customer" | "work";
|
|
}
|
|
|
|
let mermaidLoaderPromise: Promise<typeof import("mermaid").default> | null = null;
|
|
|
|
function MarkdownIssueLink({
|
|
issuePathId,
|
|
href,
|
|
children,
|
|
documentLink = false,
|
|
}: {
|
|
issuePathId: string;
|
|
href: string;
|
|
children: ReactNode;
|
|
documentLink?: boolean;
|
|
}) {
|
|
const queryClient = useQueryClient();
|
|
const chatReference = useCoordinatorChatReference(issuePathId);
|
|
const [engaged, setEngaged] = useState(false);
|
|
const { data, error } = useQuery({
|
|
queryKey: queryKeys.issues.detail(issuePathId),
|
|
// A transcript can mention dozens of tasks. Their full detail projections
|
|
// are hover information, not prerequisites for reading this conversation.
|
|
enabled: engaged && (!chatReference || documentLink),
|
|
placeholderData: getCachedIssueDetail(queryClient, issuePathId),
|
|
queryFn: () => issuesApi.get(issuePathId),
|
|
staleTime: 60_000,
|
|
// A private issue 404s on direct fetch (indistinguishable from deleted, by
|
|
// design). Don't burn retries on it — settle straight to the locked chip.
|
|
retry: (failureCount, err) =>
|
|
!(err instanceof ApiError && err.status === 404) && failureCount < 3,
|
|
});
|
|
|
|
if (chatReference && !documentLink) {
|
|
const suffix = href.match(/[?#].*$/)?.[0] ?? "";
|
|
return <Link to={`${chatReference.href}${suffix}`} disableIssueQuicklook
|
|
className="font-normal underline" data-mention-kind="chat" aria-label={chatReference.label}>
|
|
<MessageCircle aria-hidden className="relative -top-px mr-1 inline-block size-4 align-middle" />{chatReference.label}
|
|
</Link>;
|
|
}
|
|
// Mention of an issue this viewer can't read → existence-only locked chip
|
|
// (never a title or a link), matching the locked-stub treatment on edges.
|
|
if (error instanceof ApiError && error.status === 404) {
|
|
return <LockedIssueChip identifier={issuePathId} unavailable />;
|
|
}
|
|
|
|
if (documentLink) {
|
|
return <SidebarDocumentLink href={href} variant="inline" onPointerEnter={() => setEngaged(true)} onFocus={() => setEngaged(true)}>
|
|
<span className="underline underline-offset-4">{children}</span>
|
|
</SidebarDocumentLink>;
|
|
}
|
|
|
|
const identifier = data?.identifier ?? issuePathId;
|
|
const title = data?.title ?? identifier;
|
|
const status = data?.status;
|
|
// Same presentation inputs as every task view, so a covered blocked task is
|
|
// the blue in-queue glyph here too, not the red blocked one (BUG-07).
|
|
const statusIconProps = data && status ? taskStatusIconProps({ ...data, status }) : null;
|
|
const issueLabel = title !== identifier ? `Issue ${identifier}: ${title}` : `Issue ${identifier}`;
|
|
|
|
// Until the fetch settles we don't yet know whether this viewer can read the
|
|
// issue. Keep the mention a plain link (clickable, styled as today) but hold
|
|
// off mounting the IssueLinkQuicklook hover preview — a Radix Popover portal —
|
|
// until `data` confirms the issue is readable.
|
|
// - Correctness (PAP-16070): a private mention 404s straight to the locked
|
|
// chip. Mounting the quicklook popover during the loading `<Link>` only to
|
|
// tear the portal down and swap in a plain `<span>` chip on the 404 is the
|
|
// element churn that crashed the chat transcript's primary renderer (it
|
|
// fell through to the safe fallback). Loading link → chip stays portal-free.
|
|
// - Privacy: don't prefetch / hover-preview an issue of unconfirmed
|
|
// readability. `data-mention-pending` marks the transient state for tests.
|
|
const pending = !data;
|
|
|
|
return (
|
|
<Link
|
|
to={href}
|
|
data-mention-kind="issue"
|
|
disableIssueQuicklook={pending}
|
|
data-mention-pending={pending ? "true" : undefined}
|
|
onPointerEnter={() => setEngaged(true)}
|
|
onFocus={() => setEngaged(true)}
|
|
// Boxless inline mention: the unified status glyph + a regular-weight
|
|
// underlined link, optically centered with the body text.
|
|
className={cn("paperclip-markdown-issue-ref", "font-normal underline")}
|
|
title={title}
|
|
aria-label={issueLabel}
|
|
>
|
|
{statusIconProps ? (
|
|
<StatusIcon {...statusIconProps} size="md" className="relative -top-px mr-1 inline-block h-4 w-4 align-middle" />
|
|
) : null}
|
|
{children}
|
|
</Link>
|
|
);
|
|
}
|
|
|
|
function MarkdownCaseLink({
|
|
identifier,
|
|
children,
|
|
}: {
|
|
identifier: string;
|
|
children: ReactNode;
|
|
}) {
|
|
// Cases resolve via the get-by-identifier route; navigate there on click.
|
|
// Kept boxless/underlined to match the issue mention treatment.
|
|
const caseHref = useCaseHref();
|
|
return (
|
|
<Link
|
|
to={caseHref(identifier)}
|
|
data-mention-kind="case"
|
|
className={cn("paperclip-markdown-case-ref", "font-normal underline")}
|
|
aria-label={`Case ${identifier}`}
|
|
>
|
|
{children}
|
|
</Link>
|
|
);
|
|
}
|
|
|
|
function MarkdownExternalLink({
|
|
href,
|
|
reference,
|
|
children,
|
|
}: {
|
|
href: string;
|
|
reference: MarkdownExternalReference;
|
|
children: ReactNode;
|
|
}) {
|
|
const provider = externalObjectProviderLabel(reference.providerKey);
|
|
const displayKey = reference.displayKey?.trim() || provider;
|
|
const statusLabel = externalObjectDisplayStatusLabel(reference);
|
|
const livenessLabel = externalObjectLivenessLabel(reference.liveness);
|
|
const livenessSuffix = reference.liveness === "fresh" || reference.liveness === "unknown"
|
|
|| livenessLabel.toLowerCase() === statusLabel.toLowerCase()
|
|
? ""
|
|
: ` (${livenessLabel})`;
|
|
const titleParts = [
|
|
reference.displayTitle ?? `${displayKey} ${statusLabel}`,
|
|
`${displayKey} — ${statusLabel}${livenessSuffix}`,
|
|
];
|
|
const title = titleParts.filter(Boolean).join(" · ");
|
|
if (recognizeLinkPreview(href)) {
|
|
const knownState: LinkPreviewState = reference.statusIconKey === "git-merge" || reference.statusLabel === "Merged" ? "merged"
|
|
: reference.statusLabel === "Merge conflicts" ? "conflicts"
|
|
: reference.statusLabel === "Draft" ? "draft"
|
|
: reference.statusCategory === "open" ? "open"
|
|
: reference.statusCategory === "closed" ? "closed" : "unknown";
|
|
return <MarkdownUrlLink href={href} title={title} knownState={knownState}
|
|
externalStatus={{ category: reference.statusCategory, liveness: reference.liveness,
|
|
ariaLabel: `${displayKey} ${statusLabel}${livenessSuffix}: ${reference.displayTitle ?? href}` }}>
|
|
{children}
|
|
</MarkdownUrlLink>;
|
|
}
|
|
return (
|
|
<a
|
|
href={href}
|
|
target="_blank"
|
|
rel="noopener noreferrer"
|
|
data-external-link="resolved"
|
|
data-external-status={reference.statusCategory}
|
|
data-external-liveness={reference.liveness}
|
|
title={title}
|
|
aria-label={`${displayKey} ${statusLabel}${livenessSuffix}: ${reference.displayTitle ?? href}`}
|
|
className="paperclip-markdown-external-ref"
|
|
>
|
|
<ExternalObjectStatusIcon
|
|
category={reference.statusCategory}
|
|
liveness={reference.liveness}
|
|
statusIconKey={reference.statusIconKey}
|
|
label={`${displayKey}: ${statusLabel}`}
|
|
inline
|
|
/>
|
|
{children}
|
|
</a>
|
|
);
|
|
}
|
|
|
|
function loadMermaid() {
|
|
if (!mermaidLoaderPromise) {
|
|
mermaidLoaderPromise = import("mermaid").then((module) => module.default);
|
|
}
|
|
return mermaidLoaderPromise;
|
|
}
|
|
|
|
const wrapAnywhereStyle: React.CSSProperties = {
|
|
overflowWrap: "anywhere",
|
|
wordBreak: "break-word",
|
|
};
|
|
|
|
const scrollableBlockStyle: React.CSSProperties = {
|
|
maxWidth: "100%",
|
|
overflowX: "auto",
|
|
};
|
|
|
|
const codeBlockActionsStyle: React.CSSProperties = {
|
|
position: "absolute",
|
|
top: "0.4rem",
|
|
right: "0.4rem",
|
|
display: "inline-flex",
|
|
alignItems: "center",
|
|
gap: "0.25rem",
|
|
};
|
|
|
|
export const codeBlockActionStyle: React.CSSProperties = {
|
|
position: "static",
|
|
opacity: 1,
|
|
display: "inline-flex",
|
|
alignItems: "center",
|
|
justifyContent: "center",
|
|
gap: "0.25rem",
|
|
minHeight: "1.55rem",
|
|
padding: "0.2rem 0.4rem",
|
|
borderRadius: "calc(var(--radius) - 4px)",
|
|
border: "1px solid color-mix(in oklab, var(--foreground) 14%, transparent)",
|
|
backgroundColor: "var(--background)",
|
|
color: "var(--muted-foreground)",
|
|
fontSize: "var(--text-micro)",
|
|
lineHeight: 1,
|
|
cursor: "pointer",
|
|
};
|
|
|
|
const codeBlockWrapActionStyle: React.CSSProperties = {
|
|
...codeBlockActionStyle,
|
|
width: "1.55rem",
|
|
paddingInline: 0,
|
|
};
|
|
|
|
const tableCellWrapStyle: React.CSSProperties = {
|
|
overflowWrap: "anywhere",
|
|
wordBreak: "normal",
|
|
};
|
|
|
|
function isHtmlCommentNode(node: MarkdownAstNode) {
|
|
return node.type === "html" && typeof node.value === "string" && /^<!--[\s\S]*-->$/.test(node.value.trim());
|
|
}
|
|
|
|
function isEscapedHtmlCommentPlaceholder(node: MarkdownAstNode) {
|
|
if (node.type !== "text" || typeof node.value !== "string") return false;
|
|
const value = node.value.trim();
|
|
return /^\\?<!--(?:\s*-{0,2}>?)?$/.test(value) || /^<!--(?:\s*-{0,2}(?:>)?)?$/.test(value);
|
|
}
|
|
|
|
function remarkDropHtmlComments() {
|
|
return (tree: MarkdownAstNode) => {
|
|
const visit = (node: MarkdownAstNode) => {
|
|
const children = node.children;
|
|
if (!children) return;
|
|
node.children = children.filter((child) => !isHtmlCommentNode(child) && !isEscapedHtmlCommentPlaceholder(child));
|
|
for (const child of node.children) {
|
|
visit(child);
|
|
}
|
|
};
|
|
visit(tree);
|
|
};
|
|
}
|
|
|
|
function mergeWrapStyle(style?: React.CSSProperties): React.CSSProperties {
|
|
return {
|
|
...wrapAnywhereStyle,
|
|
...style,
|
|
};
|
|
}
|
|
|
|
function mergeTableCellStyle(style?: React.CSSProperties): React.CSSProperties {
|
|
return {
|
|
...tableCellWrapStyle,
|
|
...style,
|
|
};
|
|
}
|
|
|
|
function mergeScrollableBlockStyle(style?: React.CSSProperties): React.CSSProperties {
|
|
return {
|
|
...scrollableBlockStyle,
|
|
...style,
|
|
};
|
|
}
|
|
|
|
function flattenText(value: ReactNode): string {
|
|
if (value == null) return "";
|
|
if (typeof value === "string" || typeof value === "number") return String(value);
|
|
if (Array.isArray(value)) return value.map((item) => flattenText(item)).join("");
|
|
if (isValidElement<{ children?: ReactNode }>(value)) {
|
|
return flattenText(value.props.children);
|
|
}
|
|
return "";
|
|
}
|
|
|
|
function extractMermaidSource(children: ReactNode): string | null {
|
|
if (!isValidElement(children)) return null;
|
|
const childProps = children.props as { className?: unknown; children?: ReactNode };
|
|
if (typeof childProps.className !== "string") return null;
|
|
if (!/\blanguage-mermaid\b/i.test(childProps.className)) return null;
|
|
return flattenText(childProps.children).replace(/\n$/, "");
|
|
}
|
|
|
|
function extractSchemaBlockSource(children: ReactNode): ParsedFencedSchemaBlock | null {
|
|
const code = Array.isArray(children) ? children.find(isValidElement) : children;
|
|
if (!isValidElement(code)) return null;
|
|
const childProps = code.props as {
|
|
className?: unknown;
|
|
children?: ReactNode;
|
|
"data-paperclip-schema-ref"?: unknown;
|
|
};
|
|
if (typeof childProps.className !== "string") return null;
|
|
if (!/\blanguage-json\b/i.test(childProps.className)) return null;
|
|
const explicitRef =
|
|
typeof childProps["data-paperclip-schema-ref"] === "string"
|
|
? childProps["data-paperclip-schema-ref"]
|
|
: null;
|
|
const rawCode = flattenText(childProps.children).replace(/\n$/, "");
|
|
return parseJsonSchemaBlock(rawCode, explicitRef);
|
|
}
|
|
|
|
function remarkSchemaCodeBlocks() {
|
|
return (tree: MarkdownAstNode) => {
|
|
const visit = (node: MarkdownAstNode) => {
|
|
if (
|
|
node.type === "code" &&
|
|
typeof node.lang === "string" &&
|
|
node.lang.toLowerCase() === "json"
|
|
) {
|
|
const parsedMeta = parseSchemaFenceMeta(node.meta);
|
|
if (parsedMeta) {
|
|
node.data = {
|
|
...node.data,
|
|
hProperties: {
|
|
...node.data?.hProperties,
|
|
"data-paperclip-schema-ref": parsedMeta.ref,
|
|
},
|
|
};
|
|
}
|
|
}
|
|
if (!node.children) return;
|
|
for (const child of node.children) {
|
|
visit(child);
|
|
}
|
|
};
|
|
visit(tree);
|
|
};
|
|
}
|
|
|
|
function safeMarkdownUrlTransform(url: string): string {
|
|
if (url.startsWith(WORKSPACE_FILE_HREF_PREFIX)) return url;
|
|
const mention = parseMentionChipHref(url);
|
|
if (!mention) return defaultUrlTransform(url);
|
|
if (mention.kind === "issue") return safeNavigableUrl(url) ?? "";
|
|
return url;
|
|
}
|
|
|
|
type MarkdownAstNode = {
|
|
type?: string;
|
|
value?: string;
|
|
lang?: string | null;
|
|
meta?: string | null;
|
|
children?: MarkdownAstNode[];
|
|
url?: string;
|
|
title?: string | null;
|
|
data?: {
|
|
hProperties?: Record<string, string>;
|
|
};
|
|
};
|
|
|
|
type ParsedWikiLink = {
|
|
target: string;
|
|
label: string;
|
|
};
|
|
|
|
const WIKI_LINK_PATTERN = /\[\[([^\]\r\n]+)\]\]/g;
|
|
const WIKI_LINK_SKIP_PARENT_TYPES = new Set([
|
|
"definition",
|
|
"image",
|
|
"imageReference",
|
|
"link",
|
|
"linkReference",
|
|
]);
|
|
|
|
function parseWikiLinkBody(body: string): ParsedWikiLink | null {
|
|
const [rawTarget, ...rawLabelParts] = body.split("|");
|
|
const target = rawTarget?.trim() ?? "";
|
|
const label = rawLabelParts.length > 0 ? rawLabelParts.join("|").trim() : target;
|
|
if (!target || target.includes("[") || target.includes("]")) return null;
|
|
return {
|
|
target,
|
|
label: label || target,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Agents sometimes write a company link as `//PAP/agents/...`. A browser reads
|
|
* that as a protocol-relative URL for a host named after the company prefix,
|
|
* which leaves the app. When the "host" is exactly a known company prefix, the
|
|
* link can only mean the company path, so render it as `/PAP/agents/...`.
|
|
*/
|
|
export function companyPathFromProtocolRelativeHref(href: string | undefined, knownPrefixes?: readonly string[]): string | undefined {
|
|
if (!href || !knownPrefixes?.length) return href;
|
|
const match = /^\/\/([^/?#]+)((?:[/?#].*)?)$/.exec(href.trim());
|
|
if (!match || !knownPrefixes.includes(match[1]!)) return href;
|
|
return `/${match[1]}${match[2] || ""}`;
|
|
}
|
|
|
|
function encodeWikiLinkTarget(target: string): string | null {
|
|
const trimmed = target.trim();
|
|
if (!trimmed || /^[a-z][a-z\d+.-]*:/i.test(trimmed) || trimmed.startsWith("//")) return null;
|
|
|
|
const hashIndex = trimmed.indexOf("#");
|
|
const rawPath = (hashIndex >= 0 ? trimmed.slice(0, hashIndex) : trimmed)
|
|
.trim()
|
|
.replace(/^\/+/, "");
|
|
if (
|
|
!rawPath ||
|
|
rawPath.includes("\\") ||
|
|
rawPath.split("/").some((segment) => !segment || segment === "." || segment === "..")
|
|
) {
|
|
return null;
|
|
}
|
|
|
|
const encodedPath = rawPath.split("/").map((segment) => encodeURIComponent(segment)).join("/");
|
|
const rawHash = hashIndex >= 0 ? trimmed.slice(hashIndex + 1).trim() : "";
|
|
return rawHash ? `${encodedPath}#${encodeURIComponent(rawHash)}` : encodedPath;
|
|
}
|
|
|
|
function defaultWikiLinkHref(target: string, wikiLinkRoot?: string): string | null {
|
|
const encodedTarget = encodeWikiLinkTarget(target);
|
|
if (!encodedTarget) return null;
|
|
const root = wikiLinkRoot?.trim().replace(/\/+$/, "") ?? "";
|
|
return root ? `${root}/${encodedTarget}` : encodedTarget;
|
|
}
|
|
|
|
function createWikiLinkNode(href: string, wikiLink: ParsedWikiLink): MarkdownAstNode {
|
|
return {
|
|
type: "link",
|
|
url: href,
|
|
title: null,
|
|
data: {
|
|
hProperties: {
|
|
"data-paperclip-wiki-link": "true",
|
|
"data-paperclip-wiki-target": wikiLink.target,
|
|
},
|
|
},
|
|
children: [{ type: "text", value: wikiLink.label }],
|
|
};
|
|
}
|
|
|
|
function splitTextByWikiLinks(
|
|
value: string,
|
|
options: {
|
|
wikiLinkRoot?: string;
|
|
resolveWikiLinkHref?: (target: string, label: string) => string | null | undefined;
|
|
},
|
|
): MarkdownAstNode[] {
|
|
const nodes: MarkdownAstNode[] = [];
|
|
let lastIndex = 0;
|
|
|
|
for (const match of value.matchAll(WIKI_LINK_PATTERN)) {
|
|
const raw = match[0] ?? "";
|
|
const body = match[1] ?? "";
|
|
const start = match.index ?? 0;
|
|
if (start > lastIndex) {
|
|
nodes.push({ type: "text", value: value.slice(lastIndex, start) });
|
|
}
|
|
|
|
const wikiLink = parseWikiLinkBody(body);
|
|
let resolvedHref: string | null = null;
|
|
if (wikiLink) {
|
|
if (options.resolveWikiLinkHref) {
|
|
const customHref = options.resolveWikiLinkHref(wikiLink.target, wikiLink.label);
|
|
resolvedHref = customHref === undefined
|
|
? defaultWikiLinkHref(wikiLink.target, options.wikiLinkRoot)
|
|
: customHref;
|
|
} else {
|
|
resolvedHref = defaultWikiLinkHref(wikiLink.target, options.wikiLinkRoot);
|
|
}
|
|
}
|
|
|
|
if (wikiLink && resolvedHref) {
|
|
nodes.push(createWikiLinkNode(resolvedHref, wikiLink));
|
|
} else {
|
|
nodes.push({ type: "text", value: raw });
|
|
}
|
|
lastIndex = start + raw.length;
|
|
}
|
|
|
|
if (lastIndex < value.length) {
|
|
nodes.push({ type: "text", value: value.slice(lastIndex) });
|
|
}
|
|
|
|
return nodes;
|
|
}
|
|
|
|
function transformWikiLinkChildren(
|
|
node: MarkdownAstNode,
|
|
options: {
|
|
wikiLinkRoot?: string;
|
|
resolveWikiLinkHref?: (target: string, label: string) => string | null | undefined;
|
|
},
|
|
) {
|
|
if (!node.children || WIKI_LINK_SKIP_PARENT_TYPES.has(node.type ?? "")) return;
|
|
|
|
node.children = node.children.flatMap((child) => {
|
|
if (child.type === "text" && typeof child.value === "string" && child.value.includes("[[")) {
|
|
return splitTextByWikiLinks(child.value, options);
|
|
}
|
|
transformWikiLinkChildren(child, options);
|
|
return child;
|
|
});
|
|
}
|
|
|
|
function createRemarkWikiLinks(options: {
|
|
wikiLinkRoot?: string;
|
|
resolveWikiLinkHref?: (target: string, label: string) => string | null | undefined;
|
|
}) {
|
|
return function remarkWikiLinks() {
|
|
return (tree: MarkdownAstNode) => {
|
|
transformWikiLinkChildren(tree, options);
|
|
};
|
|
};
|
|
}
|
|
|
|
function CodeBlock({
|
|
children,
|
|
preProps,
|
|
}: {
|
|
children: ReactNode;
|
|
preProps: React.HTMLAttributes<HTMLPreElement>;
|
|
}) {
|
|
const code = Array.isArray(children) ? children.find(isValidElement) : children;
|
|
const patchCode = isValidElement<{ className?: string; children?: ReactNode }>(code)
|
|
&& /\blanguage-(diff|patch)\b/i.test(code.props.className ?? "");
|
|
const patchText = patchCode ? flattenText(code.props.children) : null;
|
|
const [copied, setCopied] = useState(false);
|
|
const [failed, setFailed] = useState(false);
|
|
const [wrapLines, setWrapLines] = useState(false);
|
|
const preRef = useRef<HTMLPreElement>(null);
|
|
const timerRef = useRef<ReturnType<typeof setTimeout>>(undefined);
|
|
|
|
useEffect(() => () => clearTimeout(timerRef.current), []);
|
|
|
|
const handleCopy = useCallback(async () => {
|
|
const text = patchText ?? preRef.current?.innerText ?? flattenText(children);
|
|
try {
|
|
await copyTextToClipboard(text);
|
|
setFailed(false);
|
|
setCopied(true);
|
|
} catch {
|
|
setFailed(true);
|
|
setCopied(true);
|
|
}
|
|
clearTimeout(timerRef.current);
|
|
timerRef.current = setTimeout(() => {
|
|
setCopied(false);
|
|
setFailed(false);
|
|
}, 1500);
|
|
}, [children, patchText]);
|
|
|
|
const copyLabel = failed ? "Copy failed" : copied ? "Copied!" : "Copy";
|
|
const wrapLabel = wrapLines ? "Unwrap lines" : "Wrap lines";
|
|
|
|
return (
|
|
<div className="paperclip-markdown-codeblock" data-wrap-lines={wrapLines || undefined}>
|
|
<pre
|
|
{...preProps}
|
|
ref={preRef}
|
|
style={{
|
|
...mergeScrollableBlockStyle(preProps.style as React.CSSProperties | undefined),
|
|
...(wrapLines
|
|
? {
|
|
overflowX: "hidden",
|
|
whiteSpace: "pre-wrap",
|
|
overflowWrap: "anywhere",
|
|
wordBreak: "break-word",
|
|
}
|
|
: null),
|
|
}}
|
|
>
|
|
{patchText !== null ? <code className="language-diff"><PatchLines text={patchText} /></code> : children}
|
|
</pre>
|
|
<div
|
|
className="paperclip-markdown-codeblock-actions"
|
|
style={codeBlockActionsStyle}
|
|
data-active={copied || failed || wrapLines || undefined}
|
|
>
|
|
<button
|
|
type="button"
|
|
onClick={() => setWrapLines((value) => !value)}
|
|
aria-label={wrapLabel}
|
|
title={wrapLabel}
|
|
className="paperclip-markdown-codeblock-action paperclip-markdown-codeblock-wrap"
|
|
style={wrapLines
|
|
? {
|
|
...codeBlockWrapActionStyle,
|
|
borderColor: "color-mix(in oklab, var(--primary) 38%, transparent)",
|
|
color: "var(--primary)",
|
|
}
|
|
: codeBlockWrapActionStyle}
|
|
aria-pressed={wrapLines}
|
|
data-active={wrapLines || undefined}
|
|
>
|
|
<WrapText aria-hidden="true" className="h-3.5 w-3.5" />
|
|
</button>
|
|
<button
|
|
type="button"
|
|
onClick={handleCopy}
|
|
aria-label="Copy code"
|
|
title={copyLabel}
|
|
className="paperclip-markdown-codeblock-action paperclip-markdown-codeblock-copy"
|
|
style={codeBlockActionStyle}
|
|
data-copied={copied || undefined}
|
|
data-failed={failed || undefined}
|
|
>
|
|
{copied && !failed ? (
|
|
<Check aria-hidden="true" className="h-3.5 w-3.5" />
|
|
) : (
|
|
<Copy aria-hidden="true" className="h-3.5 w-3.5" />
|
|
)}
|
|
<span className="paperclip-markdown-codeblock-action-label">{copyLabel}</span>
|
|
</button>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function MermaidDiagramBlock({ source, darkMode }: { source: string; darkMode: boolean }) {
|
|
const renderId = useId().replace(/[^a-zA-Z0-9_-]/g, "");
|
|
const [svg, setSvg] = useState<string | null>(null);
|
|
const [error, setError] = useState<string | null>(null);
|
|
|
|
useEffect(() => {
|
|
let active = true;
|
|
setSvg(null);
|
|
setError(null);
|
|
|
|
loadMermaid()
|
|
.then(async (mermaid) => {
|
|
mermaid.initialize({
|
|
startOnLoad: false,
|
|
securityLevel: "strict",
|
|
theme: darkMode ? "dark" : "default",
|
|
fontFamily: "inherit",
|
|
suppressErrorRendering: true,
|
|
});
|
|
const rendered = await mermaid.render(`paperclip-mermaid-${renderId}`, source);
|
|
if (!active) return;
|
|
setSvg(rendered.svg);
|
|
})
|
|
.catch((err) => {
|
|
if (!active) return;
|
|
const message =
|
|
err instanceof Error && err.message
|
|
? err.message
|
|
: "Failed to render Mermaid diagram.";
|
|
setError(message);
|
|
});
|
|
|
|
return () => {
|
|
active = false;
|
|
};
|
|
}, [darkMode, renderId, source]);
|
|
|
|
return (
|
|
<div className="paperclip-mermaid">
|
|
{svg ? (
|
|
<div dangerouslySetInnerHTML={{ __html: svg }} />
|
|
) : (
|
|
<>
|
|
<p className={cn("paperclip-mermaid-status", error && "paperclip-mermaid-status-error")}>
|
|
{error ? `Unable to render Mermaid diagram: ${error}` : "Rendering Mermaid diagram..."}
|
|
</p>
|
|
<pre className="paperclip-mermaid-source">
|
|
<code className="language-mermaid">{source}</code>
|
|
</pre>
|
|
</>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function MarkdownBodyImpl({
|
|
children,
|
|
className,
|
|
style,
|
|
softBreaks = true,
|
|
linkIssueReferences = true,
|
|
linkCaseReferences = false,
|
|
enableWikiLinks = false,
|
|
wikiLinkRoot,
|
|
resolveWikiLinkHref,
|
|
externalReferences,
|
|
resolveImageSrc,
|
|
resolveLinkHref,
|
|
documentIssueId,
|
|
onImageClick,
|
|
mediaMode = "render",
|
|
resolveWorkspaceFileRef,
|
|
replayContent = "customer",
|
|
}: MarkdownBodyProps) {
|
|
const { theme } = useTheme();
|
|
const coordinator = useCoordinatorPresentation();
|
|
const streamWords = useContext(MarkdownWordStreaming);
|
|
const scopedUrlTransform = useCallback((url: string, key: string) => {
|
|
const safeUrl = safeMarkdownUrlTransform(url);
|
|
const target = key === "href" && documentIssueId ? parseDocumentAnnotationHash(safeUrl) : null;
|
|
return target && !target.documentIssueId ? buildDocumentAnnotationHash({ ...target, documentIssueId }) : safeUrl;
|
|
}, [documentIssueId]);
|
|
// Read company prefixes non-throwingly: MarkdownBody renders in surfaces that
|
|
// may lack a CompanyProvider. A null context (or no companies yet) leaves
|
|
// knownPrefixes undefined, which keeps issue auto-linking permissive.
|
|
const company = useOptionalCompany();
|
|
const companies = company?.companies;
|
|
// Stable identity so it can feed the memoized remark plugins without
|
|
// re-creating them (and forcing a full markdown re-parse) every render.
|
|
const knownPrefixes = useMemo(
|
|
() => (companies?.length ? companies.map((c) => c.issuePrefix) : undefined),
|
|
[companies],
|
|
);
|
|
const knownPrefixSet = useMemo(
|
|
() => (knownPrefixes ? new Set(knownPrefixes.map((prefix) => prefix.toUpperCase())) : undefined),
|
|
[knownPrefixes],
|
|
);
|
|
const externalReferenceLookup = useMemo<MarkdownExternalReferenceMap | null>(() => {
|
|
if (!externalReferences) return null;
|
|
const lookup: MarkdownExternalReferenceMap = {};
|
|
for (const [key, value] of Object.entries(externalReferences)) {
|
|
const normalized = normalizeExternalObjectHref(key) ?? key;
|
|
lookup[normalized] = value;
|
|
}
|
|
return lookup;
|
|
}, [externalReferences]);
|
|
// react-markdown treats the values of `components` as component *types* and
|
|
// the `remarkPlugins` array by identity. Rebuilding either on every render
|
|
// forces react-markdown to unmount/remount the rendered tree, which discards
|
|
// scroll position and text selection and causes visible flashing when a
|
|
// parent re-renders frequently (see PAP-10767). Memoize both so re-renders
|
|
// that don't change the inputs are cheap and non-destructive.
|
|
const remarkPlugins = useMemo<NonNullable<Options["remarkPlugins"]>>(() => {
|
|
const plugins: NonNullable<Options["remarkPlugins"]> = [
|
|
remarkGfm,
|
|
remarkDropHtmlComments,
|
|
remarkSchemaCodeBlocks,
|
|
];
|
|
if (enableWikiLinks) {
|
|
plugins.push(createRemarkWikiLinks({ wikiLinkRoot, resolveWikiLinkHref }));
|
|
}
|
|
if (resolveWorkspaceFileRef) {
|
|
plugins.push(createRemarkWorkspaceFileRefs(resolveWorkspaceFileRef));
|
|
}
|
|
if (linkIssueReferences) {
|
|
plugins.push([remarkLinkIssueReferences, { knownPrefixes }]);
|
|
}
|
|
if (linkCaseReferences) {
|
|
plugins.push([remarkLinkCaseReferences, { knownPrefixes }]);
|
|
}
|
|
if (softBreaks) {
|
|
plugins.push(remarkSoftBreaks);
|
|
}
|
|
return plugins;
|
|
}, [enableWikiLinks, wikiLinkRoot, resolveWikiLinkHref, resolveWorkspaceFileRef, linkIssueReferences, linkCaseReferences, knownPrefixes, softBreaks]);
|
|
const components = useMemo<Components>(() => {
|
|
const map: Components = {
|
|
p: ({ node: _node, style: paragraphStyle, children: paragraphChildren, ...paragraphProps }) => (
|
|
<p {...paragraphProps} style={mergeWrapStyle(paragraphStyle as React.CSSProperties | undefined)}>
|
|
{paragraphChildren}
|
|
</p>
|
|
),
|
|
li: ({ node: _node, style: listItemStyle, children: listItemChildren, ...listItemProps }) => (
|
|
<li {...listItemProps} style={mergeWrapStyle(listItemStyle as React.CSSProperties | undefined)}>
|
|
{listItemChildren}
|
|
</li>
|
|
),
|
|
blockquote: ({ node: _node, style: blockquoteStyle, children: blockquoteChildren, ...blockquoteProps }) => (
|
|
<blockquote {...blockquoteProps} style={mergeWrapStyle(blockquoteStyle as React.CSSProperties | undefined)}>
|
|
{blockquoteChildren}
|
|
</blockquote>
|
|
),
|
|
table: ({ node: _node, style: tableStyle, children: tableChildren, ...tableProps }) => (
|
|
<div
|
|
className="paperclip-markdown-table-scroll max-w-full overflow-x-auto"
|
|
role="region"
|
|
aria-label="Scrollable table"
|
|
tabIndex={0}
|
|
>
|
|
<table {...tableProps} style={tableStyle as React.CSSProperties | undefined}>
|
|
{tableChildren}
|
|
</table>
|
|
</div>
|
|
),
|
|
td: ({ node: _node, style: tableCellStyle, children: tableCellChildren, ...tableCellProps }) => (
|
|
<td {...tableCellProps} style={mergeTableCellStyle(tableCellStyle as React.CSSProperties | undefined)}>
|
|
{tableCellChildren}
|
|
</td>
|
|
),
|
|
th: ({ node: _node, style: tableHeaderStyle, children: tableHeaderChildren, ...tableHeaderProps }) => (
|
|
<th {...tableHeaderProps} style={mergeTableCellStyle(tableHeaderStyle as React.CSSProperties | undefined)}>
|
|
{tableHeaderChildren}
|
|
</th>
|
|
),
|
|
pre: ({ node: _node, children: preChildren, ...preProps }) => {
|
|
const mermaidSource = extractMermaidSource(preChildren);
|
|
if (mermaidSource && mediaMode === "render") {
|
|
return <MermaidDiagramBlock source={mermaidSource} darkMode={theme === "dark"} />;
|
|
}
|
|
const schemaBlock = mediaMode === "render" ? extractSchemaBlockSource(preChildren) : null;
|
|
if (schemaBlock) {
|
|
return <SchemaBlockCard block={schemaBlock.block} rawJson={schemaBlock.rawJson} />;
|
|
}
|
|
return <CodeBlock preProps={preProps}>{preChildren}</CodeBlock>;
|
|
},
|
|
code: ({ node: _node, style: codeStyle, children: codeChildren, ...codeProps }) => (
|
|
<code {...codeProps} style={mergeWrapStyle(codeStyle as React.CSSProperties | undefined)}>
|
|
{codeChildren}
|
|
</code>
|
|
),
|
|
a: ({ node: _node, href: rawHref, style: linkStyle, children: linkChildren, ...anchorProps }) => {
|
|
const href = companyPathFromProtocolRelativeHref(rawHref, knownPrefixes);
|
|
const workspaceFileRef = parseWorkspaceFileHref(href);
|
|
if (workspaceFileRef) {
|
|
return (
|
|
<WorkspaceFileLink
|
|
workspaceFileRef={workspaceFileRef}
|
|
label={linkChildren}
|
|
className={typeof anchorProps.className === "string" ? anchorProps.className : undefined}
|
|
/>
|
|
);
|
|
}
|
|
|
|
const dataProps = anchorProps as Record<string, unknown>;
|
|
const isWikiLink = dataProps["data-paperclip-wiki-link"] === "true";
|
|
if (isWikiLink && href && !/^[a-z][a-z\d+.-]*:/i.test(href) && !href.startsWith("//")) {
|
|
return (
|
|
<Link
|
|
to={href}
|
|
{...anchorProps}
|
|
rel="noreferrer"
|
|
style={mergeWrapStyle(linkStyle as React.CSSProperties | undefined)}
|
|
>
|
|
{linkChildren}
|
|
</Link>
|
|
);
|
|
}
|
|
|
|
const issueRef = linkIssueReferences ? parseIssueReferenceFromHref(href, knownPrefixSet) : null;
|
|
const documentHash = href?.includes("#") ? href.slice(href.indexOf("#")) : null;
|
|
const documentLink = Boolean(coordinator && documentHash && parseDocumentAnnotationHash(documentHash));
|
|
if (documentLink && href?.startsWith("#")) {
|
|
return <SidebarDocumentLink href={href} variant="inline">
|
|
<span className="underline underline-offset-4">{linkChildren}</span>
|
|
</SidebarDocumentLink>;
|
|
}
|
|
if (issueRef) {
|
|
return (
|
|
<MarkdownIssueLink issuePathId={issueRef.issuePathId} href={issueRef.href} documentLink={documentLink}>
|
|
{linkChildren}
|
|
</MarkdownIssueLink>
|
|
);
|
|
}
|
|
|
|
const caseIdentifier = linkCaseReferences ? caseIdentifierFromHref(href) : null;
|
|
if (caseIdentifier) {
|
|
return <MarkdownCaseLink identifier={caseIdentifier}>{linkChildren}</MarkdownCaseLink>;
|
|
}
|
|
|
|
const parsed = href ? parseMentionChipHref(href) : null;
|
|
if (parsed) {
|
|
if (parsed.kind === "agent") {
|
|
return (
|
|
<MarkdownAgentMention agentId={parsed.agentId} style={linkStyle as React.CSSProperties | undefined}>
|
|
{linkChildren}
|
|
</MarkdownAgentMention>
|
|
);
|
|
}
|
|
const targetHref = parsed.kind === "project"
|
|
? `/projects/${parsed.projectId}`
|
|
: parsed.kind === "issue"
|
|
? `/issues/${parsed.identifier}`
|
|
: parsed.kind === "skill"
|
|
? `/skills/${parsed.skillId}`
|
|
: parsed.kind === "routine"
|
|
? `/routines/${parsed.routineId}`
|
|
: "/company/settings/access";
|
|
return (
|
|
<a
|
|
href={targetHref}
|
|
className={cn(
|
|
"paperclip-mention-chip",
|
|
`paperclip-mention-chip--${parsed.kind}`,
|
|
parsed.kind === "project" && "paperclip-project-mention-chip",
|
|
)}
|
|
data-mention-kind={parsed.kind}
|
|
style={{ ...mergeWrapStyle(linkStyle as React.CSSProperties | undefined), ...mentionChipInlineStyle(parsed) }}
|
|
>
|
|
{linkChildren}
|
|
</a>
|
|
);
|
|
}
|
|
const externalReference = href && externalReferenceLookup
|
|
? externalReferenceLookup[normalizeExternalObjectHref(href) ?? ""] ?? null
|
|
: null;
|
|
if (externalReference && href) {
|
|
return (
|
|
<MarkdownExternalLink href={href} reference={externalReference}>
|
|
{linkChildren}
|
|
</MarkdownExternalLink>
|
|
);
|
|
}
|
|
|
|
const resolvedHref = href && resolveLinkHref ? resolveLinkHref(href) : href;
|
|
if (resolveLinkHref && resolvedHref !== href) {
|
|
return resolvedHref ? (
|
|
<Link to={resolvedHref} style={mergeWrapStyle(linkStyle as React.CSSProperties | undefined)}>
|
|
{linkChildren}
|
|
</Link>
|
|
) : <>{linkChildren}</>;
|
|
}
|
|
return (
|
|
<MarkdownUrlLink href={href} title={anchorProps.title} style={mergeWrapStyle(linkStyle as React.CSSProperties | undefined)}>
|
|
{linkChildren}
|
|
</MarkdownUrlLink>
|
|
);
|
|
},
|
|
};
|
|
if (mediaMode === "omit") {
|
|
map.img = () => null;
|
|
} else if (mediaMode === "reference") {
|
|
map.img = ({ src, alt, title }) => (
|
|
<span data-markdown-image-reference title={title}>
|
|
Image: {alt || "Untitled image"}{src ? ` (${src})` : ""}
|
|
</span>
|
|
);
|
|
} else if (resolveImageSrc || onImageClick) {
|
|
map.img = ({ node: _node, src, alt, ...imgProps }) => {
|
|
const resolved = resolveImageSrc && src ? resolveImageSrc(src) : null;
|
|
const finalSrc = resolved ?? src;
|
|
const clickSrc = onImageClick ? safeNavigableUrl(finalSrc) : null;
|
|
return (
|
|
<img
|
|
{...imgProps}
|
|
src={finalSrc}
|
|
alt={alt ?? ""}
|
|
role={clickSrc ? "button" : undefined}
|
|
tabIndex={clickSrc ? 0 : undefined}
|
|
aria-label={clickSrc ? `Open image: ${alt || "Untitled image"}` : undefined}
|
|
onClick={onImageClick && clickSrc ? (e) => {
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
onImageClick(clickSrc, e.currentTarget);
|
|
} : undefined}
|
|
onKeyDown={onImageClick && clickSrc ? (e) => {
|
|
if (e.key !== "Enter" && e.key !== " ") return;
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
onImageClick(clickSrc, e.currentTarget);
|
|
} : undefined}
|
|
className={cn(imgProps.className, clickSrc && "cursor-pointer")}
|
|
/>
|
|
);
|
|
};
|
|
}
|
|
return map;
|
|
}, [theme, coordinator, linkIssueReferences, linkCaseReferences, externalReferenceLookup, resolveImageSrc, resolveLinkHref, onImageClick, mediaMode, knownPrefixes, knownPrefixSet]);
|
|
|
|
return (
|
|
<div
|
|
className={cn(
|
|
"paperclip-markdown prose prose-sm min-w-0 max-w-full break-words overflow-hidden",
|
|
theme === "dark" && "prose-invert",
|
|
// Customer content always masks in session replay; work content masks
|
|
// unless the company holds no Google or Slack data. Autocapture skips both.
|
|
replayContent === "work" ? ANALYTICS_WORK_CONTENT_CLASS : ANALYTICS_MASK_CLASS,
|
|
className,
|
|
)}
|
|
style={mergeWrapStyle(style)}
|
|
>
|
|
<Markdown
|
|
remarkPlugins={remarkPlugins}
|
|
rehypePlugins={streamWords ? [rehypeStreamingWords] : undefined}
|
|
components={components}
|
|
urlTransform={documentIssueId ? scopedUrlTransform : safeMarkdownUrlTransform}
|
|
>
|
|
{children}
|
|
</Markdown>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export const MarkdownBody = memo(MarkdownBodyImpl);
|