mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-19 16:29:42 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Paperclip Cloud runs the same app for hosted customers, and the same UI ships in the npm package. > - The PostHog project for Cloud gets only server events today. It has no page views, sessions, replays or people. > - So the Product and Web analytics pages are empty, and we cannot see how Cloud users move through the board. > - This pull request adds browser analytics for Cloud only. It is off until an operator sets two switches on a Cloud stack. > - Self-hosted installs do not change: they never download posthog-js and never serve the PostHog proxy. > - The benefit is real page views, sessions, heatmaps, Web Vitals and masked session replays for Cloud, linked to the user and the workspace. ## Linked Issues or Issue Description **Subsystem affected** Board UI (analytics bootstrap and privacy markers), server session payload and a new same-origin proxy route, shared validators. **Problem or motivation** Cloud sends only server events to PostHog. There is no browser SDK, so PostHog has no page views, sessions, replays or identified people for Cloud. We cannot see where Cloud users get stuck. **Proposed solution** The signed-in session gives the UI a PostHog config only on a Cloud-managed stack with `PAPERCLIP_POSTHOG_PROJECT_TOKEN` and `PAPERCLIP_POSTHOG_BROWSER_ENABLED=1`. The UI loads posthog-js after the page settles. Events go through a strict same-origin proxy at `/_ph`, so ad blockers do not drop them. Replay masks all text and all inputs by default. **Alternatives considered** Bake a key into the UI build: refused, because the same build ships to self-hosted users. A generic reverse proxy: refused, because it would forward any path. Mask only content areas: refused, because a missed surface would leak; masking is deny by default. **Additional context** This is the browser part of the Cloud direct PostHog plan. The server direct sender is already on master (#22006). Fleet configuration is a separate change. PostHog person deletion on account deletion is a follow-up. ## What Changed - Uses the shared Cloud PostHog config (`resolveCloudPostHogConfig` in `server/src/services/cloud-posthog-config.ts`, already on master from the server direct-sending change). This PR does not change it. - `server/src/services/cloud-posthog-browser.ts`: `resolveBrowserAnalyticsConfig` returns `{ token, apiHost: "/_ph", uiHost, environment, stackId, replayEnabled }` only when `PAPERCLIP_POSTHOG_BROWSER_ENABLED=1`. `environment` is always set: the explicit variable, else `staging` for a `*.staging.paperclip.app` host, else `production`. - `GET /api/auth/get-session` carries the new optional `browserAnalytics` field (the existing signed-in bootstrap request, so no new request on the cold path). `packages/shared` has `browserAnalyticsConfigSchema` and the session schema field. - `server/src/routes/posthog-proxy.ts`: a strict proxy, mounted before the body parsers and only when browser analytics is on. It forwards only these requests and answers 404 to all others without contacting PostHog: - `POST /e/`, `/i/v0/e/`, `/batch/`, `/s/`, `/flags/`, `/decide/` to the ingest host. - `GET /array/<token>/config(.js)` and `GET /static/[<version>/]<name>.js` to the assets host (derived from the ingest host). - `stream.pipeline` joins the streams, so an error on either side (PostHog closes the connection partway through a response, or the browser goes away) closes both and never goes unhandled. It builds a new header set from an allowlist plus `X-Forwarded-For`. It never forwards the inbound Host, Cookie or Authorization headers. It drops `Set-Cookie` from responses. Bodies stream; nothing is buffered. It refuses bodies over 64 MiB (413, also for chunked bodies that grow past the limit) and limits requests in flight to 16 per client address and 256 in total (429). - `ui/src/lib/analytics/product-analytics.ts` (the only module that talks to posthog-js) and `ui/src/components/ProductAnalyticsGate.tsx`: - posthog-js loads after the page settles (or at a 15 s deadline), only when the session has a config. It loads as PostHog's browser script `/_ph/static/array.js` through the proxy, the same way posthog-js itself loads its extensions (recorder, web vitals). It is not an npm dependency and is in no bundle chunk. - Init: page views on history change, page leave, autocapture, Web Vitals, heatmaps, `person_profiles: "identified_only"`, `tracing_headers` for our own host only, replay only when `replayEnabled`. Surveys, product tours, web experiments and conversations are off. - Super properties on every event: `deployment_source: "cloud"` and `environment`. - After sign-in: `identify(session.userId, { email, name })` (person properties only). `session.userId` is the authenticated actor's user id verbatim (for example `paperclip-id:...`): `GET /api/auth/get-session` copies `req.actor.userId` into it, and server events use that same actor id as `distinct_id`, so browser and server events land on one person. Tests: `auth-routes.test.ts` (the session returns the actor id verbatim) and `ProductAnalyticsGate.test.tsx` (identify uses it) and `group("workspace", stackId)`. On sign-out: `reset()`, then the super properties again. `useSignOut` calls it before it leaves the page, because Cloud sign-out navigates away while the session query is still populated. - Privacy (`ui/src/lib/analytics/privacy.ts`), deny by default: - Replay masks every text node (`maskTextSelector: "*"` with `maskTextFn`) and every input value (`maskAllInputs`). - Only elements with `ANALYTICS_UNMASK_PROPS` show their text: sidebar items whose label is a fixed string (`analyticsChrome`, added at the 99 call sites with literal labels), and a shared `Button`, `Label`, `TabsTrigger` or `EmptyState` only when its caller passes `analyticsChrome`. None of them opts in by default, because they also render customer text (agent names, document titles). Sidebar items with dynamic labels (recent tasks, agents, projects) stay masked. - Replay masks attribute values too (`maskAttributeFn`, deny by default). Only layout attributes (`class`, `style`, `role`, `data-state`, SVG geometry), rrweb metadata and stylesheet links keep their values. `title`, `aria-label`, `alt`, `placeholder`, `src`, `href`, `data-*` and element references (`id`, `for`, `aria-labelledby`, `aria-describedby`, `aria-controls`, which often embed names or slugs) are always masked, even on unmasked chrome. So the organization switcher's `aria-label`, task titles in `title` attributes, image sources and download links with file paths never reach a replay. - `before_send` (`scrubCapturedEvent`) drops the `title` property from every event, because posthog-js copies `document.title` (task and organization names) into page views. Every URL string in every event, including replay meta events, keeps only its origin and path: query and hash values never leave (they can hold tokens, `code`/`state`, file paths or search text), and the token segment of `/board-claim/<token>` and `/invite/<token>` is redacted. It recurses only into plain objects and arrays, so the `Date` timestamp stays intact. - `ANALYTICS_MASK_CLASS` keeps customer content masked even inside unmasked chrome: `MarkdownBody` (task and issue bodies, comments, chat messages, documents and artifact markdown), `MarkdownEditor`, the task chat thread, the issue chat thread, the comment timeline, the file viewer (source, markdown and CSV views) and the organization name in the organization switcher. Text in any `contenteditable` editor is always masked. - `ANALYTICS_NO_CAPTURE_CLASS` (`ph-no-capture`, a blank box in replay) on every password-type `Input` (about 40 secret, token and API key fields), environment variable values and new secret values. - Autocapture never records element text or attribute values (`mask_all_text`, `mask_all_element_attributes`). - Connected-account content (Google user data and Slack data: email bodies, calendar events, Slack messages in tasks, chat, tool results, previews) never appears unmasked in a replay. Replay masks all text by default; nothing that renders connected-account content is in the unmask allowlist; autocapture records no element text anywhere (`mask_all_text`). `ui/src/lib/analytics/unmask-allowlist.test.ts` pins the allowlist: only 7 files may spread the unmask attribute, sidebar opt-ins need a literal label, and any `analyticsChrome` opt-in on `Button`/`Label`/`TabsTrigger`/`EmptyState` fails until it is added to a reviewed list (empty today). The same test renders Gmail, Calendar and Slack-style tool results next to unmasked navigation and checks they are masked. - Guard test: UI code must never call `capture()` with a `PAPERCLIP_EVENTS` name, so each event has one sender. - Docs: `doc/cloud-browser-analytics.md` (switches, per-stack opt-out, proxy allowlist, identity, privacy) and a link from `doc/observability.md`. - No new npm dependency and no lockfile change: posthog-js comes from PostHog through the proxy at run time. (An earlier revision added `posthog-js` to `ui/package.json`; the Runner support suite requires every `ui` dependency in the reviewed lockfile, which a pull request cannot update, so the script approach replaced it.) ## Verification - `pnpm verify`: see the result below. - Focused tests: - `server/src/__tests__/cloud-posthog-browser.test.ts`: exposure matrix (self-hosted with every switch set, Cloud without token, without stack ID, without the browser switch, switch not `1`, enabled, replay off), environment fallback, proxy mount only when enabled, allowed routes, 404 for disallowed methods and paths (including `//host` and `..` paths) with no upstream contact, Host/Cookie/Authorization stripped, `Set-Cookie` dropped, 502 when PostHog is down, and no unhandled error when PostHog closes a response partway (red on the old `pipe()` code, green now). - `server/src/__tests__/auth-routes.test.ts`: the session carries `browserAnalytics` only on Cloud with the token and the switch. - `ui/src/lib/analytics/*.test.ts`, `ui/src/components/ProductAnalyticsGate.test.tsx`: no import of posthog-js without a config or when signed out; load after the page settles, once; identify, group, reset with a mocked posthog; email and name never become event properties; deny-by-default replay masking; guard test. - Real run (local, headless Chromium, production UI build, never the real PostHog project): - Self-hosted server, no env: 0 requests for PostHog's script and 0 requests to `/_ph` in 9 cold loads and in a 40 s session with navigation. `browserAnalytics` is `null`. `/_ph/e/` falls through to the UI. - Cloud config: a full Cloud boot needs S3, a managed database and the control plane. So a small local stand-in served the same production UI build, mounted the real proxy from `server/src/routes/posthog-proxy.ts`, added the real `resolveBrowserAnalyticsConfig()` output to the session, and forwarded other API calls to the local server. `PAPERCLIP_POSTHOG_HOST` pointed at a local capture server. - Captured through `/_ph` only (0 requests to any posthog.com host): `$pageview` on each client navigation (5), `$identify` with `$set: { email, name }`, `$groupidentify`, `$groups: { workspace: <stack id> }` on events, `environment` and `deployment_source` on every event, `$web_vitals`, `$autocapture` with no `$el_text`, `$$heatmap`, and 10 `$snapshot` replay events. A search of every decoded `/e/` and `/s/` payload (events, replay text and replay attributes) found the email only in `$identify`'s `$set`, and found none of: the task body, the typed comment, the task title, the organization name. No Cookie header reached the capture server. 96 of 113 API requests carried `X-POSTHOG-SESSION-ID` (the others ran before posthog-js loaded). - Client-side visits to `/invite/INVITESECRET123` and `/cli-auth/abc?token=CLISECRET456` reached PostHog as `/invite/REDACTED` and `/cli-auth/abc` (no query); neither secret was in any payload. - Disallowed proxy requests (`PUT /_ph/e/`, `GET /_ph/api/projects/`, `POST /_ph/static/x.js`) answered 404. - Sample replay payload (decoded rrweb text nodes from a captured `/s/` request). The task body, the typed comment, the task title, the organization name and the email were not in any replay payload: ```json {"text_nodes": [ {"parentTag": "title", "textContent": "****** ** * *********"}, {"parentTag": "a", "textContent": "**** ** **** *******"}, {"parentTag": "span", "textContent": "****** **"}, {"parentTag": "span", "textContent": "*** ****"}, {"parentTag": "span", "textContent": "Tasks"}, {"parentTag": "span", "textContent": "Inbox"}, {"parentTag": "h2", "textContent": "******* *******"}, {"parentTag": "p", "textContent": "****** *** * ******* ** ******"} ]} ``` - Cold load, 9 fresh-profile loads each, median, same stand-in with analytics off and on: | | DOMContentLoaded | Board content visible | | --- | --- | --- | | Analytics off | 128 ms | 336 ms | | Analytics on | 126 ms | 334 ms | Final head. The difference is inside run-to-run noise (earlier pairs: 332/335 ms and 335/348 ms). PostHog's script loads only after the content is visible. ## Risks - Inert by default. Without a Cloud-managed stack, a project token, a stack ID and `PAPERCLIP_POSTHOG_BROWSER_ENABLED=1`, the session field is `null`, the proxy is not mounted and no analytics code runs. The OSS package does not change behavior. - Per-stack opt-out: `PAPERCLIP_POSTHOG_REPLAY_ENABLED=0` turns replay off; unsetting `PAPERCLIP_POSTHOG_BROWSER_ENABLED` turns all browser analytics off. Both apply on the next restart. - Replay text shown in the clear comes only from fixed sidebar labels and from shared components whose caller opts in. Today no `Button`, `Label`, `TabsTrigger` or `EmptyState` call site opts in, so replays show layout, clicks and navigation with most copy masked. Opting in fixed-label call sites is a follow-up. Review sample replays on staging before production. - Image `src` values are masked, so images record as empty boxes. Sandboxed iframes (HTML artifacts, MCP apps) also record as empty boxes. Replays therefore show layout and product copy, not customer media. - PostHog's script is not version-pinned: the assets host serves its current browser build, as for any PostHog snippet install, and posthog-js already loads its extensions from that host at run time. It runs only on Cloud stacks with the browser switch on. - The proxy needs no sign-in, like PostHog's documented proxies: posthog-js sends some events while a page unloads, and the proxy can only reach the two PostHog hosts, on the listed paths, with the public project token. Body size and in-flight limits bound the load one client can add. - posthog-js rejects bots (including headless browsers) on its own, which is the wanted production behavior. - `SidebarNavItem.production.tsx`, `Sidebar*.tsx` and the shared `ui/*` components changed by one attribute each; no visual change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edits, headless browser runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1051 lines
38 KiB
TypeScript
1051 lines
38 KiB
TypeScript
import { PatchLines } from "./PatchLines";
|
|
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 { 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 } 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 { 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;
|
|
/** 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;
|
|
}
|
|
|
|
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("");
|
|
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 safeMarkdownUrlTransform(url: string): string {
|
|
if (url.startsWith(WORKSPACE_FILE_HREF_PREFIX)) return url;
|
|
return parseMentionChipHref(url) ? url : defaultUrlTransform(url);
|
|
}
|
|
|
|
type MarkdownAstNode = {
|
|
type?: string;
|
|
value?: string;
|
|
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,
|
|
onImageClick,
|
|
mediaMode = "render",
|
|
resolveWorkspaceFileRef,
|
|
}: MarkdownBodyProps) {
|
|
const { theme } = useTheme();
|
|
const coordinator = useCoordinatorPresentation();
|
|
const streamWords = useContext(MarkdownWordStreaming);
|
|
// 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];
|
|
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" 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"} />;
|
|
}
|
|
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;
|
|
return (
|
|
<img
|
|
{...imgProps}
|
|
src={finalSrc}
|
|
alt={alt ?? ""}
|
|
role={onImageClick && finalSrc ? "button" : undefined}
|
|
tabIndex={onImageClick && finalSrc ? 0 : undefined}
|
|
aria-label={onImageClick && finalSrc ? `Open image: ${alt || "Untitled image"}` : undefined}
|
|
onClick={onImageClick && finalSrc ? (e) => {
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
onImageClick(finalSrc, e.currentTarget);
|
|
} : undefined}
|
|
onKeyDown={onImageClick && finalSrc ? (e) => {
|
|
if (e.key !== "Enter" && e.key !== " ") return;
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
onImageClick(finalSrc, e.currentTarget);
|
|
} : undefined}
|
|
className={cn(imgProps.className, onImageClick && "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: masked in session replay, skipped by autocapture.
|
|
ANALYTICS_MASK_CLASS,
|
|
className,
|
|
)}
|
|
style={mergeWrapStyle(style)}
|
|
>
|
|
<Markdown
|
|
remarkPlugins={remarkPlugins}
|
|
rehypePlugins={streamWords ? [rehypeStreamingWords] : undefined}
|
|
components={components}
|
|
urlTransform={safeMarkdownUrlTransform}
|
|
>
|
|
{children}
|
|
</Markdown>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export const MarkdownBody = memo(MarkdownBodyImpl);
|