Tsai Yuan 0530d0c7c6
fix(frontend): resolve relative message links to artifacts (#7356)
* fix(frontend): resolve relative links in messages to thread artifacts

An assistant message that links a file it wrote with a relative
destination, e.g. [Report](report.md), rendered a plain relative href.
The browser resolved it against the chat route to
/workspace/chats/report.md, so clicking it opened a "thread" whose id is
the file name and the Gateway rejected it (422). Only /mnt/ links were
rewritten, and the clarification and present_files message text did not
get the thread-aware link renderer at all.

- A relative link (no scheme, no leading /, no .. segment) that
  suffix-matches exactly one thread artifact now opens that artifact in
  a new tab, using the rule message images already use. When zero or
  several artifacts match it renders as text instead of a link to a
  broken chat URL. Links outside the message list are unchanged.
- The artifact list reaches the link renderer through a context:
  Streamdown memoizes its root without comparing `components`, so a
  renderer built before the list arrives would keep the stale list.
- /mnt/ artifact links get the normal link styling (they rendered as
  unstyled text before).
- A reopened thread rebuilds its values from the POST /history head,
  which carries messages but not `artifacts`. The message list and the
  artifact panel now add the /mnt/ paths from present_files calls in the
  messages, so links resolve and the panel lists the files after reload.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(frontend): address artifact link review

---------

Co-authored-by: huangzz <110116@nd.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-10-23 22:50:52 +08:00

223 lines
7.8 KiB
TypeScript

import {
type AnchorHTMLAttributes,
type ComponentProps,
createContext,
useContext,
} from "react";
import {
isPotentialRelativeArtifactReference,
resolveMarkdownArtifactURL,
resolveRelativeArtifactURL,
} from "@/core/artifacts/utils";
import {
retrievalSourceId,
type RetrievalSource,
} from "@/core/citations/sources";
import { knowledgeSourceId } from "@/core/knowledge/sources";
import { cn } from "@/lib/utils";
import { CitationLink, extractReactNodeText } from "../citations/citation-link";
import { KnowledgeCitation } from "../citations/knowledge-citation";
/**
* Schemes we are willing to render as a navigable ``<a href=...>``.
*
* Anything else (``javascript:``, ``data:text/html``, ``vbscript:``,
* ``file:``, …) is blocked because once it lands in a real anchor the
* browser happily executes the payload in the chat surface where
* sessionStorage / CSRF cookies are reachable. We accept ``http(s)``
* plus the non-executing ``mailto:`` / ``tel:`` schemes; same-origin
* absolute paths (``/…``), scheme-less relative references (``report.md``,
* ``./…``, ``../…``), and in-document anchors (``#…``) are also allowed
* — they all resolve under the current HTTP(S) origin.
*/
const SAFE_HREF_PROTOCOLS = ["http:", "https:", "mailto:", "tel:"] as const;
export function isSafeHref(href: string | undefined): boolean {
if (typeof href !== "string" || href.length === 0) {
return false;
}
// Same-document anchors (e.g. "#section").
if (href.startsWith("#")) {
return true;
}
// Protocol-relative URLs (//evil.com/path) would inherit the current
// page's scheme and navigate to an unknown host. Also reject
// backslash-normalised variants (\\evil.com → //evil.com) because
// browsers treat backslash as a path separator in URLs.
if (/^(\/\/|\\\\)/.test(href)) {
return false;
}
// Parse the href so we can inspect its scheme. Items without an explicit
// protocol (report.md, ./report.md, ../assets/chart.png, /workspace/foo)
// resolve relative to the dummy HTTPS base, producing an https: URL.
// Explicitly-schemed URLs (https://…, mailto:, javascript:, data:, …)
// keep their native scheme, which we then check against the allowlist.
try {
const parsed = new URL(href, "https://dummy.example/");
return (SAFE_HREF_PROTOCOLS as ReadonlyArray<string>).includes(
parsed.protocol,
);
} catch {
return false;
}
}
/**
* Inert stand-in for a link whose href failed `isSafeHref`. It keeps the
* visible label and marks the omission on hover and for assistive tech, so
* every surface that applies the allowlist degrades the same way. Extra props
* pass through for wrappers such as Radix `asChild` triggers.
*/
export function UnsafeLink({
href,
className,
...props
}: ComponentProps<"span"> & { href: string }) {
return (
<span
{...props}
className={cn(
"text-muted-foreground cursor-not-allowed underline decoration-dotted underline-offset-2",
className,
)}
aria-label="Unsafe link omitted"
title={`Unsafe link scheme in ${href}`}
/>
);
}
function isExternalUrl(href: string | undefined): boolean {
if (typeof href !== "string") {
return false;
}
return /^https?:\/\//.test(href);
}
/**
* The current thread's artifact paths, provided by the message list. Inside
* it, a link rendered with a `threadId` resolves relative destinations
* (`report.md`, `./out/a.md`) to the artifact they name.
*
* This is a context rather than a factory argument because Streamdown
* memoizes its root without comparing `components`: a link renderer created
* before the artifact list arrives would keep the stale list, while a context
* change still reaches it.
*/
export const MessageArtifactPathsContext = createContext<
readonly string[] | null
>(null);
/**
* Builds the `a` renderer shared by message content and generic markdown.
* Passing a `threadId` also resolves `/mnt/` artifact links, plus relative
* artifact links inside a `MessageArtifactPathsContext`; without it those
* links fall through to the default external-link handling.
*/
export function createMarkdownLinkComponent(
threadId?: string,
knowledgeSources: readonly RetrievalSource[] = [],
) {
return function MarkdownLink({
href,
...props
}: AnchorHTMLAttributes<HTMLAnchorElement>) {
const artifactPaths = useContext(MessageArtifactPathsContext);
if (/^#(?:user-content-)?knowledge-source-/.test(href ?? "")) {
const id = retrievalSourceId(href);
const source = knowledgeSources.find((item) => item.id === id);
return source ? (
<KnowledgeCitation source={source} />
) : (
<span>{props.children}</span>
);
}
// Reject unsafe schemes up front so a prompt-injected / pasted href can
// never reach the rendered anchor — including through the citation
// branch (which renders <a href={href}> directly). Check before the
// citation block so prompt-injected [citation:x](javascript:...) is
// blocked. Keep the visible label so the user can still see what the
// link claimed to point at.
if (href !== undefined && !isSafeHref(href)) {
// Intentionally no {...props} spread: react-markdown props like `node`
// (and anchor-only attributes such as target/rel) are not valid on a
// <span> and would trigger React DOM warnings.
const { className, children } = props;
return (
<UnsafeLink href={href} className={className}>
{children}
</UnsafeLink>
);
}
// Knowledge destinations also appear as ordinary [Title](URL) Sources links.
if (knowledgeSourceId(href)) {
return <CitationLink {...props} href={href} />;
}
// Safe-href check passed — citation links now route through CitationLink.
const childrenText = extractReactNodeText(props.children);
if (childrenText !== null) {
const match = /^citation:(.+)$/.exec(childrenText);
if (match) {
const [, text] = match;
return (
<CitationLink {...props} href={href}>
{text}
</CitationLink>
);
}
}
// Artifact links (`/mnt/…`, or relative inside the message list) open in a
// new tab, styled like any other link so they read as clickable.
let resolvedHref = href;
let opensArtifact = false;
if (threadId && href?.startsWith("/mnt/")) {
resolvedHref = resolveMarkdownArtifactURL(href, threadId);
opensArtifact = true;
} else if (
threadId &&
artifactPaths &&
href &&
isPotentialRelativeArtifactReference(href)
) {
const artifactURL = resolveRelativeArtifactURL(
href,
threadId,
artifactPaths,
);
if (!artifactURL) {
// Left as-is, the browser would resolve the href against the chat
// route (/workspace/chats/<file>) and open a broken "thread".
const { className, children } = props;
return (
<span
className={cn(
"text-muted-foreground underline decoration-dotted underline-offset-2",
className,
)}
title={`No single artifact in this conversation matches ${href}`}
>
{children}
</span>
);
}
resolvedHref = artifactURL;
opensArtifact = true;
}
const { className, target, rel, ...rest } = props;
const opensNewTab = opensArtifact || isExternalUrl(href);
return (
<a
{...rest}
href={resolvedHref}
className={cn(
"text-primary decoration-primary/30 hover:decoration-primary/60 underline underline-offset-2 transition-colors",
className,
)}
target={target ?? (opensNewTab ? "_blank" : undefined)}
rel={rel ?? (opensNewTab ? "noopener noreferrer" : undefined)}
/>
);
};
}