feat(markdown): render inline images in messages and markdown files

Route markdown image nodes through a shared MarkdownImage component that
loads local paths through the raw file API, and allow data:image/* sources
through the sanitizer and URL transform so inline images survive rendering.

Render image attachments as thumbnails in the message thread, and accept
image/webp uploads.
This commit is contained in:
Chris Scott committed 2026-10-13 00:29:00 +00:00
1 parent 93faf387d2
commit be93975d90
13 files changed
+263 -18

No files matched your search

+1
View File
@@ -274,6 +274,7 @@ function getMimeType(filePath: string): AllowedMimeType {
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.svg': 'image/svg+xml',
'.pdf': 'application/pdf',
'.zip': 'application/zip',
@@ -1,6 +1,7 @@
import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { MarkdownRenderer } from './MarkdownRenderer'
import { getFileApiUrl } from '@/api/files'
describe('MarkdownRenderer', () => {
it('toggles a task list item in the source content', () => {
@@ -27,4 +28,13 @@ describe('MarkdownRenderer', () => {
expect(document.documentElement.dataset.fileProbe).toBeUndefined()
expect(screen.getByAltText('Logo')).toHaveAttribute('src', 'docs/logo.png')
})
it('loads a relative image through the raw file API resolved against the file path', () => {
render(<MarkdownRenderer content={'![l](img/logo.png)'} filePath="repo/docs/README.md" />)
expect(screen.getByAltText('l')).toHaveAttribute(
'src',
getFileApiUrl('repo/docs/img/logo.png', { params: { raw: true } }),
)
})
})
@@ -2,8 +2,9 @@ import { memo, useMemo, useCallback } from 'react'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import { markdownComponents } from './MarkdownComponents'
import { markdownRehypePlugins } from '@/lib/markdownRehypePlugins'
import { markdownRehypePlugins, markdownUrlTransform } from '@/lib/markdownRehypePlugins'
import { MarkdownLink } from '@/components/ui/markdown-link'
import { MarkdownImage } from '@/components/ui/markdown-image'
import { resolvePathFromFile } from '@/lib/markdownLinks'
import type { Components } from 'react-markdown'
@@ -65,6 +66,11 @@ export const MarkdownRenderer = memo(function MarkdownRenderer({ content, classN
}
}, [filePath, onOpenFile])
const resolveLocalPath = useMemo(
() => (filePath ? (path: string) => resolvePathFromFile(filePath, path) : undefined),
[filePath],
)
const components: Components = {
...markdownComponents,
input(props) {
@@ -88,6 +94,9 @@ export const MarkdownRenderer = memo(function MarkdownRenderer({ content, classN
a(props) {
return <MarkdownLink {...props} onOpenLocalPath={handleOpenLocalPath} />
},
img(props) {
return <MarkdownImage {...props} resolveLocalPath={resolveLocalPath} />
},
}
return (
@@ -95,6 +104,7 @@ export const MarkdownRenderer = memo(function MarkdownRenderer({ content, classN
<ReactMarkdown
remarkPlugins={[remarkGfm]}
rehypePlugins={markdownRehypePlugins}
urlTransform={markdownUrlTransform}
components={components}
>
{content}
@@ -3,6 +3,7 @@ import { render, screen, fireEvent } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { MemoryRouter } from 'react-router-dom'
import { MessagePart } from './MessagePart'
import { getFileApiUrl } from '@/api/files'
import { applySessionEvent, emptySessionTranscript } from '@/lib/session-projection'
import { promptSequence } from '@/test/fixtures/session-projection'
import type {
@@ -129,6 +130,53 @@ describe('MessagePart', () => {
expect(container.firstChild).toBeNull()
})
describe('markdown images', () => {
it('loads a relative image through the raw file API resolved against the directory', () => {
renderWithProviders(
<MessagePart part={textPart('![shot](docs/shot.png)')} directory="/workspace/repos/app" />,
)
expect(screen.getByAltText('shot')).toHaveAttribute(
'src',
getFileApiUrl('/workspace/repos/app/docs/shot.png', { params: { raw: true } }),
)
})
it('loads an absolute image through the raw file API without a directory', () => {
renderWithProviders(<MessagePart part={textPart('![a](/workspace/x/a.png)')} />)
expect(screen.getByAltText('a')).toHaveAttribute(
'src',
getFileApiUrl('/workspace/x/a.png', { params: { raw: true } }),
)
})
it('keeps data image sources from markdown and raw HTML', () => {
renderWithProviders(
<MessagePart
part={textPart('![d](data:image/png;base64,aGVsbG8=)\n\n<img src="data:image/png;base64,aGVsbG8=" alt="raw">')}
/>,
)
expect(screen.getByAltText('d')).toHaveAttribute('src', 'data:image/png;base64,aGVsbG8=')
expect(screen.getByAltText('raw')).toHaveAttribute('src', 'data:image/png;base64,aGVsbG8=')
})
it('keeps an external image source', () => {
renderWithProviders(<MessagePart part={textPart('![h](https://example.com/a.png)')} />)
expect(screen.getByAltText('h')).toHaveAttribute('src', 'https://example.com/a.png')
})
it('does not render a non-image data source', () => {
const { container } = renderWithProviders(
<MessagePart part={textPart('![x](data:text/html,hello)')} />,
)
expect(container.querySelector('img')).toBeNull()
})
})
describe('reasoning', () => {
it('renders null when showReasoning is false', () => {
setupSettings({
@@ -25,7 +25,7 @@ export const MessagePart = memo(function MessagePart({ part, messageID, director
switch (part.type) {
case 'text':
return <TextPart text={part.text} onFileClick={onFileClick} />
return <TextPart text={part.text} onFileClick={onFileClick} directory={directory} />
case 'reasoning':
if (simpleChatMode || !showReasoning) return null
if (!part.text.trim()) return null
@@ -491,6 +491,30 @@ describe('MessageThread', () => {
expect(container.querySelector('[data-message-id="user-42"]')).not.toBeNull()
})
it('renders image attachments as thumbnails and other files as chips', () => {
setupSettings({ simpleChatMode: false, showReasoning: false })
const messages: SessionMessageInfo[] = [
{
id: 'user-attachments',
type: 'user',
text: 'Look at these',
files: [
{ data: 'aGVsbG8=', mime: 'image/png', source: { type: 'inline' }, name: 'shot.png' },
{ data: 'dGV4dA==', mime: 'text/plain', source: { type: 'inline' }, name: 'notes.txt' },
],
time: { created: Date.now() },
},
]
render(<MessageThread sessionID="test-session" messages={messages} pending={[]} />)
const image = screen.getByAltText('shot.png')
expect(image).toHaveAttribute('src', 'data:image/png;base64,aGVsbG8=')
expect(screen.getByText('@')).toBeInTheDocument()
expect(screen.getByText('notes.txt')).toBeInTheDocument()
})
it('renders a projected shell message from the fixtures', () => {
setupSettings({ simpleChatMode: false, showReasoning: false })
@@ -21,6 +21,7 @@ import { UserMessageActionButtons } from './UserMessageActionButtons'
import { EditableUserMessage, ClickableUserMessage } from './EditableUserMessage'
import { useSettings } from '@/hooks/useSettings'
import { CopyButton } from '@/components/ui/copy-button'
import { InlineImage } from '@/components/ui/inline-image'
import { TTSButton } from '@/components/ui/tts-button'
import { backgroundShellID, collectBackgroundParts, type ShellNoticeOutcome } from '@/lib/backgroundWork'
import { groupExplorationParts, type AssistantContentItem } from '@/lib/explorationGroups'
@@ -121,15 +122,24 @@ function UserAttachments({ files: attachedFiles, agents: attachedAgents, skills:
return (
<div className="flex flex-wrap items-center gap-1 mt-1">
{files.map((file, index) => (
<span
key={`file-${index}`}
className="inline-flex items-center gap-1 px-2 py-1 rounded bg-muted border border-border text-sm text-foreground"
>
<span className="text-primary">@</span>
<span className="font-medium">{attachmentLabel(file)}</span>
</span>
))}
{files.map((file, index) =>
file.mime.startsWith('image/') ? (
<InlineImage
key={`file-${index}`}
src={`data:${file.mime};base64,${file.data}`}
alt={attachmentLabel(file)}
className="max-h-40"
/>
) : (
<span
key={`file-${index}`}
className="inline-flex items-center gap-1 px-2 py-1 rounded bg-muted border border-border text-sm text-foreground"
>
<span className="text-primary">@</span>
<span className="font-medium">{attachmentLabel(file)}</span>
</span>
),
)}
{agents.map((agent, index) => (
<span
key={`agent-${index}`}
+15 -3
View File
@@ -1,16 +1,19 @@
import React, { useEffect, useState, useId, useCallback } from 'react'
import React, { useEffect, useState, useId, useCallback, useMemo } from 'react'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import mermaid from 'mermaid'
import { Maximize2, X, AlertCircle } from 'lucide-react'
import { CopyButton } from '@/components/ui/copy-button'
import { MarkdownLink } from '@/components/ui/markdown-link'
import { MarkdownImage } from '@/components/ui/markdown-image'
import { useTheme } from '@/hooks/useTheme'
import { markdownRehypePlugins } from '@/lib/markdownRehypePlugins'
import { getWorkspaceFilePath } from '@/lib/markdownLinks'
import { markdownRehypePlugins, markdownUrlTransform } from '@/lib/markdownRehypePlugins'
interface TextPartProps {
text: string
onFileClick?: (filePath: string) => void
directory?: string
}
interface MermaidBlockProps {
@@ -181,11 +184,16 @@ function isMermaidBlockComplete(text: string): boolean {
return false
}
export function TextPart({ text, onFileClick }: TextPartProps) {
export function TextPart({ text, onFileClick, directory }: TextPartProps) {
const mermaidComplete = React.useMemo(() => {
return text ? isMermaidBlockComplete(text) : false
}, [text])
const resolveLocalPath = useMemo(
() => (directory ? (path: string) => getWorkspaceFilePath(path, { directory }) : undefined),
[directory],
)
if (!text || text.trim() === '') {
return null
}
@@ -195,6 +203,7 @@ export function TextPart({ text, onFileClick }: TextPartProps) {
<ReactMarkdown
remarkPlugins={[remarkGfm]}
rehypePlugins={markdownRehypePlugins}
urlTransform={markdownUrlTransform}
components={{
code({ className, children, ...props }) {
const isInline = !className || !className.includes('language-')
@@ -261,6 +270,9 @@ export function TextPart({ text, onFileClick }: TextPartProps) {
a(props) {
return <MarkdownLink {...props} onOpenLocalPath={onFileClick} />
},
img(props) {
return <MarkdownImage {...props} resolveLocalPath={resolveLocalPath} />
},
}}
>
{text}
@@ -0,0 +1,25 @@
import { describe, it, expect } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { InlineImage } from './inline-image'
describe('InlineImage', () => {
it('opens a full-size dialog when the thumbnail is clicked', () => {
render(<InlineImage src="data:image/png;base64,aGVsbG8=" alt="shot.png" />)
const thumbnail = screen.getByAltText('shot.png')
expect(thumbnail).toHaveAttribute('src', 'data:image/png;base64,aGVsbG8=')
fireEvent.click(screen.getByRole('button', { name: 'Expand image: shot.png' }))
expect(screen.getAllByAltText('shot.png')).toHaveLength(2)
})
it('falls back to the alt text when the image fails to load', () => {
render(<InlineImage src="broken" alt="shot.png" />)
fireEvent.error(screen.getByAltText('shot.png'))
expect(screen.queryByRole('button')).not.toBeInTheDocument()
expect(screen.getByText('shot.png')).toBeInTheDocument()
})
})
@@ -0,0 +1,44 @@
import { useState } from 'react'
import { cn } from '@/lib/utils'
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'
/**
* Renders an image as a bounded thumbnail button that opens a full-size preview dialog.
* Falls back to a muted alt-text span (or nothing) when the image fails to load.
*/
export function InlineImage({ src, alt, className }: { src: string; alt?: string; className?: string }) {
const [open, setOpen] = useState(false)
const [failed, setFailed] = useState(false)
if (failed) {
return alt ? <span className="text-xs text-muted-foreground">{alt}</span> : null
}
return (
<>
<button
type="button"
aria-label={alt ? `Expand image: ${alt}` : 'Expand image'}
onClick={() => setOpen(true)}
className="inline-flex"
>
<img
src={src}
alt={alt ?? ''}
loading="lazy"
onError={() => setFailed(true)}
className={cn(
'max-w-full max-h-80 rounded-lg border border-border object-contain cursor-zoom-in',
className,
)}
/>
</button>
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="w-auto max-w-none p-2">
<DialogTitle className="sr-only">{alt ?? 'Image'}</DialogTitle>
<img src={src} alt={alt ?? ''} className="max-w-[95vw] max-h-[90vh] object-contain" />
</DialogContent>
</Dialog>
</>
)
}
@@ -0,0 +1,34 @@
import type { ComponentPropsWithoutRef } from 'react'
import type { ExtraProps } from 'react-markdown'
import { InlineImage } from '@/components/ui/inline-image'
import { getFileApiUrl } from '@/api/files'
import { getLocalLinkPath } from '@/lib/markdownLinks'
type MarkdownImageProps = ComponentPropsWithoutRef<'img'> & ExtraProps & {
resolveLocalPath?: (path: string) => string | null
}
/**
* Renders a markdown image through the inline image viewer. Local file sources, resolved by
* `resolveLocalPath` or absolute, load through the raw file API; everything else, including
* `data:image/*` URIs, is rendered unchanged.
*/
export function MarkdownImage({ src, alt, resolveLocalPath }: MarkdownImageProps) {
if (typeof src !== 'string' || src === '') {
return null
}
const localPath = getLocalLinkPath(src)
let imageSrc = src
if (localPath) {
const resolvedPath = resolveLocalPath?.(localPath) ?? null
if (resolvedPath) {
imageSrc = getFileApiUrl(resolvedPath, { params: { raw: true } })
} else if (localPath.startsWith('/')) {
imageSrc = getFileApiUrl(localPath, { params: { raw: true } })
}
}
return <InlineImage src={imageSrc} alt={alt} />
}
+30 -4
View File
@@ -1,11 +1,37 @@
import rehypeHighlight from 'rehype-highlight'
import rehypeRaw from 'rehype-raw'
import rehypeSanitize from 'rehype-sanitize'
import type { Options } from 'react-markdown'
import rehypeSanitize, { defaultSchema } from 'rehype-sanitize'
import { defaultUrlTransform } from 'react-markdown'
import type { Options, UrlTransform } from 'react-markdown'
const markdownSanitizeSchema = {
...defaultSchema,
protocols: {
...defaultSchema.protocols,
src: [...(defaultSchema.protocols?.src ?? []), 'data'],
},
}
/**
* Rehype pipeline shared by every Markdown renderer. Raw HTML is parsed, then sanitized to
* GitHub's allow-list so scripts, frames and event handlers are stripped from model output and
* repository files, and highlighting runs last so its classes survive sanitization.
* repository files, and highlighting runs last so its classes survive sanitization. The schema
* additionally allows the `data` protocol on `src` so inline image data URIs survive sanitization.
*/
export const markdownRehypePlugins: NonNullable<Options['rehypePlugins']> = [rehypeRaw, rehypeSanitize, rehypeHighlight]
export const markdownRehypePlugins: NonNullable<Options['rehypePlugins']> = [
rehypeRaw,
[rehypeSanitize, markdownSanitizeSchema],
rehypeHighlight,
]
/**
* URL transform for Markdown renderers. Keeps `data:image/*` sources intact, which react-markdown's
* default transform strips, and defers every other URL to that default.
*/
export const markdownUrlTransform: UrlTransform = (url, key) => {
if (key === 'src' && /^data:image\//i.test(url)) {
return url
}
return defaultUrlTransform(url)
}
+1
View File
@@ -90,6 +90,7 @@ export const ALLOWED_MIME_TYPES = [
'image/png',
'image/jpeg',
'image/gif',
'image/webp',
'image/svg+xml',
'application/pdf',
'application/zip',