Files
paperclip/ui/src/components/MarkdownBody.tsx
T
Dotta 468edd8b22 Add workspace file viewer and artifact links (#7681)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Agent work is issue-centered, and reviewers often need to inspect
files, artifacts, and path references produced during that work.
> - Before this branch, workspace-relative paths and artifact file
references were not first-class inspectable objects in the board UI.
> - Safe file viewing needs shared resource contracts, server-side
workspace boundary checks, and UI that opens files without exposing
arbitrary host paths.
> - The workspace file viewer branch needed to stay as one active PR and
be rebased onto current `paperclipai/paperclip:master` for review.
> - This pull request adds the workspace file resource API, issue-page
file viewer and browser, markdown file-reference links, and artifact
file chips.
> - The benefit is that board users can inspect relevant files from
issue context while preserving workspace boundaries and auditability.

## Linked Issues or Issue Description

No public GitHub issue exists for this branch. Internal Paperclip
issues: `PAP-1953`, `PAP-10539`, `PAP-10733`.

Problem / motivation:
- Board users need to open workspace-relative files mentioned by agents
or attached as work-product metadata without switching to a terminal.
- The UI needs to support both direct file-path opening and workspace
browsing/searching from an issue page.
- The server must enforce company access, workspace boundaries, size
limits, rate limits, and safe audit logging.

Related PR:
- Prior closed attempt: #4442
- Single active PR for this branch: #7681

## What Changed

- Added shared workspace file resource types, validators, and
workspace-file `resourceRef` metadata validation for work products.
- Added server routes/services for resolving, listing, and previewing
workspace-relative files with access checks, scan caps, list-specific
limits, and audit logging.
- Added the issue file viewer provider, sheet, workspace browser,
command-palette action, markdown workspace-file autolinks, and artifact
file chips.
- Updated issue workspace UI and stories/tests for file browsing and
workspace file opening.
- Rebased the branch onto current `paperclipai/paperclip:master` and
updated the existing single PR branch.
- Addressed current-head Greptile follow-ups by applying `offset`
consistently across search/recent/changed file listings, restoring
stopped-service port ownership checks before auto-port reuse, and
stabilizing the workspace browser pagination test.

## Verification

Current local verification after rebase to `public/master`:
- `pnpm exec vitest run packages/shared/src/work-product.test.ts
server/src/__tests__/file-resources.test.ts
server/src/__tests__/instance-settings-routes.test.ts
server/src/__tests__/instance-settings-service.test.ts
server/src/__tests__/workspace-runtime.test.ts
ui/src/components/FileViewerSheet.test.tsx
ui/src/components/FileViewerSheet.copy.test.tsx
ui/src/components/WorkspaceFileBrowser.test.tsx
ui/src/components/WorkspaceFileMarkdownBody.test.tsx
ui/src/context/FileViewerContext.test.ts
ui/src/lib/remark-workspace-file-refs.test.ts
ui/src/lib/workspace-file-parser.test.ts
ui/src/components/IssueWorkspaceCard.test.tsx` - 13 files passed, 197
tests passed.
- `pnpm -r --filter @paperclipai/shared --filter @paperclipai/server
--filter @paperclipai/ui typecheck` - passed.
- `pnpm exec vitest run ui/src/components/WorkspaceFileBrowser.test.tsx`
- 1 file passed, 25 tests passed.
- `pnpm exec vitest run server/src/__tests__/file-resources.test.ts
server/src/__tests__/workspace-runtime.test.ts` - 2 files passed, 90
tests passed.
- `pnpm -r --filter @paperclipai/server typecheck` - passed.
- Confirmed branch is `0` behind and `46` ahead of current
`public/master` after rebase and follow-up commits.
- Confirmed the PR diff does not include `pnpm-lock.yaml`.
- Confirmed the PR diff does not include `.github/workflows` changes.
- Searched GitHub for duplicate or related workspace file viewer
PRs/issues; #4442 is the prior closed attempt and this PR is the single
active PR for the branch.
- No screenshots were committed; the task explicitly asked not to add
design screenshots or images unless they were part of the work.

Current remote verification on head
`a698a7bc10137baf7d25bd5722e1d6e0343387c1`:
- Greptile Review - success, 64 files reviewed, 0 comments added, no
unresolved Greptile review threads.
- PR workflow `verify` - success.
- Typecheck + Release Registry, General tests, workspace test shards,
serialized server suites, Build, Canary Dry Run, e2e, Socket, and Snyk -
success.
- `security-review` - neutral, with output saying a draft advisory was
filed for maintainer review and is not a merge block.
- `commitperclip PR Review / review` - cancelled after the security gate
detected flags and timed out while creating/reviewing the advisory. I
reran it once and it cancelled the same way; no actionable code/test
failure was exposed in the job logs.

## Risks

- This is a broad UI/server feature PR, so review needs to pay attention
to route authorization, workspace boundary handling, and markdown
autolink false positives.
- Workspace browsing intentionally caps list results and scan depth;
very large workspaces may require users to refine search terms.
- Remote workspace preview remains unavailable until remote file-access
support is implemented.
- The neutral commitperclip security-review advisory needs maintainer
review, but the check output says it is not a merge block.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected - check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- OpenAI Codex, GPT-5 coding agent in a Paperclip/Codex local tool-use
environment, medium reasoning, with shell/GitHub CLI tool use for branch
inspection, verification, rebase, PR update, Greptile review, and CI
inspection.

## 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 run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] If this change affects the UI, I have included before/after
screenshots
- [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
- [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: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-09 17:17:43 -05:00

765 lines
24 KiB
TypeScript

import { isValidElement, useCallback, useEffect, useId, useRef, useState, type ReactNode } from "react";
import { useQuery } from "@tanstack/react-query";
import { Check, Copy, ExternalLink, Github, WrapText } from "lucide-react";
import Markdown, { defaultUrlTransform, type Components, type Options } from "react-markdown";
import remarkGfm from "remark-gfm";
import { cn } from "../lib/utils";
import { Link } 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 { queryKeys } from "../lib/queryKeys";
import { parseIssueReferenceFromHref, remarkLinkIssueReferences } from "../lib/issue-reference";
import { parseWorkspaceFileHref, remarkWorkspaceFileRefs, WORKSPACE_FILE_HREF_PREFIX } from "../lib/remark-workspace-file-refs";
import { remarkSoftBreaks } from "../lib/remark-soft-breaks";
import { StatusIcon } from "./StatusIcon";
import { WorkspaceFileLink } from "./WorkspaceFileLink";
interface MarkdownBodyProps {
children: string;
className?: string;
style?: React.CSSProperties;
softBreaks?: boolean;
linkIssueReferences?: 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 resolver for relative image paths (e.g. within export packages) */
resolveImageSrc?: (src: string) => string | null;
/** Called when a user clicks an inline image */
onImageClick?: (src: string) => void;
/** Link inline-code workspace file paths to the issue file viewer. */
linkWorkspaceFileRefs?: boolean;
}
let mermaidLoaderPromise: Promise<typeof import("mermaid").default> | null = null;
function MarkdownIssueLink({
issuePathId,
children,
}: {
issuePathId: string;
children: ReactNode;
}) {
const { data } = useQuery({
queryKey: queryKeys.issues.detail(issuePathId),
queryFn: () => issuesApi.get(issuePathId),
staleTime: 60_000,
});
const identifier = data?.identifier ?? issuePathId;
const title = data?.title ?? identifier;
const status = data?.status;
const issueLabel = title !== identifier ? `Issue ${identifier}: ${title}` : `Issue ${identifier}`;
return (
<Link
to={`/issues/${identifier}`}
data-mention-kind="issue"
className="paperclip-markdown-issue-ref"
title={title}
aria-label={issueLabel}
>
{status ? (
<StatusIcon status={status} className="mr-1 h-3 w-3 align-[-0.125em]" />
) : null}
{children}
</Link>
);
}
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",
};
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: "color-mix(in oklab, var(--muted) 92%, var(--background) 8%)",
color: "var(--muted-foreground)",
fontSize: "0.7rem",
lineHeight: 1,
cursor: "pointer",
};
const codeBlockWrapActionStyle: React.CSSProperties = {
...codeBlockActionStyle,
width: "1.55rem",
paddingInline: 0,
};
const tableCellWrapStyle: React.CSSProperties = {
overflowWrap: "anywhere",
wordBreak: "normal",
};
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,
};
}
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 isGitHubUrl(href: string | null | undefined): boolean {
if (!href) return false;
try {
const url = new URL(href);
return url.protocol === "https:" && (url.hostname === "github.com" || url.hostname === "www.github.com");
} catch {
return false;
}
}
function isExternalHttpUrl(href: string | null | undefined): boolean {
if (!href) return false;
try {
const url = new URL(href);
if (url.protocol !== "http:" && url.protocol !== "https:") return false;
if (typeof window === "undefined") return true;
return url.origin !== window.location.origin;
} catch {
return false;
}
}
function renderLinkBody(
children: ReactNode,
leadingIcon: ReactNode,
trailingIcon: ReactNode,
): ReactNode {
if (!leadingIcon && !trailingIcon) return children;
// React-markdown can pass arrays/elements for styled link text; the nowrap
// splitting below is intentionally limited to plain text links.
if (typeof children === "string" && children.length > 0) {
if (children.length === 1) {
return (
<span style={{ whiteSpace: "nowrap" }}>
{leadingIcon}
{children}
{trailingIcon}
</span>
);
}
const first = children[0];
const last = children[children.length - 1];
const middle = children.slice(1, -1);
return (
<>
{leadingIcon ? (
<span style={{ whiteSpace: "nowrap" }}>
{leadingIcon}
{first}
</span>
) : first}
{middle}
{trailingIcon ? (
<span style={{ whiteSpace: "nowrap" }}>
{last}
{trailingIcon}
</span>
) : last}
</>
);
}
return (
<>
{leadingIcon}
{children}
{trailingIcon}
</>
);
}
function CodeBlock({
children,
preProps,
}: {
children: ReactNode;
preProps: React.HTMLAttributes<HTMLPreElement>;
}) {
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 = preRef.current?.innerText ?? flattenText(children);
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(text);
} else {
const textarea = document.createElement("textarea");
textarea.value = text;
textarea.style.position = "fixed";
textarea.style.left = "-9999px";
document.body.appendChild(textarea);
try {
textarea.select();
const success = document.execCommand("copy");
if (!success) throw new Error("execCommand copy failed");
} finally {
document.body.removeChild(textarea);
}
}
setFailed(false);
setCopied(true);
} catch {
setFailed(true);
setCopied(true);
}
clearTimeout(timerRef.current);
timerRef.current = setTimeout(() => {
setCopied(false);
setFailed(false);
}, 1500);
}, [children]);
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),
}}
>
{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>
);
}
export function MarkdownBody({
children,
className,
style,
softBreaks = true,
linkIssueReferences = true,
enableWikiLinks = false,
wikiLinkRoot,
resolveWikiLinkHref,
resolveImageSrc,
onImageClick,
linkWorkspaceFileRefs = false,
}: MarkdownBodyProps) {
const { theme } = useTheme();
// 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 knownPrefixes = company?.companies.length
? company.companies.map((c) => c.issuePrefix)
: undefined;
const remarkPlugins: NonNullable<Options["remarkPlugins"]> = [remarkGfm];
if (enableWikiLinks) {
remarkPlugins.push(createRemarkWikiLinks({ wikiLinkRoot, resolveWikiLinkHref }));
}
if (linkWorkspaceFileRefs) {
remarkPlugins.push(remarkWorkspaceFileRefs);
}
if (linkIssueReferences) {
remarkPlugins.push([remarkLinkIssueReferences, { knownPrefixes }]);
}
if (softBreaks) {
remarkPlugins.push(remarkSoftBreaks);
}
const components: 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) {
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, style: linkStyle, children: linkChildren, ...anchorProps }) => {
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) : null;
if (issueRef) {
return (
<MarkdownIssueLink issuePathId={issueRef.issuePathId}>
{linkChildren}
</MarkdownIssueLink>
);
}
const parsed = href ? parseMentionChipHref(href) : null;
if (parsed) {
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}`
: parsed.kind === "user"
? "/company/settings/access"
: `/agents/${parsed.agentId}`;
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 isGitHubLink = isGitHubUrl(href);
const isExternal = isExternalHttpUrl(href);
const leadingIcon = isGitHubLink ? (
<Github aria-hidden="true" className="mr-1 inline h-3.5 w-3.5 align-[-0.125em]" />
) : null;
const trailingIcon = isExternal && !isGitHubLink ? (
<ExternalLink aria-hidden="true" className="ml-1 inline h-3 w-3 align-[-0.125em]" />
) : null;
return (
<a
href={href}
{...(isExternal
? { target: "_blank", rel: "noopener noreferrer" }
: { rel: "noreferrer" })}
style={mergeWrapStyle(linkStyle as React.CSSProperties | undefined)}
>
{renderLinkBody(linkChildren, leadingIcon, trailingIcon)}
</a>
);
},
};
if (resolveImageSrc || onImageClick) {
components.img = ({ node: _node, src, alt, ...imgProps }) => {
const resolved = resolveImageSrc && src ? resolveImageSrc(src) : null;
const finalSrc = resolved ?? src;
return (
<img
{...imgProps}
src={finalSrc}
alt={alt ?? ""}
onClick={onImageClick && finalSrc ? (e) => { e.preventDefault(); onImageClick(finalSrc); } : undefined}
style={onImageClick ? { cursor: "pointer", ...(imgProps.style as React.CSSProperties | undefined) } : imgProps.style as React.CSSProperties | undefined}
/>
);
};
}
return (
<div
className={cn(
"paperclip-markdown prose prose-sm min-w-0 max-w-full break-words overflow-hidden",
theme === "dark" && "prose-invert",
className,
)}
style={mergeWrapStyle(style)}
>
<Markdown
remarkPlugins={remarkPlugins}
components={components}
urlTransform={safeMarkdownUrlTransform}
>
{children}
</Markdown>
</div>
);
}