Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(chat): send MCP image results to Anthropic, Gemini and OpenAI Responses as images
thinhlpg134116fa0f87
diff --git a/web-app/src/lib/__tests__/custom-chat-transport-abort-load.test.ts b/web-app/src/lib/__tests__/custom-chat-transport-abort-load.test.tsindex fcbcbb51d..d3ddb10d4 100644--- a/web-app/src/lib/__tests__/custom-chat-transport-abort-load.test.ts+++ b/web-app/src/lib/__tests__/custom-chat-transport-abort-load.test.ts@@ -1,5 +1,6 @@import { describe, expect, it, vi, beforeEach } from 'vitest'import type { UIMessage } from '@ai-sdk/react'+import type * as ProviderCaps from '@/lib/providerCaps'// Regression test for https://github.com/janhq/jan/issues/8432 (Stop-during-load):// aborting a request while ModelFactory.createModel() is still awaiting@@ -89,7 +90,8 @@ vi.mock('@/lib/mcp-router-model-filter', () => ({vi.mock('@/lib/reasoningProviderOptions', () => ({buildReasoningProviderOptions: () => undefined,}))-vi.mock('@/lib/providerCaps', () => ({+vi.mock('@/lib/providerCaps', async (importOriginal) => ({+ ...(await importOriginal<typeof ProviderCaps>()),isPredefinedRemoteProvider: () => false,getProviderApiType: () => 'openai',}))diff --git a/web-app/src/lib/__tests__/custom-chat-transport-prefix-stability.test.ts b/web-app/src/lib/__tests__/custom-chat-transport-prefix-stability.test.tsindex 0c01c9af4..f26984fc3 100644--- a/web-app/src/lib/__tests__/custom-chat-transport-prefix-stability.test.ts+++ b/web-app/src/lib/__tests__/custom-chat-transport-prefix-stability.test.ts@@ -1,5 +1,6 @@import { describe, expect, it, vi, beforeEach } from 'vitest'import type { UIMessage } from '@ai-sdk/react'+import type * as ProviderCaps from '@/lib/providerCaps'// Capture every streamText({...}) call so we can compare the prompt prefix// (system + tools + prior model messages) across consecutive turns.@@ -122,7 +123,8 @@ vi.mock('@/lib/mcp-router-model-filter', () => ({vi.mock('@/lib/reasoningProviderOptions', () => ({buildReasoningProviderOptions: () => undefined,}))-vi.mock('@/lib/providerCaps', () => ({+vi.mock('@/lib/providerCaps', async (importOriginal) => ({+ ...(await importOriginal<typeof ProviderCaps>()),isPredefinedRemoteProvider: () => false,getProviderApiType: () => 'openai',}))@@ -400,33 +402,55 @@ it('keeps a Cowork run on its chosen model when the viewed model changes between// The filesystem server's `read_media_file` result, stored as its MCP content// array. Sent as-is, the SDK stringifies it and the model gets the base64 as-// text; the transport must turn it into a tool image sentinel first.-it('sends an MCP image result as a tool image, not as base64 text', async () => {+// text; the transport must turn it into a tool image first.+const mcpImageTurn = (): UIMessage[] => [+ user('u1', 'look at the frame'),+ {+ id: 'a1',+ role: 'assistant',+ parts: [+ {+ type: 'tool-read_media_file',+ toolCallId: 'c1',+ state: 'output-available',+ input: { path: '/frames/a.png' },+ output: [{ type: 'image', data: 'iVBORw0KGgo=', mimeType: 'image/png' }],+ },+ ],+ } as unknown as UIMessage,+]++// OpenAI-compatible providers get a sentinel, which the request fetch decodes+// into an `image_url` part on the `role: tool` message.+it('sends an MCP image result to an OpenAI-compatible provider as a sentinel', async () => {streamTextCalls.length = 0- provider.provider = 'openai'- h.providerId = 'openai'+ provider.provider = 'groq'+ h.providerId = 'groq'selectedModel.id = 'gpt'selectedModel.capabilities = ['tools', 'vision']const transport = new CustomChatTransport('you are jan', 'thread-1')- await drain(- await send(transport, [- user('u1', 'look at the frame'),- {- id: 'a1',- role: 'assistant',- parts: [- {- type: 'tool-read_media_file',- toolCallId: 'c1',- state: 'output-available',- input: { path: '/frames/a.png' },- output: [{ type: 'image', data: 'iVBORw0KGgo=', mimeType: 'image/png' }],- },- ],- } as unknown as UIMessage,- ])- )+ await drain(await send(transport, mcpImageTurn()))const sent = JSON.stringify(streamTextCalls[0].messages)expect(sent).toContain('__JAN_TOOL_IMAGE__data:image/png;base64,iVBORw0KGgo=')expect(sent).not.toContain('mimeType')})++// Anthropic, Gemini and OpenAI Responses build their own request, so the+// image must reach the SDK as structured tool output.+it.each(['anthropic', 'google', 'openai'])(+ 'sends an MCP image result to %s as an image-data tool output',+ async (name) => {+ streamTextCalls.length = 0+ provider.provider = name+ h.providerId = name+ selectedModel.id = 'gpt'+ selectedModel.capabilities = ['tools', 'vision']+ const transport = new CustomChatTransport('you are jan', 'thread-1')+ await drain(await send(transport, mcpImageTurn()))+ const sent = JSON.stringify(streamTextCalls[0].messages)+ expect(sent).toContain(+ '"type":"image-data","mediaType":"image/png","data":"iVBORw0KGgo="'+ )+ expect(sent).not.toContain('__JAN_TOOL_IMAGE__')+ }+)diff --git a/web-app/src/lib/__tests__/tool-image-sentinel.test.ts b/web-app/src/lib/__tests__/tool-image-sentinel.test.tsindex 68afa9ebb..0b0b40098 100644--- a/web-app/src/lib/__tests__/tool-image-sentinel.test.ts+++ b/web-app/src/lib/__tests__/tool-image-sentinel.test.ts@@ -1,11 +1,13 @@import { describe, it, expect } from 'vitest'import type { UIMessage } from '@ai-sdk/react'+import type { ModelMessage } from 'ai'import {encodeMcpToolImages,encodeToolImageSentinel,hasToolImageSentinel,splitToolImageSentinels,stripToolImageSentinels,+ toContentToolOutputs,} from '../tool-image-sentinel'import { decodeToolImageSentinelsInBody } from '../model-factory'import { stripUnsupportedImageParts } from '../custom-chat-transport'@@ -163,3 +165,42 @@ describe('encodeMcpToolImages', () => {)})})++describe('toContentToolOutputs', () => {+ const toolMessage = (output: unknown): ModelMessage =>+ ({+ role: 'tool',+ content: [+ { type: 'tool-result', toolCallId: 'c1', toolName: 'read_media_file', output },+ ],+ }) as ModelMessage++ // Anthropic, Gemini and OpenAI Responses build their own request shape, so+ // the sentinel cannot be decoded in the fetch: the SDK has to be handed the+ // image as structured `content`, which each provider maps to its own format.+ it('turns a sentinel tool output into text plus an image-data part', () => {+ const [out] = toContentToolOutputs([+ toolMessage({+ type: 'text',+ value: `Rendered frame${encodeToolImageSentinel(png)}`,+ }),+ ])+ expect(out).toEqual(+ toolMessage({+ type: 'content',+ value: [+ { type: 'text', text: 'Rendered frame' },+ { type: 'image-data', data: 'iVBORw0KGgo=', mediaType: 'image/png' },+ ],+ })+ )+ })++ it('leaves plain tool outputs and other roles untouched', () => {+ const plain = toolMessage({ type: 'text', value: 'file contents' })+ const user = { role: 'user', content: 'hi' } as ModelMessage+ const [a, b] = toContentToolOutputs([plain, user])+ expect(a).toBe(plain)+ expect(b).toBe(user)+ })+})diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.tsindex 6aaa1a4a2..1545f8e4e 100644--- a/web-app/src/lib/custom-chat-transport.ts+++ b/web-app/src/lib/custom-chat-transport.ts@@ -16,10 +16,12 @@ import {encodeMcpToolImages,hasToolImageSentinel,stripToolImageSentinels,+ toContentToolOutputs,} from './tool-image-sentinel'import { useServiceStore } from '@/hooks/useServiceHub'import { useToolAvailable } from '@/hooks/useToolAvailable'import { ModelFactory } from './model-factory'+import { buildsOwnToolImageRequest } from './providerCaps'import { useModelProvider } from '@/hooks/useModelProvider'import { useAssistant } from '@/hooks/useAssistant'import { useThreads } from '@/hooks/useThreads'@@ -1527,7 +1529,7 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {const modelSupportsVision =selectedModel?.capabilities?.includes('vision') ?? false- const baseMessages = await convertToModelMessages(+ const convertedMessages = await convertToModelMessages(coalesceMessagesForAlternation(resolveOrphanToolCalls(this.encodeVideoAttachments(@@ -1543,6 +1545,11 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {)))+ // Anthropic, Gemini and OpenAI Responses build their own request, so a tool+ // image sentinel would reach them as text; the others decode it in the fetch.+ const baseMessages = buildsOwnToolImageRequest(provider)+ ? toContentToolOutputs(convertedMessages)+ : convertedMessages// If continuing a truncated response, append the partial assistant content as a// prefill so the model resumes from where it left off rather than regenerating.diff --git a/web-app/src/lib/providerCaps.ts b/web-app/src/lib/providerCaps.tsindex 8c55f0f80..1b056ec9d 100644--- a/web-app/src/lib/providerCaps.ts+++ b/web-app/src/lib/providerCaps.ts@@ -182,6 +182,21 @@ export function getProviderApiType(return provider.provider === 'anthropic' ? 'anthropic' : 'openai'}+/**+ * True when the provider's AI SDK builds its own request shape (Anthropic,+ * Gemini, OpenAI Responses), so the request fetch cannot decode a tool image+ * sentinel and the SDK must be handed the image as structured tool output.+ * Mirrors the dispatch in `ModelFactory.createModel`.+ */+export function buildsOwnToolImageRequest(+ provider: Pick<ProviderObject, 'provider' | 'api_type'>+): boolean {+ if (getProviderApiType(provider) === 'anthropic') return true+ return ['anthropic', 'openai', 'google', 'gemini'].includes(+ provider.provider.toLowerCase()+ )+}+const LOCAL_PROVIDER_IDS = new Set<string>(['llamacpp', 'mlx'])/**diff --git a/web-app/src/lib/tool-image-sentinel.ts b/web-app/src/lib/tool-image-sentinel.tsindex c763d6d9b..01bb1b46c 100644--- a/web-app/src/lib/tool-image-sentinel.ts+++ b/web-app/src/lib/tool-image-sentinel.ts@@ -7,6 +7,7 @@// decodes it back into content parts.import type { UIMessage } from '@ai-sdk/react'+import type { ModelMessage } from 'ai'const PREFIX = ' __JAN_TOOL_IMAGE__'const SUFFIX = ' '@@ -14,6 +15,12 @@ const SUFFIX = ' 'const SENTINEL_REGEX =/ __JAN_TOOL_IMAGE__(data:image\/[a-z0-9.+-]+;base64,[A-Za-z0-9+/=]+) /g+const DATA_URL_REGEX = /^data:(image\/[a-z0-9.+-]+);base64,(.+)$/++type ToolResultContentItem =+ | { type: 'text'; text: string }+ | { type: 'image-data'; mediaType: string; data: string }+export function encodeToolImageSentinel(dataUrl: string): string {return `${PREFIX}${dataUrl}${SUFFIX}`}@@ -145,3 +152,38 @@ export function encodeMcpToolImages(messages: UIMessage[]): UIMessage[] {return touched ? ({ ...message, parts } as UIMessage) : message})}++/**+ * For providers whose SDK builds its own request shape (Anthropic, Gemini,+ * OpenAI Responses), where the request fetch cannot decode a sentinel: hands+ * the SDK each tool image as a structured `content` output, which it maps to+ * the provider's native image block. Run on model messages, after+ * `convertToModelMessages` has stringified the UI tool output.+ */+export function toContentToolOutputs(messages: ModelMessage[]): ModelMessage[] {+ return messages.map((message) => {+ if (message.role !== 'tool') return message+ let touched = false+ const content = message.content.map((part) => {+ if (+ part.type !== 'tool-result' ||+ part.output.type !== 'text' ||+ !hasToolImageSentinel(part.output.value)+ ) {+ return part+ }+ const value = (splitToolImageSentinels(part.output.value) ?? []).flatMap(+ (item): ToolResultContentItem[] => {+ if (item.type === 'text') return [item]+ const match = DATA_URL_REGEX.exec(item.image_url.url)+ return match+ ? [{ type: 'image-data', mediaType: match[1], data: match[2] }]+ : []+ }+ )+ touched = true+ return { ...part, output: { type: 'content', value } } as typeof part+ })+ return touched ? { ...message, content } : message+ })+}