TypeScript
feat(pull-requests): link GitHub references in markdown (#8812)
maria42a8fd5103b4
diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsxindex 7773338a745..d23d6bef486 100644--- a/apps/web/src/components/ChatMarkdown.tsx+++ b/apps/web/src/components/ChatMarkdown.tsx@@ -179,6 +179,7 @@ interface ChatMarkdownProps {onUseArtifactTemplate?: ((template: CodexArtifactTemplate) => void) | undefined;imageBaseDir?: string | undefined;onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;+ extraRemarkPlugins?: NonNullable<ReactMarkdownOptions["remarkPlugins"]>;}export function canUseMarkdownFileShellActions(@@ -211,6 +212,7 @@ export function shouldUseMarkdownFileBrowserPrimaryAction(input: {}const EMPTY_MARKDOWN_SKILLS: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">> = [];+const EMPTY_REMARK_PLUGINS: NonNullable<ReactMarkdownOptions["remarkPlugins"]> = [];const ARTIFACT_TEMPLATE_ICON_BY_KIND = {document: FileTextIcon,@@ -360,6 +362,7 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = {code: [...(defaultSchema.attributes?.code ?? []), "dataCodeMeta", "dataInlineCode"],blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"],div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES],+ a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"],img: [...(defaultSchema.attributes?.img ?? []), "dataLocalSrc", "dataMarkdownTitle"],},protocols: {@@ -1807,6 +1810,7 @@ function ChatMarkdown({onUseArtifactTemplate,imageBaseDir,onImageExpand,+ extraRemarkPlugins = EMPTY_REMARK_PLUGINS,}: ChatMarkdownProps) {const { resolvedTheme } = useTheme();const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {@@ -2203,6 +2207,16 @@ function ChatMarkdown({: null;if (!fileLinkMeta) {const faviconHost = resolveExternalWebLinkHost(href);+ const pullRequestAutolink = String(+ (props as Record<string, unknown>)["data-pull-request-autolink"] ?? "",+ );+ const pullRequestCopy =+ pullRequestAutolink === "commit"+ ? /\/commit\/([0-9a-f]{40})$/iu.exec(href ?? "")?.[1]+ : pullRequestAutolink === "reference"+ ? plainHastText(node)+ : undefined;+ const isPullRequestAutolink = pullRequestCopy !== undefined;const isSameDocumentLink = href?.startsWith("#") ?? false;const onClick = props.onClick;const canOpenInPreview = Boolean(threadRef) && isPreviewSupportedInRuntime();@@ -2210,6 +2224,8 @@ function ChatMarkdown({const link = (<a{...props}+ className={cn(props.className, pullRequestAutolink === "commit" && "font-mono")}+ data-markdown-copy={pullRequestCopy}href={href}target={isSameDocumentLink ? undefined : "_blank"}rel={isSameDocumentLink ? undefined : "noopener noreferrer"}@@ -2281,7 +2297,7 @@ function ChatMarkdown({});}}>- {faviconHost && hastHasText(node) ? (+ {faviconHost && hastHasText(node) && !isPullRequestAutolink ? (<MarkdownExternalLinkContent host={faviconHost} plainText={plainHastText(node)}>{linkChildren}</MarkdownExternalLinkContent>@@ -2438,6 +2454,14 @@ function ChatMarkdown({]);/* eslint-enable react/no-unstable-nested-components */+ const remarkPlugins = useMemo(+ () => [+ ...(lineBreaks ? CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS : CHAT_MARKDOWN_REMARK_PLUGINS),+ ...extraRemarkPlugins,+ ],+ [extraRemarkPlugins, lineBreaks],+ );+// react-markdown converts unparsed HTML nodes to text when skipHtml is false.// Keep that behavior explicit because literal mode depends on escaping the// complete source token instead of dropping it from the rendered message.@@ -2450,9 +2474,7 @@ function ChatMarkdown({onCopy={handleCopy}><ReactMarkdown- remarkPlugins={- lineBreaks ? CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS : CHAT_MARKDOWN_REMARK_PLUGINS- }+ remarkPlugins={remarkPlugins}rehypePlugins={parseRawHtml ? CHAT_MARKDOWN_REHYPE_PLUGINS : undefined}skipHtml={false}components={markdownComponents}diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsxindex 5666ddd26e5..0f3a864f8c1 100644--- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx+++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx@@ -97,6 +97,7 @@ import { DiffPanelLoadingState } from "../DiffPanelShell";import { PullRequestsUnavailableState } from "./PullRequestsUnavailableState";import type { PullRequestAgentSelectionInput } from "./PullRequestCodeTab";import { openOnHostLabel, showPullRequestLinkContextMenu } from "./pullRequestLinkContextMenu";+import { PullRequestMarkdownContext } from "./PullRequestMarkdown";import { PullRequestSummaryTab } from "./PullRequestSummaryTab";import { PullRequestTimelineTab } from "./PullRequestTimelineTab";import {@@ -1921,7 +1922,7 @@ export function PullRequestDetailPanel({{...(unavailableGitHubUrl ? { gitHubUrl: unavailableGitHubUrl } : {})}/>) : detail ? (- <>+ <PullRequestMarkdownContext value={detail.provider === "github" ? repositoryUrl : null}>{mountedTabs.has("summary") ? (<div className={cn("absolute inset-0", tab !== "summary" && "invisible")}><PullRequestSummaryTab@@ -1978,7 +1979,7 @@ export function PullRequestDetailPanel({</Suspense></div>) : null}- </>+ </PullRequestMarkdownContext>) : null}</div>diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdown.tsxindex f782e5be113..ad06eb21e2a 100644--- a/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx+++ b/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx@@ -1,10 +1,14 @@import { ExternalLinkIcon, PaperclipIcon, PlayIcon } from "lucide-react";import type { EnvironmentId } from "@t3tools/contracts";+import { createContext, useContext, useMemo } from "react";+import type { Options as ReactMarkdownOptions } from "react-markdown";import { cn } from "~/lib/utils";import ChatMarkdown from "../ChatMarkdown";-import { splitPullRequestBody } from "./pullRequestMarkdown.logic";+import { remarkPullRequestAutolinks, splitPullRequestBody } from "./pullRequestMarkdown.logic";++export const PullRequestMarkdownContext = createContext<string | null>(null);/*** A pull request body, rendered with the app's markdown renderer plus a card for each upload@@ -27,6 +31,11 @@ export function PullRequestMarkdown({className?: string;}) {const segments = splitPullRequestBody(text);+ const repositoryUrl = useContext(PullRequestMarkdownContext);+ const extraRemarkPlugins = useMemo<NonNullable<ReactMarkdownOptions["remarkPlugins"]>>(+ () => (repositoryUrl ? [[remarkPullRequestAutolinks, { repositoryUrl }]] : []),+ [repositoryUrl],+ );return (<div className={cn("space-y-3", className)}>{segments.map((segment) => {@@ -37,6 +46,7 @@ export function PullRequestMarkdown({text={segment.text}cwd={cwd}environmentId={environmentId}+ extraRemarkPlugins={extraRemarkPlugins}/>);}diff --git a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.tsindex e322b595a18..79ae60e928c 100644--- a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts+++ b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts@@ -1,3 +1,9 @@+import {+ findAndReplaceText,+ type MarkdownNode,+ type TextMatch,+} from "~/vendor/mdast-find-and-replace";+/** `id` is positional on purpose: the same attachment can be embedded twice in one body. */export type PullRequestBodySegment =| { readonly id: string; readonly kind: "markdown"; readonly text: string }@@ -141,3 +147,46 @@ export function splitPullRequestBody(body: string): ReadonlyArray<PullRequestBodflushMarkdown();return segments;}++const AUTOLINK_CANDIDATE_PATTERN = /#[1-9]\d*|[0-9a-f]{40}/giu;+const AUTOLINK_WORD_CHARACTER_PATTERN = /[A-Za-z0-9_]/u;+const AUTOLINK_COMMIT_PREFIX_PATTERN = /[\s([{]/u;+const AUTOLINK_IGNORED_TYPES = new Set(["link", "linkReference"]);++/** GitHub-style same-repository references for pull request prose, never code or authored links. */+export function remarkPullRequestAutolinks(options: { readonly repositoryUrl: string }) {+ const repositoryUrl = options.repositoryUrl.replace(/\/+$/u, "");+ return (tree: MarkdownNode) => {+ findAndReplaceText(+ tree,+ AUTOLINK_CANDIDATE_PATTERN,+ (matched: string, match: TextMatch) => {+ const reference = matched.startsWith("#");+ const before = match.input[match.index - 1];+ const after = match.input[match.index + matched.length];+ if (+ (before !== undefined &&+ (reference+ ? AUTOLINK_WORD_CHARACTER_PATTERN.test(before)+ : !AUTOLINK_COMMIT_PREFIX_PATTERN.test(before))) ||+ (after !== undefined && AUTOLINK_WORD_CHARACTER_PATTERN.test(after))+ ) {+ return false;+ }+ return {+ type: "link",+ url: reference+ ? `${repositoryUrl}/issues/${matched.slice(1)}`+ : `${repositoryUrl}/commit/${matched}`,+ data: {+ hProperties: {+ dataPullRequestAutolink: reference ? "reference" : "commit",+ },+ },+ children: [{ type: "text", value: reference ? matched : matched.slice(0, 7) }],+ };+ },+ AUTOLINK_IGNORED_TYPES,+ );+ };+}diff --git a/apps/web/src/vendor/mdast-find-and-replace.ts b/apps/web/src/vendor/mdast-find-and-replace.tsnew file mode 100644index 00000000000..2f16ab202ba--- /dev/null+++ b/apps/web/src/vendor/mdast-find-and-replace.ts@@ -0,0 +1,90 @@+/*+ * Adapted from mdast-util-find-and-replace:+ * https://github.com/syntax-tree/mdast-util-find-and-replace/blob/main/lib/index.js+ *+ * The MIT License+ *+ * Copyright (c) Titus Wormer <[email protected]>+ *+ * Permission is hereby granted, free of charge, to any person obtaining a copy+ * of this software and associated documentation files (the "Software"), to deal+ * in the Software without restriction, including without limitation the rights+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+ * copies of the Software, and to permit persons to whom the Software is+ * furnished to do so, subject to the following conditions:+ *+ * The above copyright notice and this permission notice shall be included in+ * all copies or substantial portions of the Software.+ *+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+ * SOFTWARE.+ */++export type MarkdownNode = {+ type: string;+ value?: string;+ children?: MarkdownNode[];+ url?: string;+ data?: unknown;+};++export type TextMatch = {+ index: number;+ input: string;+};++/** The dependency-free subset of mdast-util-find-and-replace used by PR autolinks. */+export function findAndReplaceText(+ tree: MarkdownNode,+ find: RegExp,+ replace: (matched: string, match: TextMatch) => MarkdownNode | false,+ ignoredTypes: ReadonlySet<string>,+): void {+ visit(tree);++ function visit(node: MarkdownNode): void {+ if (node.children === undefined) return;+ for (let childIndex = 0; childIndex < node.children.length; childIndex += 1) {+ const child = node.children[childIndex]!;+ if (ignoredTypes.has(child.type)) continue;+ if (child.type !== "text" || child.value === undefined) {+ visit(child);+ continue;+ }++ const replacements: MarkdownNode[] = [];+ let start = 0;+ let changed = false;+ find.lastIndex = 0;+ let match = find.exec(child.value);+ while (match !== null) {+ const position = match.index;+ const replacement = replace(match[0], { index: position, input: match.input });+ if (replacement === false) {+ find.lastIndex = position + 1;+ } else {+ if (start < position) {+ replacements.push({ type: "text", value: child.value.slice(start, position) });+ }+ replacements.push(replacement);+ start = position + match[0].length;+ changed = true;+ }+ if (!find.global) break;+ match = find.exec(child.value);+ }++ if (!changed) continue;+ if (start < child.value.length) {+ replacements.push({ type: "text", value: child.value.slice(start) });+ }+ node.children.splice(childIndex, 1, ...replacements);+ childIndex += replacements.length - 1;+ }+ }+}