Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(chat): show an MCP image result in the tool card without opening Raw (#9547) (#9562)
Thinh Leba21a49ad7d6
diff --git a/web-app/src/components/ai-elements/__tests__/tool.test.tsx b/web-app/src/components/ai-elements/__tests__/tool.test.tsxindex e4e431977..b5e664d85 100644--- a/web-app/src/components/ai-elements/__tests__/tool.test.tsx+++ b/web-app/src/components/ai-elements/__tests__/tool.test.tsx@@ -40,8 +40,6 @@ import {} from '../tool'import { useToolCallRuntime } from '@/hooks/useToolCallRuntime'-const resolver = (input: string) => Promise.resolve(input)-// The approval mock is module state; leaving a pending entry behind would make// every later header render as awaiting approval.beforeEach(() => {@@ -240,7 +238,6 @@ const renderOutput = (<ToolOutputoutput="short result"errorText={undefined}- resolver={resolver}{...props}/></ToolContent>@@ -317,11 +314,118 @@ describe('ToolOutput', () => {<ToolOutputoutput={undefined}errorText={undefined}- resolver={resolver}/></ToolContent></Tool>)expect(container).not.toHaveTextContent('tools:toolCall.result')})++ // #9547: an MCP image result must be visible in the card without opening the+ // raw payload. The summary used to hide the whole output, images included.+ describe('MCP image results', () => {+ const png = 'iVBORw0KGgo='++ it('shows an image from a bare content array without "View raw"', () => {+ const { container } = renderOutput({+ output: [{ type: 'image', data: png, mimeType: 'image/png' }],+ })+ const img = container.querySelector('img')+ expect(img).not.toBeNull()+ expect(img).toHaveAttribute('src', `data:image/png;base64,${png}`)+ })++ it('shows an image from a { content } envelope without "View raw"', () => {+ const { container } = renderOutput({+ output: {+ content: [{ type: 'image', data: png, mimeType: 'image/png' }],+ },+ })+ expect(container.querySelectorAll('img')).toHaveLength(1)+ })++ it('keeps the caption summary next to the image', () => {+ const { container } = renderOutput({+ output: [+ { type: 'text', text: 'rendered' },+ { type: 'image', data: png, mimeType: 'image/png' },+ ],+ })+ expect(container.querySelectorAll('img')).toHaveLength(1)+ expect(screen.getByText('tools:toolCall.summaryItems')).toBeInTheDocument()+ })++ it('uses the declared media type, not always png', () => {+ const { container } = renderOutput({+ output: [{ type: 'image', data: png, mimeType: 'image/jpeg' }],+ })+ expect(container.querySelector('img')).toHaveAttribute(+ 'src',+ `data:image/jpeg;base64,${png}`+ )+ })++ it('does not draw the image twice when the raw payload is opened', () => {+ const { container } = renderOutput({+ output: [+ { type: 'text', text: 'rendered' },+ { type: 'image', data: png, mimeType: 'image/png' },+ ],+ })+ fireEvent.click(screen.getByText('tools:toolCall.viewRaw'))+ expect(container.querySelectorAll('img')).toHaveLength(1)+ expect(screen.getByTestId('code-block').textContent).toContain('rendered')+ expect(screen.getByTestId('code-block').textContent).not.toContain(png)+ })++ it('renders every image of a multi-image result', () => {+ const { container } = renderOutput({+ output: [+ { type: 'image', data: png, mimeType: 'image/png' },+ { type: 'image', data: png, mimeType: 'image/png' },+ ],+ })+ expect(container.querySelectorAll('img')).toHaveLength(2)+ })++ it('does not render an image block for a result with none', () => {+ const { container } = renderOutput({+ output: { content: [{ type: 'text', text: 'plain' }] },+ })+ expect(container.querySelectorAll('img')).toHaveLength(0)+ })++ it('does not fetch a remote URL a tool points an image block at', () => {+ const { container } = renderOutput({+ output: [+ { type: 'image', data: 'https://tracker.example/pixel.png' },+ { type: 'image', image: { url: 'http://tracker.example/b.png' } },+ ],+ })+ expect(container.querySelectorAll('img')).toHaveLength(0)+ })++ it('falls back to png when the declared media type is not an image type', () => {+ const { container } = renderOutput({+ output: [{ type: 'image', data: png, mimeType: 'text/html' }],+ })+ expect(container.querySelector('img')).toHaveAttribute(+ 'src',+ `data:image/png;base64,${png}`+ )+ })++ // The raw view elides the base64, so a large image alone must not make a+ // short caption look long enough to need "Show more".+ it('does not offer "Show more" because an image is large', () => {+ renderOutput({+ output: [+ { type: 'text', text: 'caption' },+ { type: 'image', data: 'A'.repeat(5000), mimeType: 'image/png' },+ ],+ })+ fireEvent.click(screen.getByText('tools:toolCall.viewRaw'))+ expect(screen.queryByText('tools:toolCall.showMore')).not.toBeInTheDocument()+ })+ })})diff --git a/web-app/src/components/ai-elements/tool.tsx b/web-app/src/components/ai-elements/tool.tsxindex 1b898fae6..5c4ca226b 100644--- a/web-app/src/components/ai-elements/tool.tsx+++ b/web-app/src/components/ai-elements/tool.tsx@@ -397,57 +397,82 @@ export const ToolApprovalActions = memo(() => {)})-type ToolImageProps = {- data: string- index: number- resolver: (input: string) => Promise<string>+type ContentBlock = {+ type?: string+ text?: string+ data?: string+ mimeType?: string+ image?: { url?: string }}-const ToolImage = memo(({ data, index }: ToolImageProps) => {- // Prepare the URL - convert base64 to data URL if needed- const [preparedUrl, setPreparedUrl] = useState<string | undefined>(undefined)-- useEffect(() => {- if (data.startsWith('data:image') || data.startsWith('http')) {- // Already a data URL or HTTP URL- setPreparedUrl(data)- } else {- // Assume it's base64 encoded- setPreparedUrl(`data:image/png;base64,${data}`)- }- }, [data])-- const isLoading = !preparedUrl+type ToolImageSource = { data: string; mimeType?: string }++const REMOTE_URL = /^https?:/i++/**+ * The image blocks of an MCP result, stored bare or as `{ content }`. Only+ * inline data is drawn: a block that points at a URL is not fetched just+ * because a tool returned it.+ */+function toolImages(output: unknown): ToolImageSource[] {+ const items: ContentBlock[] = Array.isArray(output)+ ? output+ : isPlainObject(output) && Array.isArray(output.content)+ ? output.content+ : []+ return items.flatMap((item) => {+ if (item?.type !== 'image') return []+ const data = item.data || item.image?.url+ return data && !REMOTE_URL.test(data)+ ? [{ data, mimeType: item.mimeType }]+ : []+ })+}- if (isLoading) {- return (- <div className="flex justify-center">- <div className="flex size-24 items-center justify-center rounded-md bg-muted">- <div className="size-4 animate-spin rounded-full border-2 border-primary border-t-transparent" />- </div>- </div>- )- }+/** The raw view of image blocks: what came back, without the inline data. */+function redactImages(items: ContentBlock[]): ContentBlock[] {+ const elide = (value: string) => `<${value.length} characters elided>`+ const inline = (value?: string): value is string =>+ !!value && !REMOTE_URL.test(value)+ return items.map((item) => {+ if (item?.type !== 'image') return item+ return {+ ...item,+ ...(inline(item.data) ? { data: elide(item.data) } : {}),+ ...(inline(item.image?.url)+ ? { image: { ...item.image, url: elide(item.image.url) } }+ : {}),+ }+ })+}- if (!preparedUrl) {- return null- }+/**+ * `src` for an inline image: a data URL as given, otherwise bare base64 with+ * the media type the server declared (png when it declared none, or something+ * that is not an image type).+ */+function toolImageSrc(data: string, mimeType?: string): string {+ const value = data.replace(/\s+/g, '')+ if (/^data:image\//i.test(value)) return value+ const mime = mimeType?.toLowerCase().startsWith('image/')+ ? mimeType.toLowerCase()+ : 'image/png'+ return `data:${mime};base64,${value}`+}- return (- <div key={index} className="inline-block">- <img- src={preparedUrl}- alt="Tool output"- className="max-w-full max-h-96 w-auto h-auto object-contain rounded-md border"- />- </div>- )-})+const ToolImage = memo(({ data, mimeType }: ToolImageSource) => (+ <div className="inline-block">+ <img+ src={toolImageSrc(data, mimeType)}+ alt="Tool output"+ className="max-w-full max-h-96 w-auto h-auto object-contain rounded-md border"+ />+ </div>+))export type ToolOutputProps = ComponentProps<'div'> & {output: ToolUIPart['output']errorText: ToolUIPart['errorText']- resolver: (input: string) => Promise<string>// Running count of citations from earlier tool calls in this turn, so each// card's numbering/anchors continue the global sequence the markers use.citationOffset?: number@@ -458,7 +483,6 @@ export const ToolOutput = memo(className,output,errorText,- resolver,citationOffset = 0,...props}: ToolOutputProps) => {@@ -478,6 +502,10 @@ export const ToolOutput = memo([citationPayload, errorText, output])+ // MCP image blocks are the result itself, not an attachment to it: they show+ // in the card without opening the raw payload (#9547).+ const images = useMemo(() => toolImages(output), [output])+const copyText = useMemo(() => (errorText ? errorText : stringifyToolInput(output)),[errorText, output]@@ -485,8 +513,12 @@ export const ToolOutput = memo(// Only offer expansion for payloads long enough to be clipped. Citation// output (native web search, RAG) renders as cards outside the scroll box,// so there is no height for the control to act on.+ // The raw view elides image data, so image bytes are not what makes a+ // payload long enough to need the expand control.+ const imageChars = images.reduce((n, image) => n + image.data.length, 0)const isLong =- !citationPayload && copyText.length > OUTPUT_EXPAND_THRESHOLD+ !citationPayload &&+ copyText.length - imageChars > OUTPUT_EXPAND_THRESHOLDconst boxClassName = cn('rounded-md overflow-auto border',expanded ? 'max-h-[32rem]' : 'max-h-40'@@ -517,93 +549,45 @@ export const ToolOutput = memo(}if (typeof output === 'object' && !isValidElement(output)) {- // Check if output has content array (new structure: {content: [{text, type}, {data, type: image}]})+ // MCP content envelope: { content: [{ text, type }, { data, type: image }] }.+ // The images are drawn by the card itself (see `images`), so the raw+ // view carries the text blocks, or the blocks with the base64 elided.if (output &&typeof output === 'object' &&'content' in output &&Array.isArray(output.content)) {- const content = output.content as Array<{- type: string- text?: string- data?: string- mimeType?: string- }>-+ const content = output.content as ContentBlock[]const textItems = content.filter((item) => item.type === 'text')- const imageItems = content.filter((item) => item.type === 'image')-- return (- <div className="space-y-4">- {textItems.length > 0 && (- <div className="space-y-2">- {textItems.map((item, index) => (- <div key={index} className={boxClassName}>- <CodeBlock code={item.text || ''} language="markdown" />- </div>- ))}- </div>- )}- {imageItems.length > 0 && (- <div className="space-y-2">- {imageItems.map((item, index) => (- <ToolImage- key={index}- data={item.data || ''}- index={index}- resolver={resolver}- />- ))}- </div>- )}- </div>- )- }-- // Handle old array format for backward compatibility- if (Array.isArray(output)) {- const hasImages = output.some(- (item) => item?.type === 'image' && (item?.data || item?.image)- )-- if (hasImages) {- // Filter out images from JSON and render images separately- const nonImageOutput = output.filter(- (item) => item?.type !== 'image'- )+ if (textItems.length > 0) {return (- <div className="space-y-4">- {nonImageOutput.length > 0 && (- <div className={boxClassName}>- <CodeBlock- code={JSON.stringify(nonImageOutput, null, 2)}- language="json"- />+ <div className="space-y-2">+ {textItems.map((item, index) => (+ <div key={index} className={boxClassName}>+ <CodeBlock code={item.text || ''} language="markdown" /></div>- )}- {output- .filter(- (item) =>- item?.type === 'image' && (item?.data || item?.image?.url)- )- .map((item, index) => (- <ToolImage- key={index}- data={item.data ?? item.image?.url}- index={index}- resolver={resolver}- />- ))}+ ))}</div>)}+ return (+ <div className={boxClassName}>+ <CodeBlock+ code={JSON.stringify(redactImages(content), null, 2)}+ language="json"+ />+ </div>+ )+ }+ // Bare content array, which is how a stored MCP result looks.+ if (Array.isArray(output)) {return (<div className={boxClassName}><CodeBlock- code={JSON.stringify(output, null, 2)}+ code={JSON.stringify(redactImages(output), null, 2)}language="json"/></div>@@ -622,7 +606,6 @@ export const ToolOutput = memo(}, [output,errorText,- resolver,citationPayload,messageId,citationOffset,@@ -678,6 +661,17 @@ export const ToolOutput = memo({errorText}</div>)}+ {images.length > 0 && (+ <div className="space-y-2">+ {images.map((image, index) => (+ <ToolImage+ key={index}+ data={image.data}+ mimeType={image.mimeType}+ />+ ))}+ </div>+ )}{(!summary || showRaw) && Output}</div></div>diff --git a/web-app/src/containers/message/ToolCallCard.tsx b/web-app/src/containers/message/ToolCallCard.tsxindex 6c0d3127d..4a5f56a00 100644--- a/web-app/src/containers/message/ToolCallCard.tsx+++ b/web-app/src/containers/message/ToolCallCard.tsx@@ -18,8 +18,6 @@ import { WebToolWidget } from './WebToolWidget'import { AgentToolWidget, TerminalWidget } from './AgentToolWidget'import { SubagentToolWidget } from './SubagentToolWidget'-const identityResolver = (input: string) => Promise.resolve(input)-export type ToolCallCardProps = {part: MessagePartLikemessageId: string@@ -145,14 +143,12 @@ export const ToolCallCard = memo(<ToolOutputoutput={undefined}errorText={errorText}- resolver={identityResolver}/>) : (Boolean(part.output) && (<ToolOutputoutput={part.output}errorText={undefined}- resolver={identityResolver}citationOffset={citationOffset}/>)