Skip to content
TypeScript

fix(web): render nested markdown images correctly (#8501)

oliverc0e09f323ac9
diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx
index dd21a4e1bf4..c55bfd05909 100644
--- a/apps/web/src/components/ChatMarkdown.tsx
+++ b/apps/web/src/components/ChatMarkdown.tsx
@@ -24,12 +24,16 @@ import {
squashAtomCommandFailure,
type AtomCommandResult,
} from "@t3tools/client-runtime/state/runtime";
-import { classifyMarkdownImageSource } from "@t3tools/client-runtime/markdown-images";
+import {
+ classifyMarkdownImageSource,
+ markdownImageSourceFragment,
+} from "@t3tools/client-runtime/markdown-images";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/unstable/reactivity";
import React, {
Children,
Suspense,
+ type CSSProperties,
type ClipboardEvent as ReactClipboardEvent,
type MouseEvent as ReactMouseEvent,
isValidElement,
@@ -90,6 +94,7 @@ import {
import { remarkNormalizeListItemIndentation } from "../markdown-list-indentation";
import {
extractMarkdownLinkHrefs,
+ isWindowsDrivePathHref,
normalizeMarkdownLinkDestination,
resolveInlineCodeFileLinkMeta,
resolveMarkdownFileLinkMeta,
@@ -149,6 +154,7 @@ interface ChatMarkdownProps {
lineBreaks?: boolean;
/** Parse sanitized raw HTML instead of displaying its source text. */
parseRawHtml?: boolean;
+ imageBaseDir?: string | undefined;
}
export function canUseMarkdownFileShellActions(
@@ -237,27 +243,24 @@ export function orderedListGutterStyle(
return { "--list-gutter": `${markerWidth + 1}ch` };
}
-type MarkdownHtmlAstNode = {
+type MarkdownImageHastNode = {
type?: string;
tagName?: string;
properties?: Record<string, unknown>;
- children?: MarkdownHtmlAstNode[];
+ children?: MarkdownImageHastNode[];
};
-/** Preserve Windows drive paths through the protocol allowlist in rehype-sanitize. */
-function rehypeNormalizeWindowsImageSrc() {
- return (tree: MarkdownHtmlAstNode) => {
- const visit = (node: MarkdownHtmlAstNode) => {
+/** Carries authored image source metadata through the sanitizer to the image renderer. */
+function rehypePreserveImageSourceMeta() {
+ return (tree: MarkdownImageHastNode) => {
+ const visit = (node: MarkdownImageHastNode) => {
const src = node.properties?.src;
- if (
- node.type === "element" &&
- node.tagName === "img" &&
- typeof src === "string" &&
- WINDOWS_DRIVE_PATH_REGEX.test(src)
- ) {
+ const title = node.properties?.title;
+ if (node.type === "element" && node.tagName === "img") {
node.properties = {
...node.properties,
- src: `file:///${src.replaceAll("\\", "/")}`,
+ ...(typeof src === "string" && isWindowsDrivePathHref(src) ? { dataLocalSrc: src } : {}),
+ ...(typeof title === "string" ? { dataMarkdownTitle: title } : {}),
};
}
node.children?.forEach(visit);
@@ -274,6 +277,7 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
"*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"),
code: [...(defaultSchema.attributes?.code ?? []), "dataCodeMeta", "dataInlineCode"],
blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"],
+ img: [...(defaultSchema.attributes?.img ?? []), "dataLocalSrc", "dataMarkdownTitle"],
},
protocols: {
...defaultSchema.protocols,
@@ -301,7 +305,7 @@ const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS = [
const CHAT_MARKDOWN_REHYPE_PLUGINS = [
rehypeRaw,
- rehypeNormalizeWindowsImageSrc,
+ rehypePreserveImageSourceMeta,
[rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA],
] satisfies NonNullable<ReactMarkdownOptions["rehypePlugins"]>;
@@ -1045,21 +1049,63 @@ const MarkdownLinkFavicon = memo(function MarkdownLinkFavicon({ host }: { host:
);
});
-const CHAT_MARKDOWN_IMAGE_SIZE_CLASS_NAME =
- "h-auto w-auto max-h-[30rem] max-w-[min(100%,30rem)] object-contain";
+const CHAT_MARKDOWN_IMAGE_BOUNDS_CLASS_NAME = "max-h-[30rem] max-w-[min(100%,30rem)]";
+const CHAT_MARKDOWN_IMAGE_SIZE_CLASS_NAME = cn(
+ "h-auto w-auto object-contain",
+ CHAT_MARKDOWN_IMAGE_BOUNDS_CLASS_NAME,
+);
+
+function markdownImageCopy(alt: string, src: string, title: string | undefined): string {
+ const escapedAlt = alt.replaceAll("\\", "\\\\").replaceAll("[", "\\[").replaceAll("]", "\\]");
+ const titleSuffix =
+ title === undefined ? "" : ` "${title.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
+ return `![${escapedAlt}](${src}${titleSuffix})`;
+}
+
+function authoredImageSizeStyle(
+ width: string | number | undefined,
+ height: string | number | undefined,
+): CSSProperties | undefined {
+ const parsedWidth = Number(width);
+ const parsedHeight = Number(height);
+ const hasWidth = Number.isFinite(parsedWidth) && parsedWidth > 0;
+ const hasHeight = Number.isFinite(parsedHeight) && parsedHeight > 0;
+ if (hasWidth && hasHeight) {
+ return {
+ width: parsedWidth,
+ height: "auto",
+ aspectRatio: `${parsedWidth} / ${parsedHeight}`,
+ maxWidth: `min(100%, 30rem, ${(30 * parsedWidth) / parsedHeight}rem)`,
+ };
+ }
+ if (hasWidth) return { maxWidth: `min(100%, 30rem, ${parsedWidth}px)` };
+ if (hasHeight) return { maxHeight: `min(30rem, ${parsedHeight}px)` };
+ return undefined;
+}
-// block! outranks the unlayered `.chat-markdown img { display: inline-block }`
-// rule, keeping workspace images on the same block layout as their placeholder.
+const CHAT_MARKDOWN_WORKSPACE_IMAGE_LAYOUT_CLASS_NAME = "inline-block!";
const CHAT_MARKDOWN_WORKSPACE_IMAGE_CLASS_NAME = cn(
CHAT_MARKDOWN_IMAGE_SIZE_CLASS_NAME,
- "my-1 block! rounded-lg border border-border/40",
+ CHAT_MARKDOWN_WORKSPACE_IMAGE_LAYOUT_CLASS_NAME,
+ "rounded-lg border border-border/40",
);
-function ChatMarkdownImageFallback(props: { readonly alt: string }) {
+function ChatMarkdownImageFallback(props: {
+ readonly alt: string;
+ readonly copyMarkdown?: string | undefined;
+}) {
return (
- <span className="my-1 inline-flex items-center gap-1.5 rounded-md border border-border/40 bg-muted/40 px-2 py-1 text-xs text-muted-foreground">
- <TriangleAlertIcon aria-hidden className="size-3.5 shrink-0" />
- {props.alt.length > 0 ? `Image unavailable · ${props.alt}` : "Image unavailable"}
+ <span
+ data-markdown-copy={props.copyMarkdown}
+ className={cn(
+ CHAT_MARKDOWN_WORKSPACE_IMAGE_LAYOUT_CLASS_NAME,
+ "rounded-md border border-border/40 bg-muted/40 px-2 py-1 text-xs text-muted-foreground",
+ )}
+ >
+ <span className="inline-flex items-center gap-1.5">
+ <TriangleAlertIcon aria-hidden className="size-3.5 shrink-0" />
+ {props.alt.length > 0 ? `Image unavailable · ${props.alt}` : "Image unavailable"}
+ </span>
</span>
);
}
@@ -1069,6 +1115,9 @@ const ChatMarkdownWorkspaceImage = memo(function ChatMarkdownWorkspaceImage(prop
readonly threadRef: ScopedThreadRef;
readonly path: string;
readonly alt: string;
+ readonly copyMarkdown: string;
+ readonly srcFragment: string;
+ readonly style?: CSSProperties | undefined;
}) {
const assetUrl = useAssetUrlState(props.threadRef.environmentId, {
_tag: "workspace-file",
@@ -1078,24 +1127,32 @@ const ChatMarkdownWorkspaceImage = memo(function ChatMarkdownWorkspaceImage(prop
const [failedUrl, setFailedUrl] = useState<string | null>(null);
if (assetUrl._tag === "Failure" || (assetUrl._tag === "Success" && failedUrl === assetUrl.url)) {
- return <ChatMarkdownImageFallback alt={props.alt} />;
+ return <ChatMarkdownImageFallback alt={props.alt} copyMarkdown={props.copyMarkdown} />;
}
if (assetUrl._tag !== "Success") {
return (
<span
+ data-markdown-copy={props.copyMarkdown}
role="status"
aria-label="Loading image"
- className="my-1 block aspect-video w-full max-w-[30rem] rounded-lg bg-muted/60"
+ className={cn(
+ CHAT_MARKDOWN_WORKSPACE_IMAGE_LAYOUT_CLASS_NAME,
+ "aspect-video w-64 max-w-full rounded-lg bg-muted/60",
+ CHAT_MARKDOWN_IMAGE_BOUNDS_CLASS_NAME,
+ )}
+ style={props.style}
/>
);
}
return (
<img
- src={assetUrl.url}
+ src={assetUrl.url + props.srcFragment}
alt={props.alt}
+ data-markdown-copy={props.copyMarkdown}
loading="lazy"
draggable={false}
className={CHAT_MARKDOWN_WORKSPACE_IMAGE_CLASS_NAME}
+ style={props.style}
onError={() => setFailedUrl(assetUrl.url)}
/>
);
@@ -1636,6 +1693,7 @@ function ChatMarkdown({
className,
lineBreaks = false,
parseRawHtml = true,
+ imageBaseDir,
}: ChatMarkdownProps) {
const { resolvedTheme } = useTheme();
const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
@@ -1729,6 +1787,7 @@ function ChatMarkdown({
return buildFileLinkParentSuffixByPath(filePaths);
}, [inlineCodeFileLinkMetaByText, markdownFileLinkMetaByHref]);
const markdownUrlTransform = useCallback((href: string) => {
+ if (isWindowsDrivePathHref(href)) return href;
return rewriteMarkdownFileUriHref(href) ?? defaultUrlTransform(href);
}, []);
// Re-emit highlighted content as markdown so copying out of the rendered
@@ -2146,10 +2205,19 @@ function ChatMarkdown({
</code>
);
},
- img({ node: _node, title: _title, src, alt, ...props }) {
- const srcString = typeof src === "string" ? normalizeMarkdownLinkDestination(src) : "";
+ img({ node, title, src, alt, ...props }) {
+ const localSrc = node?.properties?.dataLocalSrc;
+ const markdownTitle = node?.properties?.dataMarkdownTitle;
+ const authoredSrc = typeof localSrc === "string" ? localSrc : src;
+ const authoredTitle = typeof markdownTitle === "string" ? markdownTitle : title;
+ const srcString =
+ typeof authoredSrc === "string" ? normalizeMarkdownLinkDestination(authoredSrc) : "";
+ const classifiedSrc =
+ typeof localSrc === "string" ? srcString.replaceAll("\\", "/") : srcString;
const altText = alt ?? "";
- const imageSource = classifyMarkdownImageSource(srcString, cwd);
+ const copyMarkdown = markdownImageCopy(altText, srcString, authoredTitle);
+ const authoredSizeStyle = authoredImageSizeStyle(props.width, props.height);
+ const imageSource = classifyMarkdownImageSource(classifiedSrc, imageBaseDir ?? cwd);
if (imageSource._tag === "Direct") {
return (
<img
@@ -2158,6 +2226,7 @@ function ChatMarkdown({
alt={altText}
loading="lazy"
className={cn(props.className, CHAT_MARKDOWN_IMAGE_SIZE_CLASS_NAME)}
+ style={authoredSizeStyle}
/>
);
}
@@ -2167,10 +2236,13 @@ function ChatMarkdown({
threadRef={threadRef}
path={imageSource.path}
alt={altText}
+ copyMarkdown={copyMarkdown}
+ srcFragment={markdownImageSourceFragment(classifiedSrc)}
+ style={authoredSizeStyle}
/>
);
}
- return <ChatMarkdownImageFallback alt={altText} />;
+ return <ChatMarkdownImageFallback alt={altText} copyMarkdown={copyMarkdown} />;
},
table({ node: _node, ...props }) {
return <MarkdownTable {...props} />;
@@ -2213,6 +2285,7 @@ function ChatMarkdown({
diffThemeName,
fileLinkParentSuffixByPath,
inlineCodeFileLinkMetaByText,
+ imageBaseDir,
isStreaming,
markdownFileLinkMetaByHref,
onTaskListChange,
diff --git a/apps/web/src/components/ChatMarkdown.workspace-images.test.tsx b/apps/web/src/components/ChatMarkdown.workspace-images.test.tsx
index 37a0f27a0ba..39ea214d43c 100644
--- a/apps/web/src/components/ChatMarkdown.workspace-images.test.tsx
+++ b/apps/web/src/components/ChatMarkdown.workspace-images.test.tsx
@@ -4,16 +4,16 @@ import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
const testState = vi.hoisted(() => ({
resources: [] as Array<unknown>,
- assetState: "success" as "success" | "loading",
+ assetState: "success" as "success" | "loading" | "failure",
}));
vi.mock("@effect/atom-react", () => ({ useAtomValue: () => null }));
vi.mock("../assets/assetUrls", () => ({
useAssetUrlState: (_environmentId: unknown, resource: unknown) => {
testState.resources.push(resource);
- return testState.assetState === "loading"
- ? { _tag: "Loading" }
- : { _tag: "Success", url: "https://signed.test/workspace-image.svg" };
+ if (testState.assetState === "loading") return { _tag: "Loading" };
+ if (testState.assetState === "failure") return { _tag: "Failure" };
+ return { _tag: "Success", url: "https://signed.test/workspace-image.svg" };
},
}));
vi.mock("../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
@@ -42,6 +42,7 @@ vi.mock("~/lib/openPullRequestLink", () => ({
}));
import ChatMarkdown from "./ChatMarkdown";
+import { FileMarkdownPreview } from "./files/FileMarkdownPreview";
const threadRef = {
environmentId: EnvironmentId.make("env-windows"),
@@ -58,12 +59,60 @@ function renderWithoutThread(markdown: string): string {
return renderToStaticMarkup(<ChatMarkdown cwd={"C:\\Users\\shawn\\project"} text={markdown} />);
}
+function renderFilePreview(cwd: string, relativePath: string): string {
+ return renderToStaticMarkup(
+ <FileMarkdownPreview
+ cwd={cwd}
+ relativePath={relativePath}
+ text="![diagram](images/diagram.png)"
+ threadRef={threadRef}
+ />,
+ );
+}
+
+function copiedMarkdownFrom(html: string): string {
+ const copy = /data-markdown-copy="([^"]*)"/.exec(html)?.[1]?.replaceAll("&quot;", '"');
+ expect(copy).toBeDefined();
+ return copy ?? "";
+}
+
+function firstInlineStyle(html: string): Record<string, string> {
+ const style = /style="([^"]+)"/.exec(html)?.[1];
+ expect(style).toBeDefined();
+ return Object.fromEntries(
+ (style ?? "").split(";").map((declaration) => {
+ const separator = declaration.indexOf(":");
+ return [declaration.slice(0, separator), declaration.slice(separator + 1)];
+ }),
+ );
+}
+
describe("ChatMarkdown workspace images", () => {
beforeEach(() => {
testState.resources = [];
testState.assetState = "success";
});
+ it.each([
+ ["/workspace/project", "docs/README.md", "/workspace/project/docs/images/diagram.png"],
+ [
+ "C:\\Users\\shawn\\project",
+ "docs\\README.md",
+ "C:\\Users\\shawn\\project\\docs\\images\\diagram.png",
+ ],
+ ["/workspace/project", "README.md", "/workspace/project/images/diagram.png"],
+ ])("resolves images beside a nested file in %s", (cwd, relativePath, expectedPath) => {
+ renderFilePreview(cwd, relativePath);
+
+ expect(testState.resources).toEqual([
+ {
+ _tag: "workspace-file",
+ threadId: threadRef.threadId,
+ path: expectedPath,
+ },
+ ]);
+ });
+
it("loads every Windows workspace path form through a signed asset URL", () => {
const imagePath = "C:/Users/shawn/project/.t3/workspace-image.svg";
const html = render(
@@ -108,13 +157,116 @@ describe("ChatMarkdown workspace images", () => {
expect(html).toContain("https://signed.test/workspace-image.svg");
});
- it("uses a static placeholder while a signed asset URL loads", () => {
+ it("keeps a tall image placeholder and loaded image at the same proportional bounds", () => {
+ const markdown = '<img src=".t3/workspace-image.svg" alt="sized" width="96" height="128">';
+ const loadedStyle = firstInlineStyle(render(markdown));
+ testState.assetState = "loading";
+ const loadingStyle = firstInlineStyle(render(markdown));
+
+ expect(loadedStyle).toMatchObject({
+ width: "96px",
+ height: "auto",
+ "aspect-ratio": "96 / 128",
+ "max-width": "min(100%, 30rem, 22.5rem)",
+ });
+ expect(loadingStyle).toEqual(loadedStyle);
+ });
+
+ it.each([
+ ["width", "max-width", "min(100%, 30rem, 300px)"],
+ ["height", "max-height", "min(30rem, 300px)"],
+ ])("treats a lone authored %s as a cap", (axis, constraint, expectedValue) => {
+ const markdown = `<img src=".t3/workspace-image.svg" alt="sized" ${axis}="300">`;
+ const loadedStyle = firstInlineStyle(render(markdown));
+
+ expect(loadedStyle).not.toHaveProperty(axis);
+ expect(loadedStyle).toHaveProperty(constraint, expectedValue);
+ });
+
+ it("keeps all images baseline-aligned and workspace images inline", () => {
+ const html = render(
+ "![remote](https://example.com/badge.svg) ![workspace](.t3/workspace-image.svg)",
+ );
+ const classNames = Array.from(html.matchAll(/<img[^>]*class="([^"]*)"/g), (match) =>
+ match[1]?.split(" "),
+ );
+
+ expect(classNames).toHaveLength(2);
+ expect(classNames[1]).toContain("inline-block!");
+
+ const centeredHtml = render(
+ '<p align="center"><img src=".t3/workspace-image.svg" alt="logo"></p>',
+ );
+ const centeredClassName = /<img[^>]*class="([^"]*)"/.exec(centeredHtml)?.[1];
+
+ expect(centeredClassName?.split(" ")).toContain("inline-block!");
+ });
+
+ it("retains an authored SVG fragment on the signed URL", () => {
+ const html = render("![logo](icons.svg#logo)");
+
+ expect(html).toContain('src="https://signed.test/workspace-image.svg#logo"');
+ });
+
+ it.each(["success", "loading", "failure", "no-thread"] as const)(
+ "copies the authored workspace source (%s)",
+ (scenario) => {
+ if (scenario === "no-thread") {
+ const html = renderWithoutThread("![diagram](images/diagram.png)");
+ expect(copiedMarkdownFrom(html)).toBe("![diagram](images/diagram.png)");
+ return;
+ }
+
+ testState.assetState = scenario;
+ const html = render("![diagram](images/diagram.png#preview)");
+
+ expect(copiedMarkdownFrom(html)).toBe("![diagram](images/diagram.png#preview)");
+ },
+ );
+
+ it("copies an authored title with a workspace image", () => {
+ const html = render('![logo](images/logo.svg "My Title")');
+
+ expect(copiedMarkdownFrom(html)).toBe('![logo](images/logo.svg "My Title")');
+ });
+
+ it("escapes double quotes in an authored image title", () => {
+ const html = render(`![logo](images/logo.svg 'My "Title"')`);
+
+ expect(copiedMarkdownFrom(html)).toBe('![logo](images/logo.svg "My \\"Title\\"")');
+ });
+
+ it("escapes a closing bracket in authored image alt text", () => {
+ const markdown = String.raw`![build\] badge](badge.svg)`;
+
+ expect(copiedMarkdownFrom(render(markdown))).toBe(markdown);
+ });
+
+ it("escapes a literal backslash in authored image alt text", () => {
+ const markdown = String.raw`![folder\\name](badge.svg)`;
+
+ expect(copiedMarkdownFrom(render(markdown))).toBe(markdown);
+ });
+
+ it("escapes a literal backslash before a quote in an authored image title", () => {
+ const html = render(
+ String.raw`<img src="images/logo.svg" alt="logo" title="Path \&quot;Title\&quot;">`,
+ );
+
+ expect(copiedMarkdownFrom(html)).toBe(
+ String.raw`![logo](images/logo.svg "Path \\\"Title\\\"")`,
+ );
+ });
+
+ it("uses a static bounded-width placeholder while a signed asset URL loads", () => {
testState.assetState = "loading";
const html = render("![loading](.t3/workspace-image.svg)");
+ const className = /<span[^>]*aria-label="Loading image"[^>]*class="([^"]*)"/.exec(html)?.[1];
expect(html).toContain('aria-label="Loading image"');
expect(html).not.toContain("animate-pulse");
+ expect(className?.split(" ")).toContain("w-64");
});
it("never passes a workspace source to a raw image when thread context is unavailable", () => {
diff --git a/apps/web/src/components/files/FileMarkdownPreview.tsx b/apps/web/src/components/files/FileMarkdownPreview.tsx
new file mode 100644
index 00000000000..e36ada48acb
--- /dev/null
+++ b/apps/web/src/components/files/FileMarkdownPreview.tsx
@@ -0,0 +1,34 @@
+import type { ScopedThreadRef } from "@t3tools/contracts";
+
+import ChatMarkdown from "~/components/ChatMarkdown";
+import { resolvePathLinkTarget } from "~/terminal-links";
+
+export function FileMarkdownPreview(props: {
+ readonly cwd: string;
+ readonly relativePath: string;
+ readonly text: string;
+ readonly threadRef: ScopedThreadRef;
+ readonly onTaskListChange?:
+ | ((input: { readonly markerOffset: number; readonly checked: boolean }) => void)
+ | undefined;
+}) {
+ const lastSeparator = Math.max(
+ props.relativePath.lastIndexOf("/"),
+ props.relativePath.lastIndexOf("\\"),
+ );
+ const imageBaseDir =
+ lastSeparator >= 0
+ ? resolvePathLinkTarget(props.relativePath.slice(0, lastSeparator), props.cwd)
+ : props.cwd;
+
+ return (
+ <ChatMarkdown
+ text={props.text}
+ cwd={props.cwd}
+ imageBaseDir={imageBaseDir}
+ threadRef={props.threadRef}
+ className="mx-auto max-w-4xl px-6 py-5"
+ onTaskListChange={props.onTaskListChange}
+ />
+ );
+}
diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsx
index a8c364763c2..bc2ff98f0a2 100644
--- a/apps/web/src/components/files/FilePreviewPanel.tsx
+++ b/apps/web/src/components/files/FilePreviewPanel.tsx
@@ -18,7 +18,6 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { isBrowserPreviewFile, openFileInPreview } from "~/browser/openFileInPreview";
import { useAssetUrlState } from "~/assets/assetUrls";
-import ChatMarkdown from "~/components/ChatMarkdown";
import { OpenInPicker } from "~/components/chat/OpenInPicker";
import { useRemoteOpenState } from "~/remoteOpen";
import { useClientSettings } from "~/hooks/useSettings";
@@ -42,6 +41,7 @@ import { useAtomCommand } from "~/state/use-atom-command";
import { useAtomQueryRunner } from "~/state/use-atom-query-runner";
import FileBrowserPanel from "./FileBrowserPanel";
+import { FileMarkdownPreview } from "./FileMarkdownPreview";
import {
type FileCommentAnnotationEntry,
type FileCommentAnnotationGroup,
@@ -727,11 +727,11 @@ function RenderedMarkdownSurface({
return (
<ScrollArea className="min-h-0 flex-1">
- <ChatMarkdown
+ <FileMarkdownPreview
text={contents}
cwd={cwd}
+ relativePath={relativePath}
threadRef={threadRef}
- className="mx-auto max-w-4xl px-6 py-5"
onTaskListChange={({ markerOffset, checked }) => {
const currentContents =
getOptimisticProjectFileQueryData(environmentId, cwd, relativePath)?.contents ??
diff --git a/apps/web/src/markdown-links.test.ts b/apps/web/src/markdown-links.test.ts
index c7a2bcedcfa..75c5d329f9f 100644
--- a/apps/web/src/markdown-links.test.ts
+++ b/apps/web/src/markdown-links.test.ts
@@ -5,6 +5,7 @@ import ReactMarkdown from "react-markdown";
import {
extractMarkdownLinkHrefs,
+ isWindowsDrivePathHref,
resolveInlineCodeFileLinkMeta,
resolveMarkdownFileLinkMeta,
resolveMarkdownFileLinkTarget,
@@ -13,6 +14,16 @@ import {
shouldOpenMarkdownFileLinkInEditor,
} from "./markdown-links";
+describe("isWindowsDrivePathHref", () => {
+ it.each([
+ ["C:\\repo\\image.png", true],
+ ["C:%5Crepo%5Cimage.png", true],
+ ["https://example.com/image.png", false],
+ ])("classifies %s as %s", (href, expected) => {
+ expect(isWindowsDrivePathHref(href)).toBe(expected);
+ });
+});
+
function renderMarkdownLinkHref(markdown: string): string | undefined {
let renderedHref: string | undefined;
renderToStaticMarkup(
diff --git a/apps/web/src/markdown-links.ts b/apps/web/src/markdown-links.ts
index 24ecd1906ee..1ce25765ee4 100644
--- a/apps/web/src/markdown-links.ts
+++ b/apps/web/src/markdown-links.ts
@@ -84,6 +84,10 @@ function safeDecode(value: string): string {
}
}
+export function isWindowsDrivePathHref(href: string): boolean {
+ return WINDOWS_DRIVE_PATH_PATTERN.test(safeDecode(href));
+}
+
function unwrapMarkdownLinkDestination(value: string): string {
return value.startsWith("<") && value.endsWith(">") ? value.slice(1, -1) : value;
}
diff --git a/packages/client-runtime/src/markdownImages.test.ts b/packages/client-runtime/src/markdownImages.test.ts
index a4160c3da4c..8ee18675623 100644
--- a/packages/client-runtime/src/markdownImages.test.ts
+++ b/packages/client-runtime/src/markdownImages.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
-import { classifyMarkdownImageSource } from "./markdownImages.js";
+import { classifyMarkdownImageSource, markdownImageSourceFragment } from "./markdownImages.js";
describe("classifyMarkdownImageSource", () => {
it.each([
@@ -60,3 +60,12 @@ describe("classifyMarkdownImageSource", () => {
expect(classifyMarkdownImageSource(source)).toEqual({ _tag: "Blocked" });
});
});
+
+describe("markdownImageSourceFragment", () => {
+ it.each([
+ ["<icons.svg?version=2#logo>", "#logo"],
+ ["icons.svg?version=2", ""],
+ ])("extracts %s as %s", (source, fragment) => {
+ expect(markdownImageSourceFragment(source)).toBe(fragment);
+ });
+});
diff --git a/packages/client-runtime/src/markdownImages.ts b/packages/client-runtime/src/markdownImages.ts
index 404f828390a..671a94d490d 100644
--- a/packages/client-runtime/src/markdownImages.ts
+++ b/packages/client-runtime/src/markdownImages.ts
@@ -20,6 +20,12 @@ function normalizeSource(value: string): string {
return trimmed.startsWith("<") && trimmed.endsWith(">") ? trimmed.slice(1, -1) : trimmed;
}
+export function markdownImageSourceFragment(source: string): string {
+ const normalizedSource = normalizeSource(source);
+ const hashIndex = normalizedSource.indexOf("#");
+ return hashIndex >= 0 ? normalizedSource.slice(hashIndex) : "";
+}
+
function normalizeWindowsDrivePath(value: string): string {
return /^\/[A-Za-z]:[\\/]/.test(value) ? value.slice(1) : value;
}