Commit 41c7a1b49 for llama.cpp
commit 41c7a1b49d1ec314305f0e50019faac3b2bcbec3
Author: Aleksander Grygier <aleksander.grygier@gmail.com>
Date: Wed Nov 25 14:13:26 2026 +0100
ui: fix tool result media shown twice, uncapped and dropped after its run (#33010)
* ui: drop images of old turns from the context, read_media loads them again
When read_media is offered and the model has vision, the images of user
turns far behind leave the request. A note stays in their place with an
"attachment:" path, and read_media resolves that path from the
attachments the browser holds, with no call to the server. Without the
tool, attachments are sent as before.
The cut moves once per 4 turns, so the server keeps its cache between
moves. The chat request, the pre-encode and the compaction summary read
the same list.
Images of a tool result now get the max resolution cap that attached
images get.
Assisted-by: Claude (Opus 5.5 Medium)
* ui: store the media of a tool result once
The tool result message was created with its extracted media, then
onAttachments appended the same extras to it again, so the trace showed
every read_media image twice. The callback had no other use and goes.
Assisted-by: Claude (Opus 5.5 Medium)
* ui: images of tool results follow the cut of old turns
A stored tool result now sends its media to the model as the run that
called the tool did, only what the model can read, through one helper,
so the image stays in later turns and the server's cache stays valid.
Before, it left the request once the run ended, with no note to load it
again.
The cut of old turns now covers tool results too, read_media's own
included: their images leave with a note and an "attachment:" path.
Media stored twice by the earlier bug is sent, noted and shown once.
Assisted-by: Claude (Opus 5.5 Medium)
* ui: keep attached images in the context
Takes back the cut of old turns: images of turns far behind stay in the
request, and read_media has no "attachment:" path. Each move of the cut
made the server process everything after the removed image again, which
costs far more than the tokens of the image it frees.
The fixes stay: the media of a tool result is stored once, its images
get the max resolution cap, and it goes along in later turns.
Assisted-by: Claude (Opus 5.5 Medium)
* ui: send the media of a stored tool result in agent requests
The agent request turned a tool message with content parts into an
empty string, so a stored tool result with media reached the model
with no text and no image on later turns.
Assisted-by: Claude (Opus 5.5 Medium)
diff --git a/ui/apps/chat/src/lib/services/chat.service.ts b/ui/apps/chat/src/lib/services/chat.service.ts
index 9d0a146cd..fccf270fa 100644
--- a/ui/apps/chat/src/lib/services/chat.service.ts
+++ b/ui/apps/chat/src/lib/services/chat.service.ts
@@ -6,8 +6,6 @@
* warming. No reactive state; consumed by chatStore and its managers.
*/
-import { getAudioInputFormat } from '../utils/audio-format';
-import { capImageDataURLSize } from '../utils/cap-img-size';
import { dropIncompleteToolCalls } from '../utils/incomplete-tool-calls';
import {
API_CHAT,
@@ -49,12 +47,19 @@ import { isAbortError } from '#lib/utils/abort.ts';
import { ApiError } from '#lib/utils/api-fetch.ts';
import { getAuthHeaders, getJsonHeaders } from '#lib/utils/api-headers.ts';
import { formatAttachmentText } from '#lib/utils/formatters.ts';
+import {
+ audioContentPart,
+ imageContentPart,
+ toolResultMediaParts
+} from '#lib/utils/media-content-parts.ts';
import { streamIdentity } from '#lib/utils/stream-identity.ts';
/** How stored messages are shaped for the model a request goes to. */
export interface ApiMessageConversionOptions {
/** False when the model has no audio input: voice messages go as their transcript. */
audioInput?: boolean;
+ /** False when the model has no vision: the images of tool results stay out. */
+ visionInput?: boolean;
}
interface ResumableStreamState {
@@ -141,13 +146,13 @@ export class ChatService {
}
/**
- * How messages are shaped for `model`: whether it takes audio, known only once its
- * modalities are. Unknown modalities keep the audio, as before voice messages.
+ * How messages are shaped for `model`: whether it takes audio and images, known only
+ * once its modalities are. Unknown modalities keep the audio, as before voice messages.
*/
static conversionOptionsFor(model?: string | null): ApiMessageConversionOptions {
const modalities = modelsStore.props.getModelModalities(model ?? '');
- return modalities ? { audioInput: modalities.audio } : {};
+ return modalities ? { audioInput: modalities.audio, visionInput: modalities.vision } : {};
}
/**
@@ -161,8 +166,17 @@ export class ChatService {
): Promise<ApiChatMessageData> {
// Handle tool result messages (role: 'tool')
if (message.role === MessageRole.TOOL && message.toolCallId) {
+ // the media goes along as in the run that called the tool, the model reads it the same way
+ const mediaParts = await toolResultMediaParts(
+ message.extra ?? [],
+ { audio: options.audioInput === true, vision: options.visionInput === true },
+ settingsStore.getConfig(SETTINGS_KEYS.MAX_IMAGE_RESOLUTION)
+ );
+
return {
- content: message.content,
+ content: mediaParts.length
+ ? [{ text: message.content, type: ContentPartType.TEXT }, ...mediaParts]
+ : message.content,
role: MessageRole.TOOL,
tool_call_id: message.toolCallId
};
@@ -232,15 +246,9 @@ export class ChatService {
);
for (const image of imageFiles) {
- const maxImageResolution = settingsStore.getConfig(SETTINGS_KEYS.MAX_IMAGE_RESOLUTION);
- // Caps the resolution and bakes the jpeg exif orientation in one pass,
- // untouched images pass through as is
- const base64Url = await capImageDataURLSize(image.base64Url, maxImageResolution);
-
- contentParts.push({
- image_url: { url: base64Url },
- type: ContentPartType.IMAGE_URL
- });
+ contentParts.push(
+ await imageContentPart(image, settingsStore.getConfig(SETTINGS_KEYS.MAX_IMAGE_RESOLUTION))
+ );
}
const audioFiles = message.extra.filter(
@@ -263,13 +271,7 @@ export class ChatService {
continue;
}
- contentParts.push({
- input_audio: {
- data: audio.base64Data,
- format: getAudioInputFormat(audio.mimeType)
- },
- type: ContentPartType.INPUT_AUDIO
- });
+ contentParts.push(audioContentPart(audio));
}
if (message.content) {
diff --git a/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts b/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts
index 61b40ac1a..78524ba33 100644
--- a/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts
+++ b/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts
@@ -11,7 +11,6 @@
*/
import {
- type ContentPart,
createHarness,
type InferenceClient,
type InferenceEvent,
@@ -21,7 +20,7 @@ import {
type ToolContext,
type ToolResult
} from '@ggml-org/llama-harness';
-import { DEFAULT_AGENTIC_CONFIG, NEWLINE } from '#lib/constants/index.ts';
+import { DEFAULT_AGENTIC_CONFIG, NEWLINE, SETTINGS_KEYS } from '#lib/constants/index.ts';
import {
AUDIO_MIME_TO_EXTENSION,
DATA_URI_BASE64_REGEX,
@@ -34,7 +33,6 @@ import {
import { BuiltInTool, ToolPermissionDecision, ToolSource } from '#lib/enums/index.ts';
import {
AttachmentType,
- ContentPartType,
HarnessEventType,
InferenceEventType,
MessageRole,
@@ -63,11 +61,7 @@ import type {
} from '#lib/types/agentic.js';
import type { ApiChatMessageData } from '#lib/types/api.js';
import type { ChatMessagePromptProgress, ChatMessageTimings } from '#lib/types/chat.js';
-import type {
- DatabaseMessageExtra,
- DatabaseMessageExtraAudioFile,
- DatabaseMessageExtraImageFile
-} from '#lib/types/database.js';
+import type { DatabaseMessageExtra } from '#lib/types/database.js';
import type {
AgenticConfig,
AgenticFlowParams,
@@ -82,10 +76,10 @@ import { createAsyncQueue } from '#lib/utils/async-queue.ts';
import {
executeBrowserInfoTool,
executeGetDatetimeTool,
- getAudioInputFormat,
isAbortError,
throwIfAborted
} from '#lib/utils/index.ts';
+import { toolResultMediaParts } from '#lib/utils/media-content-parts.ts';
import { SvelteMap } from 'svelte/reactivity';
function createDefaultSession(): AgenticSession {
@@ -136,7 +130,8 @@ function toAgenticMessages(messages: ApiChatMessageData[]): AgenticMessage[] {
if (message.role === MessageRole.TOOL && message.tool_call_id) {
return {
- content: typeof message.content === 'string' ? message.content : '',
+ // a stored tool result can hold media parts after its text
+ content: message.content,
role: MessageRole.TOOL,
tool_call_id: message.tool_call_id
} satisfies AgenticMessage;
@@ -432,45 +427,6 @@ class AgenticStore {
return `${MCP_ATTACHMENT_NAME_PREFIX}-${Date.now()}-${index}.${extension}`;
}
- /**
- * The media of a tool result as content parts, only what the model can read.
- */
- private buildContentParts(
- attachments: DatabaseMessageExtra[],
- effectiveModel: string
- ): ContentPart[] {
- const contentParts: ContentPart[] = [];
-
- for (const attachment of attachments) {
- if (attachment.type === AttachmentType.AUDIO) {
- if (modelsStore.props.modelSupportsAudio(effectiveModel)) {
- contentParts.push({
- input_audio: {
- data: (attachment as DatabaseMessageExtraAudioFile).base64Data,
- format: getAudioInputFormat((attachment as DatabaseMessageExtraAudioFile).mimeType)
- },
- type: ContentPartType.INPUT_AUDIO
- });
- }
- } else if (attachment.type === AttachmentType.IMAGE) {
- if (modelsStore.props.modelSupportsVision(effectiveModel)) {
- contentParts.push({
- image_url: {
- url: (attachment as DatabaseMessageExtraImageFile).base64Url
- },
- type: ContentPartType.IMAGE_URL
- });
- } else {
- console.info(
- `[AgenticStore] Skipping image attachment (model "${effectiveModel}" does not support vision)`
- );
- }
- }
- }
-
- return contentParts;
- }
-
/**
* Run a tool call where its source runs it: on llama-server, in the
* browser or on an MCP server. Throws when the call fails.
@@ -582,7 +538,6 @@ class AgenticStore {
createAssistantMessage,
createToolResultMessage,
onAssistantTurnComplete,
- onAttachments,
onChunk,
onCompletionId,
onFlowComplete,
@@ -745,23 +700,16 @@ class AgenticStore {
const extras = attachments.length > 0 ? attachments : undefined;
const streamed = streamedResults.get(event.toolCall.id);
- let toolResultMessageId: string | undefined;
-
if (streamed) {
- toolResultMessageId = streamed.messageId;
-
// the message already shows the streamed output: rewrite it only when the result differs
if (extras || content !== streamed.content) {
await updateToolResultMessage?.(streamed.messageId, content, extras);
}
} else if (createToolResultMessage) {
- toolResultMessageId = (
- await createToolResultMessage(event.toolCall.id, content, extras)
- ).id;
+ // the extras go in with the message: appending them again would show each image twice
+ await createToolResultMessage(event.toolCall.id, content, extras);
}
- if (extras && toolResultMessageId) onAttachments?.(toolResultMessageId, extras);
-
break;
}
@@ -850,7 +798,14 @@ class AgenticStore {
details: attachments,
durationMs,
isError: execution.isError,
- parts: this.buildContentParts(attachments, effectiveModel)
+ parts: await toolResultMediaParts(
+ attachments,
+ {
+ audio: modelsStore.props.modelSupportsAudio(effectiveModel),
+ vision: modelsStore.props.modelSupportsVision(effectiveModel)
+ },
+ settingsStore.getConfig(SETTINGS_KEYS.MAX_IMAGE_RESOLUTION)
+ )
};
}
diff --git a/ui/apps/chat/src/lib/stores/chat/index.svelte.ts b/ui/apps/chat/src/lib/stores/chat/index.svelte.ts
index d939077b2..0f30d75b9 100644
--- a/ui/apps/chat/src/lib/stores/chat/index.svelte.ts
+++ b/ui/apps/chat/src/lib/stores/chat/index.svelte.ts
@@ -1176,19 +1176,6 @@ class ChatStore implements ChatStreamHost, ChatFlowsHost {
await DatabaseService.updateCurrentNode(convId, currentMessageId);
}
},
- onAttachments: (messageId: string, extras: DatabaseMessageExtra[]) => {
- if (!extras.length) return;
-
- const idx = conversationsStore.findMessageIndex(messageId);
-
- if (idx === -1) return;
-
- const msg = conversationsStore.activeMessages[idx];
- const updatedExtras = [...(msg.extra || []), ...extras];
-
- conversationsStore.updateMessageAtIndex(idx, { extra: updatedExtras });
- DatabaseService.updateMessage(messageId, { extra: updatedExtras }).catch(console.error);
- },
onChunk: (chunk: string) => {
streamedContent += chunk;
updateStreamingUI();
diff --git a/ui/apps/chat/src/lib/types/agentic.d.ts b/ui/apps/chat/src/lib/types/agentic.d.ts
index faf4ce701..226bf2d39 100644
--- a/ui/apps/chat/src/lib/types/agentic.d.ts
+++ b/ui/apps/chat/src/lib/types/agentic.d.ts
@@ -122,8 +122,6 @@ export interface AgenticFlowCallbacks {
onReasoningChunk?: (chunk: string) => void;
/** Tool calls being streamed (partial, accumulating) for the current turn */
onToolCallsStreaming?: (toolCalls: ApiChatCompletionToolCall[]) => void;
- /** Attachments extracted from tool results */
- onAttachments?: (messageId: string, extras: DatabaseMessageExtra[]) => void;
/** Model name detected from response */
onModel?: (model: string) => void;
onCompletionId?: (id: string) => void;
diff --git a/ui/apps/chat/src/lib/types/chat.d.ts b/ui/apps/chat/src/lib/types/chat.d.ts
index 659edf101..604f6bba0 100644
--- a/ui/apps/chat/src/lib/types/chat.d.ts
+++ b/ui/apps/chat/src/lib/types/chat.d.ts
@@ -156,7 +156,6 @@ export interface ChatStreamCallbacks {
onChunk?: (chunk: string) => void;
onReasoningChunk?: (chunk: string) => void;
onToolCallsStreaming?: (toolCalls: ApiChatCompletionToolCall[]) => void;
- onAttachments?: (messageId: string, extras: DatabaseMessageExtra[]) => void;
onModel?: (model: string) => void;
onCompletionId?: (id: string) => void;
onTimings?: (timings?: ChatMessageTimings, promptProgress?: ChatMessagePromptProgress) => void;
diff --git a/ui/apps/chat/src/lib/utils/agentic.ts b/ui/apps/chat/src/lib/utils/agentic.ts
index 638d6aee8..a674e8c99 100644
--- a/ui/apps/chat/src/lib/utils/agentic.ts
+++ b/ui/apps/chat/src/lib/utils/agentic.ts
@@ -20,6 +20,7 @@ import type {
DatabaseMessageExtra,
DatabaseMessageExtraImageFile
} from '#lib/types/database.js';
+import { withoutRepeatedAttachments } from '#lib/utils/media-content-parts.ts';
/**
* Derives display sections from a single assistant message and its direct tool results.
@@ -85,7 +86,7 @@ function deriveSingleTurnSections(
toolCwd: resultMsg?.toolCwd,
toolName: tc.function?.name,
toolResult: resultMsg?.content,
- toolResultExtras: resultMsg?.extra,
+ toolResultExtras: resultMsg?.extra && withoutRepeatedAttachments(resultMsg.extra),
type
});
}
diff --git a/ui/apps/chat/src/lib/utils/media-content-parts.ts b/ui/apps/chat/src/lib/utils/media-content-parts.ts
new file mode 100644
index 000000000..f0598d06d
--- /dev/null
+++ b/ui/apps/chat/src/lib/utils/media-content-parts.ts
@@ -0,0 +1,101 @@
+import { getAudioInputFormat } from './audio-format';
+import { capImageDataURLSize } from './cap-img-size';
+import { AttachmentType, ContentPartType } from '#lib/enums/index.ts';
+import type { AudioInputFormat } from '#lib/types/api.js';
+import type {
+ DatabaseMessageExtra,
+ DatabaseMessageExtraAudioFile,
+ DatabaseMessageExtraImageFile
+} from '#lib/types/database.js';
+
+export interface ImageContentPart {
+ image_url: { url: string };
+ type: ContentPartType.IMAGE_URL;
+}
+
+export interface AudioContentPart {
+ input_audio: { data: string; format: AudioInputFormat };
+ type: ContentPartType.INPUT_AUDIO;
+}
+
+/**
+ * An image as the model receives it: capped to the max resolution, with the jpeg exif orientation baked in.
+ * User attachments and tool results both go through here, so they cost the same.
+ */
+export async function imageContentPart(
+ image: DatabaseMessageExtraImageFile,
+ maxMegapixels: number
+): Promise<ImageContentPart> {
+ return {
+ image_url: { url: await capImageDataURLSize(image.base64Url, maxMegapixels) },
+ type: ContentPartType.IMAGE_URL
+ };
+}
+
+export function audioContentPart(audio: DatabaseMessageExtraAudioFile): AudioContentPart {
+ return {
+ input_audio: { data: audio.base64Data, format: getAudioInputFormat(audio.mimeType) },
+ type: ContentPartType.INPUT_AUDIO
+ };
+}
+
+/** Modalities a model takes, for the media of a tool result. */
+export interface ToolMediaInput {
+ audio: boolean;
+ vision: boolean;
+}
+
+/** An attachment's identity: its name and its bytes. */
+function attachmentKey(extra: DatabaseMessageExtra): string {
+ if (extra.type === AttachmentType.IMAGE) return `${extra.name}\0${extra.base64Url}`;
+
+ if (extra.type === AttachmentType.AUDIO) return `${extra.name}\0${extra.base64Data}`;
+
+ return `${extra.type}\0${extra.name}`;
+}
+
+/**
+ * The attachments without the ones repeated with the same name and bytes. Tool results
+ * once stored their media twice; the copy adds nothing to the trace or the context.
+ */
+export function withoutRepeatedAttachments(extras: DatabaseMessageExtra[]): DatabaseMessageExtra[] {
+ const seen = new Set<string>();
+
+ return extras.filter((extra) => {
+ const key = attachmentKey(extra);
+
+ if (seen.has(key)) return false;
+
+ seen.add(key);
+
+ return true;
+ });
+}
+
+/**
+ * The media of a tool result as content parts, only what the model can read. The run that
+ * calls the tool and every later request build them here, so the server's cache stays valid.
+ */
+export async function toolResultMediaParts(
+ extras: DatabaseMessageExtra[],
+ input: ToolMediaInput,
+ maxMegapixels: number
+): Promise<(AudioContentPart | ImageContentPart)[]> {
+ const parts: (AudioContentPart | ImageContentPart)[] = [];
+
+ for (const extra of withoutRepeatedAttachments(extras)) {
+ if (extra.type === AttachmentType.AUDIO && input.audio) {
+ parts.push(audioContentPart(extra));
+ } else if (extra.type === AttachmentType.IMAGE && input.vision) {
+ parts.push(
+ // a tool can return a format the cap cannot draw: send it as it is
+ await imageContentPart(extra, maxMegapixels).catch(() => ({
+ image_url: { url: extra.base64Url },
+ type: ContentPartType.IMAGE_URL as const
+ }))
+ );
+ }
+ }
+
+ return parts;
+}
diff --git a/ui/apps/chat/tests/unit/agentic-flow.test.ts b/ui/apps/chat/tests/unit/agentic-flow.test.ts
index 1003f8fcb..d6b15863a 100644
--- a/ui/apps/chat/tests/unit/agentic-flow.test.ts
+++ b/ui/apps/chat/tests/unit/agentic-flow.test.ts
@@ -7,7 +7,20 @@ vi.mock('#lib/services/database.service.ts', () => ({
DatabaseService: {}
}));
-import { BuiltInTool, MessageRole, ToolPermissionDecision, ToolSource } from '#lib/enums/index.ts';
+// the cap draws on a canvas, which the unit tests do not have
+let capImage: (url: string) => Promise<string>;
+
+vi.mock('#lib/utils/cap-img-size.ts', () => ({
+ capImageDataURLSize: (url: string) => capImage(url)
+}));
+
+import {
+ BuiltInTool,
+ ContentPartType,
+ MessageRole,
+ ToolPermissionDecision,
+ ToolSource
+} from '#lib/enums/index.ts';
import { ChatService } from '#lib/services/chat.service.ts';
import { ToolsService } from '#lib/services/tools.service.ts';
import { agenticStore } from '#lib/stores/agentic/index.svelte.ts';
@@ -80,7 +93,6 @@ function recorder() {
onAssistantTurnComplete: async (...args) => {
calls.push(['onAssistantTurnComplete', ...args]);
},
- onAttachments: log('onAttachments'),
onChunk: log('onChunk'),
onError: log('onError'),
onFlowComplete: log('onFlowComplete'),
@@ -111,6 +123,7 @@ function runFlow(callbacks: AgenticFlowCallbacks, signal?: AbortSignal) {
beforeEach(() => {
vi.restoreAllMocks();
+ capImage = async (url) => url;
agenticStore.clearSession(CONV_ID);
vi.spyOn(console, 'log').mockImplementation(() => {});
vi.spyOn(ChatService, 'normalizeMessagesForApi').mockImplementation(
@@ -296,7 +309,6 @@ describe('agentic flow', () => {
expect(content).toMatch(/^saved\n\[Attachment saved: .+\.png\]$/);
expect(extras).toMatchObject([{ base64Url: IMAGE_DATA_URI, type: 'IMAGE' }]);
- expect(named('onAttachments')[0].slice(1)).toEqual(['msg_0', extras]);
expect(requests[1][2]).toEqual({
content: [
{ text: content, type: 'text' },
@@ -307,6 +319,71 @@ describe('agentic flow', () => {
});
});
+ it('caps the image of a tool result for the model and stores it as it came', async () => {
+ const capped = 'data:image/png;base64,BBBB';
+
+ capImage = async () => capped;
+ mockTools(ToolSource.SERVER, 'screenshot');
+ vi.spyOn(ToolsService, 'executeTool').mockResolvedValue({
+ content: IMAGE_DATA_URI,
+ isError: false
+ });
+ vi.spyOn(modelsStore.props, 'modelSupportsVision').mockReturnValue(true);
+
+ const requests = mockTurns(
+ (options) => options.onToolCallChunk?.(toolCalls('screenshot')),
+ (options) => options.onChunk?.('here')
+ );
+ const { callbacks, named } = recorder();
+
+ await runFlow(callbacks);
+
+ expect(named('createToolResultMessage')[0][3]).toMatchObject([{ base64Url: IMAGE_DATA_URI }]);
+ expect(requests[1][2].content).toMatchObject([{}, { image_url: { url: capped } }]);
+ });
+
+ it('sends the image of a tool result as it is when the cap fails', async () => {
+ capImage = async () => {
+ throw new Error('Unsupported image MIME type');
+ };
+ mockTools(ToolSource.SERVER, 'screenshot');
+ vi.spyOn(ToolsService, 'executeTool').mockResolvedValue({
+ content: IMAGE_DATA_URI,
+ isError: false
+ });
+ vi.spyOn(modelsStore.props, 'modelSupportsVision').mockReturnValue(true);
+
+ const requests = mockTurns(
+ (options) => options.onToolCallChunk?.(toolCalls('screenshot')),
+ (options) => options.onChunk?.('here')
+ );
+
+ await runFlow(recorder().callbacks);
+
+ expect(requests[1][2].content).toMatchObject([{}, { image_url: { url: IMAGE_DATA_URI } }]);
+ });
+
+ it('sends the media of an earlier tool result along in a later request', async () => {
+ const earlier: ApiChatMessageData[] = [
+ ...USER_MESSAGES,
+ { content: '', role: MessageRole.ASSISTANT, tool_calls: JSON.parse(toolCalls('screenshot')) },
+ {
+ content: [
+ { text: 'saved', type: ContentPartType.TEXT },
+ { image_url: { url: IMAGE_DATA_URI }, type: ContentPartType.IMAGE_URL }
+ ],
+ role: MessageRole.TOOL,
+ tool_call_id: 'call_0'
+ }
+ ];
+
+ mockTools(ToolSource.SERVER, 'screenshot');
+
+ const request = await agenticStore.requestFor(earlier);
+
+ expect(request.messages[2]).toEqual(earlier[2]);
+ });
+
it('leaves the flow when a steering message is queued, skipping the tool calls left', async () => {
mockTools(ToolSource.SERVER, 'first', 'second');
vi.spyOn(ToolsService, 'executeTool').mockImplementation(async () => {
diff --git a/ui/apps/chat/tests/unit/tool-result-media.test.ts b/ui/apps/chat/tests/unit/tool-result-media.test.ts
new file mode 100644
index 000000000..f0cc340e2
--- /dev/null
+++ b/ui/apps/chat/tests/unit/tool-result-media.test.ts
@@ -0,0 +1,75 @@
+// Guards the media of a stored tool result: later requests send it as the run that
+// called the tool did, so the model keeps seeing it and the server keeps its cache.
+
+import { AttachmentType, ContentPartType, MessageRole, MessageType } from '#lib/enums/index.ts';
+import { ChatService } from '#lib/services/chat.service.ts';
+import type { DatabaseMessage, DatabaseMessageExtra } from '#lib/types/index.ts';
+import { withoutRepeatedAttachments } from '#lib/utils/media-content-parts.ts';
+import { describe, expect, it } from 'vitest';
+
+const IMAGE_URL = 'data:image/png;base64,AAAA';
+const shot: DatabaseMessageExtra = {
+ base64Url: IMAGE_URL,
+ name: 'mcp-attachment-1-0.png',
+ type: AttachmentType.IMAGE
+};
+
+function toolResult(extra: DatabaseMessageExtra[]): DatabaseMessage {
+ return {
+ children: [],
+ content: 'File: /tmp/shot.png',
+ convId: 'c1',
+ extra,
+ id: 'm1',
+ parent: null,
+ role: MessageRole.TOOL,
+ timestamp: 0,
+ toolCallId: 'call_0',
+ type: MessageType.TEXT
+ } as DatabaseMessage;
+}
+
+describe('a stored tool result with an image', () => {
+ it('sends the text and the image to a model with vision', async () => {
+ const result = await ChatService.convertDbMessageToApiChatMessageData(toolResult([shot]), {
+ visionInput: true
+ });
+
+ expect(result).toMatchObject({
+ content: [
+ { text: 'File: /tmp/shot.png', type: ContentPartType.TEXT },
+ { type: ContentPartType.IMAGE_URL }
+ ],
+ role: MessageRole.TOOL,
+ tool_call_id: 'call_0'
+ });
+ });
+
+ it('sends the text alone to a model without vision or with unknown modalities', async () => {
+ for (const options of [{ visionInput: false }, {}]) {
+ const result = await ChatService.convertDbMessageToApiChatMessageData(
+ toolResult([shot]),
+ options
+ );
+
+ expect(result.content).toBe('File: /tmp/shot.png');
+ }
+ });
+
+ it('sends a repeated copy of the image once', async () => {
+ const result = await ChatService.convertDbMessageToApiChatMessageData(
+ toolResult([shot, { ...shot }]),
+ { visionInput: true }
+ );
+
+ expect(result.content).toHaveLength(2);
+ });
+});
+
+describe('withoutRepeatedAttachments', () => {
+ it('keeps attachments that share a name but not the bytes', () => {
+ const other = { ...shot, base64Url: 'data:image/png;base64,BBBB' };
+
+ expect(withoutRepeatedAttachments([shot, { ...shot }, other])).toEqual([shot, other]);
+ });
+});
diff --git a/ui/apps/chat/tests/unit/voice-message-send.test.ts b/ui/apps/chat/tests/unit/voice-message-send.test.ts
index 36858e504..c83951313 100644
--- a/ui/apps/chat/tests/unit/voice-message-send.test.ts
+++ b/ui/apps/chat/tests/unit/voice-message-send.test.ts
@@ -89,7 +89,10 @@ describe('sending a voice message', () => {
vision: true
});
- expect(ChatService.conversionOptionsFor('text-model')).toEqual({ audioInput: false });
+ expect(ChatService.conversionOptionsFor('text-model')).toEqual({
+ audioInput: false,
+ visionInput: true
+ });
});
});