Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export const MarkdownMathRenderer: React.FC<MarkdownMathRendererProps> = ({
const content = (
<ReactMarkdown
remarkPlugins={[remarkGfm, remarkMath, [remarkStreamingTableLinks, { isStreaming }], remarkAutolinkBoundaries, remarkAutolinkComputerFileLinks]}
rehypePlugins={[rehypeRaw, rehypeWindowsDrivePaths, [rehypeSanitize, sanitizeSchema], [rehypeSourceRange, sourceRange], rehypeKatex, [rehypeImageThumbnails, { enabled: imageThumbnails }]]}
rehypePlugins={[rehypeRaw, [rehypeWindowsDrivePaths, { markdownSource: markdownContent }], [rehypeSanitize, sanitizeSchema], [rehypeSourceRange, sourceRange], rehypeKatex, [rehypeImageThumbnails, { enabled: imageThumbnails }]]}
urlTransform={urlTransform}
components={components}
>
Expand Down
24 changes: 24 additions & 0 deletions src/web-ui/src/infrastructure/markdown/MarkdownRenderer.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1002,6 +1002,30 @@ Second paragraph.
expect(image?.src).toBe('data:image/png;base64,cmVsdS1wbmc=');
});

it('loads generated images when Markdown contains a native Windows path', async () => {
const imagePath = 'D:\\Desktop\\.openbitfun\\generated-images\\preview.jpg';

await act(async () => {
root.render(
<MarkdownRenderer
content={`![Generated preview](${imagePath})`}
basePath="C:/IgnoredWorkspace"
/>,
);
await Promise.resolve();
await Promise.resolve();
});

const image = container.querySelector<HTMLImageElement>('img[alt="Generated preview"]');
expect(image).not.toBeNull();
expect(mocks.readFileContent).toHaveBeenCalledWith(
'D:/Desktop/.openbitfun/generated-images/preview.jpg',
'base64',
undefined,
);
expect(image?.src).toBe('data:image/jpeg;base64,cmVsdS1wbmc=');
});

it.each([
['computer://output/preview%20%E5%9B%BE.png', '/srv/project/output/preview 图.png'],
['file:///srv/project/preview.png', '/srv/project/preview.png'],
Expand Down
14 changes: 12 additions & 2 deletions src/web-ui/src/infrastructure/markdown/MarkdownRenderer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,16 @@ function markdownUrlTransform(value: string, key?: string): string {
// the renderer will strip the internal prefix and read it through the
// owning workspace/session provider.
if (/^[A-Za-z]:[\\/]/.test(value)) return `file:///${value.replace(/\\/g, '/')}`;
// micromark percent-encodes backslashes in some Markdown destinations. Keep
// those references safe even when no rehype node position is available.
if (key === 'src' && /^[A-Za-z]:(?:%5C|%2F)/i.test(value)) {
try {
const decoded = decodeURIComponent(value);
if (/^[A-Za-z]:[\\/]/.test(decoded)) return `file:///${decoded.replace(/\\/g, '/')}`;
} catch {
// Leave malformed URLs to react-markdown's normal safety transform.
}
}
if (key === 'src' && /^data:image\/(png|jpeg|gif|webp|bmp|svg\+xml|avif);base64,/i.test(value)) return value;
if (value.startsWith(CANVAS_LINK_PREFIX) && parseCanvasArtifactReference(value)) {
return value;
Expand Down Expand Up @@ -1756,7 +1766,7 @@ const MarkdownSurface = React.memo<MarkdownRendererProps & { thinking?: boolean;
const basicFragment = (
<ReactMarkdown
remarkPlugins={[remarkGfm, remarkAutolinkBoundaries, remarkAutolinkInternalLinks]}
rehypePlugins={[rehypeRaw, rehypeWindowsDrivePaths, [rehypeSanitize, sanitizeSchema]]}
rehypePlugins={[rehypeRaw, [rehypeWindowsDrivePaths, { markdownSource: fragment }], [rehypeSanitize, sanitizeSchema]]}
urlTransform={markdownUrlTransform}
components={fragmentComponents}
>{fragment}</ReactMarkdown>
Expand All @@ -1778,7 +1788,7 @@ const MarkdownSurface = React.memo<MarkdownRendererProps & { thinking?: boolean;
const basicMarkdownRenderer = (
<ReactMarkdown
remarkPlugins={[remarkGfm, ...(!isStreaming ? [remarkCachedParse] : []), [remarkStreamingTableLinks, { isStreaming }], remarkAutolinkBoundaries, remarkAutolinkInternalLinks]}
rehypePlugins={[rehypeRaw, rehypeWindowsDrivePaths, [rehypeSanitize, sanitizeSchema], [rehypeSourceRange, sourceRange], [rehypeImageThumbnails, { enabled: imageThumbnails }]]}
rehypePlugins={[rehypeRaw, [rehypeWindowsDrivePaths, { markdownSource: markdownContent }], [rehypeSanitize, sanitizeSchema], [rehypeSourceRange, sourceRange], [rehypeImageThumbnails, { enabled: imageThumbnails }]]}
urlTransform={markdownUrlTransform}
components={components}
>
Expand Down
91 changes: 88 additions & 3 deletions src/web-ui/src/infrastructure/markdown/rehypeWindowsDrivePaths.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,105 @@
import { visit } from 'unist-util-visit';

const WINDOWS_DRIVE_PATH = /^[A-Za-z]:[\\/]/;
const ENCODED_WINDOWS_DRIVE_PATH = /^[A-Za-z]:(?:%5C|%2F)/i;

interface RehypeWindowsDrivePathsOptions {
/** Original Markdown source, used when parsing escaped Windows paths loses separators. */
markdownSource?: string;
}

interface NodePosition {
start?: { offset?: number };
end?: { offset?: number };
}

function extractDestinationFromMarkdown(source: string, position: NodePosition | undefined): string | undefined {
const start = position?.start?.offset;
const end = position?.end?.offset;
if (typeof start !== 'number' || typeof end !== 'number' || end <= start) {
return undefined;
}

const snippet = source.slice(start, end);
// Use the last destination in case an anchor contains an image in its label.
const markerIndex = snippet.lastIndexOf('](');
if (markerIndex === -1) {
return undefined;
}

let destination = snippet.slice(markerIndex + 2).trim();
if (destination.endsWith(')')) {
destination = destination.slice(0, -1).trimEnd();
}

if (destination.startsWith('<')) {
const closeIndex = destination.indexOf('>');
return closeIndex === -1 ? undefined : destination.slice(1, closeIndex);
}

const whitespaceIndex = destination.search(/[\t\r\n ]/);
return whitespaceIndex === -1 ? destination : destination.slice(0, whitespaceIndex);
}

function extractSourceAttribute(source: string, position: NodePosition | undefined, property: string): string | undefined {
const start = position?.start?.offset;
const end = position?.end?.offset;
if (typeof start !== 'number' || typeof end !== 'number' || end <= start) {
return undefined;
}

const snippet = source.slice(start, end);
const match = snippet.match(new RegExp(`\\b${property}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i'));
return match?.[1] ?? match?.[2] ?? match?.[3];
}

function sourceValueForProperty(source: string | undefined, node: any, property: string): string | undefined {
if (!source || property !== 'src') {
return undefined;
}

return extractDestinationFromMarkdown(source, node.position)
?? extractSourceAttribute(source, node.position, property);
}

function asWindowsFileUrl(value: string, allowEncoded = true): string | undefined {
if (WINDOWS_DRIVE_PATH.test(value)) {
return `file:///${value.replace(/\\/g, '/')}`;
}

if (!allowEncoded || !ENCODED_WINDOWS_DRIVE_PATH.test(value)) {
return undefined;
}

try {
const decoded = decodeURIComponent(value);
return WINDOWS_DRIVE_PATH.test(decoded)
? `file:///${decoded.replace(/\\/g, '/')}`
: undefined;
} catch {
return undefined;
}
}

/**
* Mark Windows drive-letter paths as local file references before
* rehype-sanitize evaluates their apparent protocol (`C:`). The canonical
* `file:///C:/...` form also keeps the transformed value a valid file URI if
* another renderer ever observes it before local-path normalization.
*/
export function rehypeWindowsDrivePaths() {
export function rehypeWindowsDrivePaths(options: RehypeWindowsDrivePathsOptions = {}) {
return (tree: unknown) => {
visit(tree, 'element', (node: any) => {
if (!node.properties) return;
for (const property of ['src', 'href']) {
const value = node.properties?.[property];
if (typeof value === 'string' && WINDOWS_DRIVE_PATH.test(value)) {
node.properties[property] = `file:///${value.replace(/\\/g, '/')}`;
const sourceValue = sourceValueForProperty(options.markdownSource, node, property);
const localValue = typeof sourceValue === 'string' ? sourceValue : value;
if (typeof localValue === 'string') {
const fileUrl = asWindowsFileUrl(localValue, property === 'src');
if (fileUrl) {
node.properties[property] = fileUrl;
}
}
}
});
Expand Down
Loading