Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix: support media refs for tool result images (#18743)

YuTengjing774e04c44b77
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
index 5c2aa7b0947..d20a2fee1fb 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
@@ -5255,11 +5255,13 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
expect(result.newState.messages).toHaveLength(2);
expect(result.newState.messages[0]).toEqual({
content: 'Tool execution was aborted by user.',
+ id: 'msg-123',
role: 'tool',
tool_call_id: 'tool-call-1',
});
expect(result.newState.messages[1]).toEqual({
content: 'Tool execution was aborted by user.',
+ id: 'msg-123',
role: 'tool',
tool_call_id: 'tool-call-2',
});
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts
index cd0adfffeb5..e8bab1dac80 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts
@@ -259,6 +259,38 @@ describe('AiAgentService.execAgent - device tool pipeline ()', () => {
});
});
+ it('advertises local manifest capabilities only for the caller desktop', async () => {
+ const { deviceGateway } = await import('@/server/services/deviceGateway');
+ vi.spyOn(deviceGateway, 'isConfigured', 'get').mockReturnValue(true);
+ mockQueryDeviceList.mockResolvedValue([
+ { deviceId: 'desktop-device', hostname: 'Desktop', online: true, platform: 'darwin' },
+ { deviceId: 'remote-cli', hostname: 'CLI', online: true, platform: 'linux' },
+ ]);
+ mockGetAgentConfig.mockResolvedValue(
+ createBaseAgentConfig({ agencyConfig: { executionTarget: 'local' } }),
+ );
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ deviceId: 'desktop-device',
+ localDeviceId: 'desktop-device',
+ prompt: 'Hello',
+ });
+ expect(mockCreateServerAgentToolsEngine.mock.calls.at(-1)?.[1].manifestContext).toEqual(
+ expect.objectContaining({ executionEnv: 'local' }),
+ );
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ deviceId: 'remote-cli',
+ localDeviceId: 'desktop-device',
+ prompt: 'Hello',
+ });
+ expect(mockCreateServerAgentToolsEngine.mock.calls.at(-1)?.[1].manifestContext).toEqual(
+ expect.objectContaining({ executionEnv: 'device' }),
+ );
+ });
+
it('should not pass deviceContext when gateway is not configured', async () => {
const { deviceGateway } = await import('@/server/services/deviceGateway');
vi.spyOn(deviceGateway, 'isConfigured', 'get').mockReturnValue(false);
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 0f58ff650ea..f3f7e4af628 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -132,6 +132,7 @@ import { WorkspaceUserSettingsModel } from '@/database/models/workspaceUserSetti
import { toolsEnv } from '@/envs/tools';
import {
type ExecutionPlan,
+ executionPlanToManifestExecutionEnv,
executionTargetToRuntimeMode,
isDeviceCapablePlan,
isDeviceLockedPlan,
@@ -3962,6 +3963,7 @@ export class AiAgentService {
canUseDevice,
chatConfig: agentConfig.chatConfig ?? undefined,
clientExecutionAvailable: gatewayConfigured,
+ localDeviceId,
onlineDeviceIds: onlineDevices.map((device) => device.deviceId),
requestedDeviceId,
trigger: requestTriggerMetadata?.trigger,
@@ -4116,10 +4118,11 @@ export class AiAgentService {
// lobe-agent drops `callSubAgent` so the model can't recurse into nested
// sub-agents (which the runtime rejects, looping until the inactivity
// watchdog kills the op). Mirrors the frontend `createAgentToolsEngine`.
- // `executionEnv` mirrors the resolved plan so exec-capable tools
- // (lobe-skills) can state where their commands actually run β€” most
- // importantly the `device-unrouted` degradation, where the user picked
- // a local device that is offline and exec silently lands in the sandbox.
+ // `executionEnv` mirrors the resolved plan, while preserving the local
+ // target for a routed desktop because its readFile implementation can
+ // return images. It also keeps the `device-unrouted` degradation, where
+ // the user picked a local device that is offline and exec silently lands
+ // in the sandbox.
// For bot conversations we also pass the IM platform so `lobe-message`
// can drop APIs the platform can't fulfil (e.g. WeChat has no
// `readMessages`).
@@ -4131,7 +4134,7 @@ export class AiAgentService {
?.unsupportedMessageApis,
},
}),
- executionEnv: executionPlan.kind,
+ executionEnv: executionPlanToManifestExecutionEnv(executionPlan, localDeviceId),
executionEnvUnroutedReason:
executionPlan.kind === 'device-unrouted' ? executionPlan.reason : undefined,
isSubAgent: appContext?.isSubAgent,
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts
index c87bb45feb4..1785c9c32ec 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts
@@ -14,6 +14,7 @@ const mockMessageModelQuery = vi.hoisted(() => vi.fn());
const mockChat = vi.hoisted(() => vi.fn());
const mockInitModelRuntimeFromDB = vi.hoisted(() => vi.fn());
const mockConsumeStreamUntilDone = vi.hoisted(() => vi.fn());
+const mockSharpOptions = vi.hoisted(() => vi.fn());
const mockBuiltinModels = vi.hoisted(() => [
{
abilities: { audio: true, video: true, vision: true },
@@ -32,6 +33,18 @@ const mockBuiltinModels = vi.hoisted(() => [
},
]);
+const VALID_PNG_BASE64 =
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';
+const VALID_PNG_DATA_URL = `data:image/png;base64,${VALID_PNG_BASE64}`;
+
+const createCorruptedPngDataUrl = () => {
+ const bytes = Buffer.from(VALID_PNG_BASE64, 'base64');
+ const idatOffset = bytes.indexOf(Buffer.from('IDAT'));
+ bytes[idatOffset + 4] ^= 1;
+
+ return `data:image/png;base64,${bytes.toString('base64')}`;
+};
+
vi.mock('@/envs/tools', () => ({
toolsEnv: mockToolsEnv,
}));
@@ -65,6 +78,18 @@ vi.mock('model-bank', () => ({
LOBE_DEFAULT_MODEL_LIST: mockBuiltinModels,
}));
+vi.mock('sharp', async (importOriginal) => {
+ const actual = (await importOriginal()) as { default: (...args: any[]) => any };
+
+ return {
+ ...actual,
+ default: (input: Buffer, options?: Record<string, unknown>) => {
+ mockSharpOptions(options);
+ return actual.default(input, options);
+ },
+ };
+});
+
// Plan documents are the todo runtime's optional mirror; a topic that never ran
// `createPlan` simply has none. Model that here so the todo tests exercise the
// message-history path the tool context is supposed to supply.
@@ -317,14 +342,13 @@ describe('lobeAgentRuntime', () => {
const result = await runtime.analyzeMedia({
question: 'what is this?',
- urls: [
- 'http://example.com/generated.png',
- 'data:image/png;base64,abcd',
- 'data:audio/mpeg;base64,abcd',
- ],
+ urls: ['http://example.com/generated.png', VALID_PNG_DATA_URL, 'data:audio/mpeg;base64,abcd'],
});
expect(result.success).toBe(true);
+ expect(mockSharpOptions).toHaveBeenCalledWith(
+ expect.objectContaining({ failOn: 'error', limitInputPixels: 25_000_000 }),
+ );
expect(mockMessageModelQueryByIds).not.toHaveBeenCalled();
expect(mockChat).toHaveBeenCalledWith(
expect.objectContaining({
@@ -337,7 +361,7 @@ describe('lobeAgentRuntime', () => {
type: 'image_url',
}),
expect.objectContaining({
- image_url: { detail: 'auto', url: 'data:image/png;base64,abcd' },
+ image_url: { detail: 'auto', url: VALID_PNG_DATA_URL },
type: 'image_url',
}),
expect.objectContaining({
@@ -352,6 +376,83 @@ describe('lobeAgentRuntime', () => {
);
});
+ it('should reject a corrupted inline image and fail a multi-image batch closed', async () => {
+ const runtime = lobeAgentRuntime.factory(baseContext);
+
+ const result = await runtime.analyzeMedia({
+ question: 'compare these images',
+ urls: [VALID_PNG_DATA_URL, createCorruptedPngDataUrl()],
+ });
+
+ expect(result).toMatchObject({
+ error: { code: 'INVALID_IMAGE_DATA' },
+ success: false,
+ });
+ expect(result.content).toContain('2');
+ expect(mockChat).not.toHaveBeenCalled();
+ });
+
+ it('should resolve stable refs for durable tool-result images', async () => {
+ const toolImageRef = createMediaFileRef({
+ index: 0,
+ messageId: 'msg-read-file',
+ type: 'image',
+ });
+ mockMessageModelQueryByIds.mockResolvedValue([
+ { id: 'msg-1', role: 'tool', topicId: 'topic-1' },
+ ]);
+ mockMessageModelQuery.mockResolvedValue([
+ {
+ id: 'msg-read-file',
+ pluginState: {
+ filename: 'character.png',
+ images: [
+ {
+ fileId: 'file-tool-image',
+ mediaType: 'image/png',
+ url: 'https://example.com/tool-image.png',
+ },
+ ],
+ },
+ role: 'tool',
+ topicId: 'topic-1',
+ },
+ ]);
+ const runtime = lobeAgentRuntime.factory({ ...baseContext, topicId: 'topic-1' });
+
+ const result = await runtime.analyzeMedia({
+ question: 'what is in the image?',
+ refs: [toolImageRef],
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.state).toMatchObject({
+ files: [
+ {
+ id: 'file-tool-image',
+ name: 'character.png',
+ ref: toolImageRef,
+ type: 'image',
+ },
+ ],
+ });
+ expect(mockChat).toHaveBeenCalledWith(
+ expect.objectContaining({
+ messages: [
+ expect.objectContaining({
+ content: expect.arrayContaining([
+ {
+ image_url: { detail: 'auto', url: 'https://example.com/tool-image.png' },
+ type: 'image_url',
+ },
+ ]),
+ }),
+ ],
+ }),
+ expect.anything(),
+ );
+ });
+
it('should resolve stable refs from earlier topic messages', async () => {
const previousImageRef = createMediaFileRef({
index: 0,
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts
index a6e7cc5461e..c50de4e033f 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts
@@ -6,10 +6,10 @@ import type {
} from '@lobechat/builtin-tool-lobe-agent';
import {
buildAnalyzeMediaContent,
- createMediaFileItems,
+ createMediaFileItemsFromMessage,
createUrlMediaFileItems,
formatMediaUrlValidationError,
- hasUserMediaFiles,
+ hasAnalyzableMediaFiles,
LobeAgentIdentifier,
normalizeAnalyzeMediaInput,
selectMediaFileItems,
@@ -22,6 +22,7 @@ import type { ChatStreamPayload } from '@lobechat/model-runtime';
import { consumeStreamUntilDone } from '@lobechat/model-runtime';
import type { BuiltinServerRuntimeOutput } from '@lobechat/types';
import { RequestTrigger } from '@lobechat/types';
+import { parseDataUri } from '@lobechat/utils/uriParser';
import { MessageModel } from '@/database/models/message';
import { toolsEnv } from '@/envs/tools';
@@ -56,6 +57,49 @@ const buildError = (content: string, code: string): BuiltinServerRuntimeOutput =
success: false,
});
+const BASE64_CONTENT_PATTERN = /^[A-Z\d+/]+={0,2}$/i;
+const MAX_INLINE_IMAGE_PIXELS = 25_000_000;
+
+/**
+ * Decode inline images before the provider boundary. Protocol and header checks
+ * are insufficient because a PNG can retain a valid signature while its pixel
+ * chunks or CRCs are corrupted. Decode sequentially with an explicit pixel
+ * ceiling to cap peak memory for highly compressed and multi-image calls.
+ */
+const findInvalidInlineImageIndexes = async (urls: string[]) => {
+ const invalidIndexes: number[] = [];
+ const hasInlineImages = urls.some((url) => /^data:image\//i.test(url));
+ if (!hasInlineImages) return invalidIndexes;
+
+ // Keep the native image dependency out of server bundles that never validate
+ // inline images; the server runtime registry imports this module eagerly.
+ const { default: sharp } = await import('sharp');
+
+ for (const [index, url] of urls.entries()) {
+ if (!/^data:image\//i.test(url)) continue;
+
+ const { base64, type } = parseDataUri(url);
+ if (
+ type !== 'base64' ||
+ !base64 ||
+ !BASE64_CONTENT_PATTERN.test(base64) ||
+ base64.length % 4 === 1
+ ) {
+ invalidIndexes.push(index + 1);
+ continue;
+ }
+
+ try {
+ const buffer = Buffer.from(base64, 'base64');
+ await sharp(buffer, { failOn: 'error', limitInputPixels: MAX_INLINE_IMAGE_PIXELS }).stats();
+ } catch {
+ invalidIndexes.push(index + 1);
+ }
+ }
+
+ return invalidIndexes;
+};
+
const getModelAbilities = async (model: string, provider: string) => {
const { loadModels } = await import('@/business/client/model-bank/loadModels');
const builtinModels = await loadModels();
@@ -275,6 +319,14 @@ class LobeAgentExecutionRuntime {
return buildError(urlValidationError, 'UNSUPPORTED_MEDIA_URLS');
}
+ const invalidInlineImageIndexes = await findInvalidInlineImageIndexes(urlValidation.validUrls);
+ if (invalidInlineImageIndexes.length > 0) {
+ return buildError(
+ `Invalid inline image data at URL indexes: ${invalidInlineImageIndexes.join(', ')}.`,
+ 'INVALID_IMAGE_DATA',
+ );
+ }
+
const selectedUrlItems = createUrlMediaFileItems(urlValidation.validUrls);
let selectedRefItems: MediaFileItem[] = [];
@@ -293,9 +345,9 @@ class LobeAgentExecutionRuntime {
? await this.queryScopeMessages(messageModel, sourceMessage, postProcessUrl)
: [];
const orderedMediaMessages = [
- ...(sourceMessage && hasUserMediaFiles(sourceMessage) ? [sourceMessage] : []),
+ ...(sourceMessage && hasAnalyzableMediaFiles(sourceMessage) ? [sourceMessage] : []),
...mediaMessages.filter(
- (message) => message.id !== sourceMessage?.id && hasUserMediaFiles(message),
+ (message) => message.id !== sourceMessage?.id && hasAnalyzableMediaFiles(message),
),
];
@@ -307,7 +359,7 @@ class LobeAgentExecutionRuntime {
}
const mediaItems = orderedMediaMessages.flatMap((message) =>
- createMediaFileItems(message, message.imageList, message.videoList, message.audioList),
+ createMediaFileItemsFromMessage(message),
);
if (mediaItems.length === 0) {
diff --git a/packages/agent-runtime/src/executors/abortedToolRows.ts b/packages/agent-runtime/src/executors/abortedToolRows.ts
index a84499b35ec..b353a316716 100644
--- a/packages/agent-runtime/src/executors/abortedToolRows.ts
+++ b/packages/agent-runtime/src/executors/abortedToolRows.ts
@@ -83,7 +83,7 @@ export const settleAbortedToolRows = async ({
/** `tool_call_id β†’ the row that now holds its aborted result`. */
messageIds: Record<string, string>;
/** Tool messages to append to `state.messages`, in call order. */
- messages: Array<{ content: string; role: 'tool'; tool_call_id: string }>;
+ messages: Array<{ content: string; id: string; role: 'tool'; tool_call_id: string }>;
}> => {
const { operation, transports } = host;
const agentId = operation.agentId ?? state.metadata?.agentId;
@@ -98,7 +98,7 @@ export const settleAbortedToolRows = async ({
}
const messageIds: Record<string, string> = {};
- const messages: Array<{ content: string; role: 'tool'; tool_call_id: string }> = [];
+ const messages: Array<{ content: string; id: string; role: 'tool'; tool_call_id: string }> = [];
for (const toolPayload of toolsCalling) {
// Prefer an ID carried by the approval resume: its `parentMessageId` is the
@@ -140,8 +140,10 @@ export const settleAbortedToolRows = async ({
throw error;
}
+ /** Keep the persisted id even though aborted operations normally stop here. */
messages.push({
content: ABORTED_TOOL_CONTENT,
+ id: messageIds[toolPayload.id],
role: 'tool',
tool_call_id: toolPayload.id,
});
diff --git a/packages/agent-runtime/src/executors/resolveTools.test.ts b/packages/agent-runtime/src/executors/resolveTools.test.ts
index 27d3f1128bb..1b9747877a7 100644
--- a/packages/agent-runtime/src/executors/resolveTools.test.ts
+++ b/packages/agent-runtime/src/executors/resolveTools.test.ts
@@ -140,6 +140,9 @@ describe('resolveTools executors', () => {
parentMessageId: 'tool-msg-1',
toolCount: 1,
});
+ expect(result.newState.messages).toContainEqual(
+ expect.objectContaining({ id: 'tool-msg-1', role: 'tool' }),
+ );
});
it('persists a caller-provided blocked reason and content', async () => {
@@ -202,6 +205,10 @@ describe('resolveTools executors', () => {
);
expect(result.newState.status).toBe('done');
expect(result.newState.messages).toHaveLength(2);
+ expect(result.newState.messages).toEqual([
+ expect.objectContaining({ id: 'tool-msg-1', tool_call_id: 'tool-call-1' }),
+ expect.objectContaining({ id: 'tool-msg-1', tool_call_id: 'tool-call-2' }),
+ ]);
expect(result.events).toContainEqual(
expect.objectContaining({
reason: 'user_aborted',
@@ -260,6 +267,10 @@ describe('resolveTools executors', () => {
expect(createToolMessage).toHaveBeenCalledWith(
expect.objectContaining({ tool_call_id: 'tool-call-2' }),
);
+ expect(result.newState.messages).toEqual([
+ expect.objectContaining({ id: 'pending-msg-1', tool_call_id: 'tool-call-1' }),
+ expect.objectContaining({ id: 'tool-msg-1', tool_call_id: 'tool-call-2' }),
+ ]);
expect(result.newState.status).toBe('done');
});
diff --git a/packages/agent-runtime/src/executors/resolveTools.ts b/packages/agent-runtime/src/executors/resolveTools.ts
index 9f6664a6359..1ad0efdcaf9 100644
--- a/packages/agent-runtime/src/executors/resolveTools.ts
+++ b/packages/agent-runtime/src/executors/resolveTools.ts
@@ -76,6 +76,7 @@ export const resolveBlockedTools =
type: 'tool_end',
});
+ let toolMessageId: string;
try {
const toolMessage = await transports.messages.createToolMessage({
agentId,
@@ -95,14 +96,17 @@ export const resolveBlockedTools =
tool_call_id: toolPayload.id,
topicId,
});
- toolMessageIds.push(toolMessage.id);
+ toolMessageId = toolMessage.id;
+ toolMessageIds.push(toolMessageId);
} catch (error) {
await publishPersistError(host, error);
throw error;
}
+ /** Keep the persisted id so the next gateway step can resolve media refs. */
newState.messages.push({
content: result.content,
+ id: toolMessageId,
role: 'tool',
tool_call_id: toolPayload.id,
});
diff --git a/packages/agent-runtime/src/executors/tool.test.ts b/packages/agent-runtime/src/executors/tool.test.ts
index 5a1fc06390f..d5339e96c11 100644
--- a/packages/agent-runtime/src/executors/tool.test.ts
+++ b/packages/agent-runtime/src/executors/tool.test.ts
@@ -169,6 +169,9 @@ describe('tool executors', () => {
);
expect(result.nextContext?.phase).toBe('tool_result');
expect(result.nextContext?.payload).toMatchObject({ parentMessageId: 'tool-msg-1' });
+ expect(result.newState.messages).toContainEqual(
+ expect.objectContaining({ id: 'tool-msg-1', role: 'tool' }),
+ );
expect(result.newState.usage.tools.totalCalls).toBe(1);
});
diff --git a/packages/agent-runtime/src/executors/tool.ts b/packages/agent-runtime/src/executors/tool.ts
index d194e373cdc..282d54c0712 100644
--- a/packages/agent-runtime/src/executors/tool.ts
+++ b/packages/agent-runtime/src/executors/tool.ts
@@ -637,8 +637,15 @@ export const callTool =
topicId: runContext.topicId,
});
} else {
+ /**
+ * Preserve the durable row id in the in-memory turn. The next gateway
+ * step uses message ids to rebuild media refs before its DB rehydrate,
+ * and an id-less tool result makes that safety gate keep the stale
+ * snapshot instead.
+ */
newState.messages.push({
content: executionResult.content,
+ id: toolMessageId,
plugin: tool,
pluginState: executionResult.state,
role: 'tool',
diff --git a/packages/builtin-tool-lobe-agent/src/client/executor/index.ts b/packages/builtin-tool-lobe-agent/src/client/executor/index.ts
index 773481770a6..614c0aca898 100644
--- a/packages/builtin-tool-lobe-agent/src/client/executor/index.ts
+++ b/packages/builtin-tool-lobe-agent/src/client/executor/index.ts
@@ -9,10 +9,11 @@ import { LobeAgentManifest } from '../../manifest';
import type { MediaFileItem } from '../../media';
import {
buildAnalyzeMediaContent,
- createMediaFileItems,
+ createMediaFileItemsFromMessage,
createUrlMediaFileItems,
formatMediaUrlValidationError,
getUnexpectedAnalyzeMediaArgumentKeys,
+ hasAnalyzableMediaFiles,
hasUserMediaFiles,
normalizeAnalyzeMediaInput,
selectMediaFileItems,
@@ -265,14 +266,12 @@ class LobeAgentExecutor extends BaseExecutor<typeof LobeAgentApiName> {
: dbMessageSelectors.latestUserMessage(chatState);
const activeMediaMessages = dbMessageSelectors
.activeDbMessages(chatState)
- .filter(hasUserMediaFiles);
+ .filter(hasAnalyzableMediaFiles);
const mediaMessages = [
- ...(hasUserMediaFiles(sourceMessage) ? [sourceMessage] : []),
+ ...(hasAnalyzableMediaFiles(sourceMessage) ? [sourceMessage] : []),
...activeMediaMessages.filter((message) => message.id !== sourceMessage?.id),
];
- const files = mediaMessages.flatMap((message) =>
- createMediaFileItems(message, message.imageList, message.videoList, message.audioList),
- );
+ const files = mediaMessages.flatMap((message) => createMediaFileItemsFromMessage(message));
if (files.length === 0) {
return {
diff --git a/packages/builtin-tool-lobe-agent/src/manifest.test.ts b/packages/builtin-tool-lobe-agent/src/manifest.test.ts
index 7385e0d9038..9b10ca0c44d 100644
--- a/packages/builtin-tool-lobe-agent/src/manifest.test.ts
+++ b/packages/builtin-tool-lobe-agent/src/manifest.test.ts
@@ -36,6 +36,20 @@ describe('LobeAgentManifest', () => {
);
});
+ it('should route local media through file refs instead of local URLs or base64 text', () => {
+ const analyzeMedia = LobeAgentManifest.api[0];
+ const { refs, urls } = analyzeMedia.parameters.properties;
+
+ expect(analyzeMedia.description).toContain('local filesystem');
+ expect(analyzeMedia.description).toContain('base64 text');
+ expect(refs.description).toContain('local file-reading tools');
+ expect(urls.description).toContain('Local filesystem paths and file:// URLs are unsupported');
+ expect(LobeAgentManifest.systemRole).toContain(
+ 'Never pass local filesystem paths or `file://` URLs to `analyzeMedia.urls`',
+ );
+ expect(LobeAgentManifest.systemRole).toContain('stable ref');
+ });
+
it('should keep media analysis parameters compatible with strict tool schema validators', () => {
const parameters = LobeAgentManifest.api[0].parameters;
diff --git a/packages/builtin-tool-lobe-agent/src/manifest.ts b/packages/builtin-tool-lobe-agent/src/manifest.ts
index bf0187c5111..08fbcb3fbff 100644
--- a/packages/builtin-tool-lobe-agent/src/manifest.ts
+++ b/packages/builtin-tool-lobe-agent/src/manifest.ts
@@ -8,7 +8,7 @@ export const LobeAgentManifest: BuiltinToolManifest = {
api: [
{
description:
- "Analyze audio, images, or videos selected by media file refs or direct media URLs and answer a question about them. Prefer the active model's native multimodal capability when it can inspect the media directly; use this tool only as a fallback when the active model lacks the required audio, image, or video capability. Provide either refs or urls; at least one is required. Prefer refs when stable refs are available in <files_info>, such as msg_xxx.audio_1, msg_xxx.image_1, or msg_xxx.video_1, and use urls only for direct media URLs that are not available as message refs. After this tool returns, answer the user directly with the result.",
+ "Analyze audio, images, or videos selected by media file refs or direct media URLs and answer a question about them. Prefer the active model's native multimodal capability when it can inspect the media directly; use this tool only as a fallback when the active model lacks the required audio, image, or video capability. Provide either refs or urls; at least one is required. Prefer refs when stable refs are available in <files_info>, such as msg_xxx.audio_1, msg_xxx.image_1, or msg_xxx.video_1, and use urls only for direct media URLs that are not available as message refs. For media stored on a local filesystem, never pass an OS path or file:// URL through urls and never convert or copy the media as base64 text. If this fallback is needed, first use an available local file-reading tool to upload the media, then pass its stable ref through refs. After this tool returns, answer the user directly with the result.",
name: LobeAgentApiName.analyzeMedia,
parameters: {
additionalProperties: false,
@@ -19,7 +19,7 @@ export const LobeAgentManifest: BuiltinToolManifest = {
},
refs: {
description:
- 'Stable media file ref strings to analyze, such as ["msg_xxx.audio_1"], ["msg_xxx.image_1"], or ["msg_xxx.video_1"].',
+ 'Stable media file ref strings from <files_info>, including refs created for media uploaded by local file-reading tools, such as ["msg_xxx.audio_1"], ["msg_xxx.image_1"], or ["msg_xxx.video_1"].',
items: {
type: 'string',
},
@@ -28,7 +28,7 @@ export const LobeAgentManifest: BuiltinToolManifest = {
},
urls: {
description:
- 'Direct audio, image, or video URLs to analyze when no message file ref exists.',
+ 'Direct provider-readable HTTP(S) or data URLs to analyze when no stable media ref exists. Local filesystem paths and file:// URLs are unsupported; use an available local file-reading tool first, then pass its stable ref through refs.',
items: {
type: 'string',
},
diff --git a/packages/builtin-tool-lobe-agent/src/media.test.ts b/packages/builtin-tool-lobe-agent/src/media.test.ts
index bd8999c2f2f..2e092982889 100644
--- a/packages/builtin-tool-lobe-agent/src/media.test.ts
+++ b/packages/builtin-tool-lobe-agent/src/media.test.ts
@@ -4,9 +4,11 @@ import { describe, expect, it } from 'vitest';
import {
buildAnalyzeMediaContent,
createMediaFileItems,
+ createMediaFileItemsFromMessage,
createUrlMediaFileItems,
filterAllowedMediaUrls,
formatMediaUrlValidationError,
+ hasAnalyzableMediaFiles,
hasUserMediaFiles,
MAX_MEDIA_URL_LENGTH,
MAX_MEDIA_URLS,
@@ -108,6 +110,53 @@ describe('media', () => {
]);
});
+ it('should create stable refs for durable tool-result images', () => {
+ const items = createMediaFileItemsFromMessage({
+ id: 'tool-message-1',
+ pluginState: {
+ filename: 'character.png',
+ images: [
+ {
+ mediaType: 'image/png',
+ url: 'data:image/png;base64,opaque-data-must-not-be-exposed',
+ },
+ {
+ fileId: 'tool-image-1',
+ mediaType: 'image/png',
+ url: 'https://example.com/tool-image.png',
+ },
+ ],
+ },
+ role: 'tool',
+ });
+
+ expect(items).toEqual([
+ {
+ description: 'character.png',
+ id: 'tool-image-1',
+ localRef: 'image_2',
+ messageId: 'tool-message-1',
+ name: 'character.png',
+ ref: createMediaFileRef({ index: 1, messageId: 'tool-message-1', type: 'image' }),
+ type: 'image',
+ uri: 'https://example.com/tool-image.png',
+ },
+ ]);
+ });
+
+ it('should limit analyzable message media to user attachments and durable tool images', () => {
+ const imageList = [{ url: 'https://example.com/image.png' }];
+
+ expect(hasAnalyzableMediaFiles({ imageList, role: 'user' })).toBe(true);
+ expect(hasAnalyzableMediaFiles({ imageList, role: 'assistant' })).toBe(false);
+ expect(
+ hasAnalyzableMediaFiles({
+ pluginState: { images: [{ url: 'https://example.com/tool-image.png' }] },
+ role: 'tool',
+ }),
+ ).toBe(true);
+ });
+
it('should infer URL item type and name from direct media urls', () => {
expect(
createUrlMediaFileItems([
diff --git a/packages/builtin-tool-lobe-agent/src/media.ts b/packages/builtin-tool-lobe-agent/src/media.ts
index df8c237a335..952092fccc9 100644
--- a/packages/builtin-tool-lobe-agent/src/media.ts
+++ b/packages/builtin-tool-lobe-agent/src/media.ts
@@ -16,6 +16,15 @@ export interface MediaSourceMessage {
audioList?: ChatAudioItem[];
id?: string;
imageList?: ChatImageItem[];
+ pluginState?: {
+ filename?: string;
+ images?: Array<{
+ fileId?: string;
+ mediaType?: string;
+ name?: string;
+ url?: string;
+ }>;
+ };
role?: string;
videoList?: ChatVideoItem[];
}
@@ -156,6 +165,37 @@ export const hasUserMediaFiles = (message: unknown): message is MediaSourceMessa
(message as MediaSourceMessage).role === 'user' &&
hasMediaFiles(message);
+const createToolResultImageItems = (message: MediaSourceMessage): MediaFileItem[] => {
+ if (message.role !== 'tool' || !Array.isArray(message.pluginState?.images)) return [];
+
+ const { filename, images } = message.pluginState;
+
+ return images.flatMap((image, index) => {
+ if (typeof image.url !== 'string') return [];
+
+ try {
+ if (!ALLOWED_REMOTE_MEDIA_URL_PROTOCOLS.has(new URL(image.url).protocol)) return [];
+ } catch {
+ return [];
+ }
+
+ const name = image.name || filename || image.fileId || `Image ${index + 1}`;
+
+ return [
+ {
+ description: name,
+ id: image.fileId,
+ localRef: createMediaLocalRef('image', index),
+ messageId: message.id,
+ name,
+ ref: createMediaFileRef({ index, messageId: message.id, type: 'image' }),
+ type: 'image' as const,
+ uri: image.url,
+ },
+ ];
+ });
+};
+
export const createMediaFileItems = (
message: MediaSourceMessage | undefined,
images: ChatImageItem[] = [],
@@ -206,6 +246,27 @@ export const createMediaFileItems = (
}),
];
+export const createMediaFileItemsFromMessage = (message: MediaSourceMessage): MediaFileItem[] => {
+ const toolResultImages = createToolResultImageItems(message);
+ // Tool result images and imageList entries share the same message/index ref
+ // namespace. Prefer the durable tool result to avoid duplicate refs where
+ // selectMediaFileItems would otherwise resolve the attachment first.
+ const attachmentImages = toolResultImages.length > 0 ? [] : message.imageList;
+
+ return [
+ ...createMediaFileItems(message, attachmentImages, message.videoList, message.audioList),
+ ...toolResultImages,
+ ];
+};
+
+export const hasAnalyzableMediaFiles = (message: unknown): message is MediaSourceMessage => {
+ if (!message || typeof message !== 'object') return false;
+
+ const mediaMessage = message as MediaSourceMessage;
+
+ return hasUserMediaFiles(mediaMessage) || createToolResultImageItems(mediaMessage).length > 0;
+};
+
export const inferMediaTypeFromUrl = (url: string): MediaFileItem['type'] => {
if (/^data:audio\//i.test(url)) return 'audio';
if (/^data:video\//i.test(url)) return 'video';
diff --git a/packages/builtin-tool-lobe-agent/src/systemRole.ts b/packages/builtin-tool-lobe-agent/src/systemRole.ts
index 3b33d46d561..206e9bb188f 100644
--- a/packages/builtin-tool-lobe-agent/src/systemRole.ts
+++ b/packages/builtin-tool-lobe-agent/src/systemRole.ts
@@ -210,6 +210,11 @@ const multimodalAnalysisSection = `
\`analyzeMedia\` is only a fallback when the active model cannot inspect the requested audio/image/video natively.
If the media is already visible in the current multimodal context, answer directly without this tool.
Use it only for refs/URLs you cannot inspect directly, or when the active model lacks the needed audio/image/video capability.
+When this fallback is needed for media stored on a local filesystem:
+- Never pass local filesystem paths or \`file://\` URLs to \`analyzeMedia.urls\`.
+- Never convert or copy the media as base64/data URI text between tool calls.
+- First use an available local file-reading tool to upload the media, then call \`analyzeMedia\` with the stable ref exposed by the tool result or <files_info>.
+- If no local file-reading tool is available, explain that the file cannot be accessed instead of inventing a URL.
</multimodal_analysis>
`;
diff --git a/packages/builtin-tool-local-system/src/__tests__/systemRole.test.ts b/packages/builtin-tool-local-system/src/__tests__/systemRole.test.ts
index 79fdb38926f..1ac608d50c2 100644
--- a/packages/builtin-tool-local-system/src/__tests__/systemRole.test.ts
+++ b/packages/builtin-tool-local-system/src/__tests__/systemRole.test.ts
@@ -27,4 +27,10 @@ describe('systemRole templates', () => {
expect(template).toContain('{{shellSyntaxGuidance}}');
}
});
+
+ it('teaches image reads only in the desktop template', () => {
+ expect(desktopPrompt).toContain('readFile');
+ expect(desktopPrompt).toContain('base64');
+ expect(genericPrompt).not.toContain('base64');
+ });
});
diff --git a/packages/builtin-tool-local-system/src/index.ts b/packages/builtin-tool-local-system/src/index.ts
index aae77ff09ad..aa7d7ed48dd 100644
--- a/packages/builtin-tool-local-system/src/index.ts
+++ b/packages/builtin-tool-local-system/src/index.ts
@@ -1,5 +1,6 @@
export { createPathScopeAudit, pathScopeAudit } from './interventionAudit';
export { LocalSystemManifest } from './manifest';
+export { resolveLocalSystemManifest } from './resolveManifest';
export { getShellSyntaxGuidance } from './shellSyntaxGuidance';
export { systemPrompt } from './systemRole';
export {
diff --git a/packages/builtin-tool-local-system/src/manifest.ts b/packages/builtin-tool-local-system/src/manifest.ts
index 9779dcbd909..01d57657656 100644
--- a/packages/builtin-tool-local-system/src/manifest.ts
+++ b/packages/builtin-tool-local-system/src/manifest.ts
@@ -3,13 +3,18 @@ import { type BuiltinToolManifest } from '@lobechat/types';
import { systemPrompt } from './systemRole';
import { LocalSystemApiName, LocalSystemIdentifier } from './types';
+export const READ_FILE_DESCRIPTION =
+ 'Read the content of a text or document file (txt/md/json/source code/pdf/docx/etc.). Binary files (.bin/.exe/.zip/.b64/encoded blobs) are rejected with a structured error β€” use runCommand with file/hexdump/strings to inspect those instead. Output is capped at 500K chars total and 8K chars per line; for larger files, use a narrower line range or grepContent.';
+
+export const IMAGE_CAPABLE_READ_FILE_DESCRIPTION =
+ 'Read text and document files (txt/md/json/source code/pdf/docx/etc.) or local image files (PNG/JPEG/GIF/WebP). For a local image path, call readFile directly so the image is uploaded as a visual tool result. Never use shell commands to convert images to base64/data URI text or copy encoded image data between tools. Other binary files (.bin/.exe/.zip/.b64/encoded blobs) are rejected with a structured error β€” use runCommand with file/hexdump/strings to inspect those instead. Text output is capped at 500K chars total and 8K chars per line; for larger files, use a narrower line range or grepContent.';
+
export const LocalSystemManifest: BuiltinToolManifest = {
executors: ['client', 'server'],
api: [
{
defaultTimeoutMs: 30_000,
- description:
- 'Read the content of a text or document file (txt/md/json/source code/pdf/docx/etc.). Binary files (.bin/.exe/.zip/.b64/encoded blobs) are rejected with a structured error β€” use runCommand with file/hexdump/strings to inspect those instead. Output is capped at 500K chars total and 8K chars per line; for larger files, use a narrower line range or grepContent.',
+ description: READ_FILE_DESCRIPTION,
humanIntervention: {
dynamic: {
default: 'never',
diff --git a/packages/builtin-tool-local-system/src/resolveManifest.test.ts b/packages/builtin-tool-local-system/src/resolveManifest.test.ts
new file mode 100644
index 00000000000..5d611204ee7
--- /dev/null
+++ b/packages/builtin-tool-local-system/src/resolveManifest.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ IMAGE_CAPABLE_READ_FILE_DESCRIPTION,
+ LocalSystemManifest,
+ READ_FILE_DESCRIPTION,
+} from './manifest';
+import { resolveLocalSystemManifest } from './resolveManifest';
+import { LocalSystemApiName } from './types';
+
+const readFileDescription = (
+ executionEnv?: 'device' | 'device-unrouted' | 'local' | 'none' | 'sandbox',
+) =>
+ resolveLocalSystemManifest({ executionEnv })?.api.find(
+ (api) => api.name === LocalSystemApiName.readFile,
+ )?.description;
+
+describe('resolveLocalSystemManifest', () => {
+ it('keeps the context-free manifest limited to portable file capabilities', () => {
+ const description = LocalSystemManifest.api.find(
+ (api) => api.name === LocalSystemApiName.readFile,
+ )?.description;
+
+ expect(description).toBe(READ_FILE_DESCRIPTION);
+ expect(description).not.toContain('PNG');
+ });
+
+ it('advertises direct image reads for the desktop local runtime', () => {
+ const manifest = resolveLocalSystemManifest({ executionEnv: 'local' });
+
+ expect(readFileDescription('local')).toBe(IMAGE_CAPABLE_READ_FILE_DESCRIPTION);
+ expect(readFileDescription('local')).toContain('base64');
+ expect(manifest?.systemRole).toContain('Image files are uploaded as visual tool results');
+ });
+
+ it.each([undefined, 'device', 'device-unrouted', 'none', 'sandbox'] as const)(
+ 'keeps %s instructions aligned with portable file capabilities',
+ (executionEnv) => {
+ const manifest = resolveLocalSystemManifest({ executionEnv });
+
+ expect(readFileDescription(executionEnv)).toBe(READ_FILE_DESCRIPTION);
+ expect(manifest?.systemRole).not.toContain('base64');
+ expect(manifest?.systemRole).not.toContain('local images such as PNG');
+ },
+ );
+});
diff --git a/packages/builtin-tool-local-system/src/resolveManifest.ts b/packages/builtin-tool-local-system/src/resolveManifest.ts
new file mode 100644
index 00000000000..41d43ae76aa
--- /dev/null
+++ b/packages/builtin-tool-local-system/src/resolveManifest.ts
@@ -0,0 +1,26 @@
+import type { BuiltinManifestResolver } from '@lobechat/types';
+
+import { IMAGE_CAPABLE_READ_FILE_DESCRIPTION, LocalSystemManifest } from './manifest';
+import { systemPrompt as desktopSystemPrompt } from './systemRole.desktop';
+import { LocalSystemApiName } from './types';
+
+/**
+ * Image reads are currently implemented only by the Desktop local IPC path.
+ * Device runs use local-file-shell, which rejects binary image files, so their
+ * manifest must not instruct the model to call an unsupported capability.
+ */
+export const resolveLocalSystemManifest: BuiltinManifestResolver = (context) => {
+ if (context.executionEnv !== 'local') {
+ return LocalSystemManifest;
+ }
+
+ return {
+ ...LocalSystemManifest,
+ api: LocalSystemManifest.api.map((api) =>
+ api.name === LocalSystemApiName.readFile
+ ? { ...api, description: IMAGE_CAPABLE_READ_FILE_DESCRIPTION }
+ : api,
+ ),
+ systemRole: desktopSystemPrompt,
+ };
+};
diff --git a/packages/builtin-tool-local-system/src/systemRole.desktop.ts b/packages/builtin-tool-local-system/src/systemRole.desktop.ts
index 845b8ee0597..084fe0f3776 100644
--- a/packages/builtin-tool-local-system/src/systemRole.desktop.ts
+++ b/packages/builtin-tool-local-system/src/systemRole.desktop.ts
@@ -21,7 +21,7 @@ Use these paths when the user refers to these common locations by name (e.g., "m
You have access to a set of tools to interact with the user's local file system:
**File Operations:**
-1. **readFile**: Reads the content of a specified file, optionally within a line range. You can read file types such as Word, Excel, PowerPoint, PDF, and plain text files.
+1. **readFile**: Reads documents, text files, and local images such as PNG, JPEG, GIF, and WebP. Image files are uploaded as visual tool results.
2. **writeFile**: Write content to a specific file, only support plain text file like \`.text\` or \`.md\`
3. **editFile**: Performs exact string replacements in files. Must read the file first before editing.
4. **moveFiles**: Moves multiple files or directories. Also handles renames β€” pass the original directory with the new filename in \`newPath\`.
@@ -53,6 +53,7 @@ You have access to a set of tools to interact with the user's local file system:
- 'loc' (Optional): A two-element array [startLine, endLine] to specify a line range to read (e.g., '[301, 400]' reads lines 301 to 400).
- If 'loc' is omitted, it defaults to reading the first 200 lines ('[0, 200]').
- To read the entire file: First call 'readFile' (potentially without 'loc'). The response includes 'totalLineCount'. Then, call 'readFile' again with 'loc: [0, totalLineCount]' to get the full content.
+ - For a local image path, call 'readFile' directly. Never use shell commands to convert the image to base64/data URI text or copy encoded image data between tools.
- For searching files: Use 'searchFiles' with the 'keywords' parameter (search string). 'keywords' is split on whitespace and every token must appear as a substring of the filename (case- and diacritic-insensitive, order-independent). Pass only the discriminating words β€” long phrases full of optional words will return nothing. You can optionally add the following filter parameters to narrow down the search:
- 'contentContains': Find files whose content includes specific text.
- 'createdAfter' / 'createdBefore': Filter by creation date.
diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.ts
index 4c523906041..a408bbd0ecc 100644
--- a/packages/builtin-tools/src/index.ts
+++ b/packages/builtin-tools/src/index.ts
@@ -20,7 +20,10 @@ import { GroupManagementManifest } from '@lobechat/builtin-tool-group-management
import { ImageGenerationManifest } from '@lobechat/builtin-tool-image-generation';
import { KnowledgeBaseManifest } from '@lobechat/builtin-tool-knowledge-base';
import { LobeAgentManifest, resolveLobeAgentManifest } from '@lobechat/builtin-tool-lobe-agent';
-import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
+import {
+ LocalSystemManifest,
+ resolveLocalSystemManifest,
+} from '@lobechat/builtin-tool-local-system';
import { MemoryManifest } from '@lobechat/builtin-tool-memory';
import { MessageManifest, resolveMessageManifest } from '@lobechat/builtin-tool-message';
import { PageAgentManifest } from '@lobechat/builtin-tool-page-agent';
@@ -256,6 +259,7 @@ const builtinToolRegistry: LobeBuiltinTool[] = [
hidden: true,
identifier: LocalSystemManifest.identifier,
manifest: LocalSystemManifest,
+ resolveManifest: resolveLocalSystemManifest,
type: 'builtin',
},
{
diff --git a/packages/context-engine/src/processors/MessageContent.ts b/packages/context-engine/src/processors/MessageContent.ts
index e333809a3ed..918463f967e 100644
--- a/packages/context-engine/src/processors/MessageContent.ts
+++ b/packages/context-engine/src/processors/MessageContent.ts
@@ -1,3 +1,4 @@
+import { createMediaFileRef } from '@lobechat/const/mediaRef';
import { filesPrompts } from '@lobechat/prompts';
import type { ChatAudioItem, MessageContentPart } from '@lobechat/types';
import { normalizeAudioDurationMs } from '@lobechat/utils/audio';
@@ -30,6 +31,25 @@ const log = debug('context-engine:processor:MessageContentProcessor');
export const VISION_DOWNGRADE_PLACEHOLDER =
'[image omitted: native vision is not supported. Do not infer or describe the image. If the request depends on it, use an available visual-analysis tool before answering; otherwise state that the image cannot be inspected.]';
+/**
+ * Heterogeneous-agent image uploads mirror each persisted image URL into tool
+ * text as `![mediaType](url)`. Non-vision models must receive only the opaque
+ * media ref, otherwise they can copy the signed URL into a later tool call.
+ */
+const stripUploadedImageMarkdown = (
+ content: string,
+ images: Array<{ mediaType?: unknown; url: string }>,
+): string => {
+ let sanitized = content;
+
+ for (const image of images) {
+ if (typeof image.mediaType !== 'string') continue;
+ sanitized = sanitized.replaceAll(`![${image.mediaType}](${image.url})`, '');
+ }
+
+ return sanitized.trim();
+};
+
/**
* Deserialize content string to message content parts
* Returns null if content is not valid JSON array of parts
@@ -476,13 +496,14 @@ export class MessageContentProcessor extends BaseProcessor {
private async processToolMessage(message: any): Promise<any> {
const rawImages = message.pluginState?.images;
- // Only forward entries with a durable, fetchable URL. Pre-upload entries
- // (base64 `data`, no `url`) must never reach the LLM payload, and legacy
- // non-http(s) URLs (e.g. desktop-only `localfile://` previews) can't be
- // fetched by the send path.
+ // Forward provider-readable HTTP(S) and inline image URLs to vision models.
+ // Pre-upload entries (`data` without `url`) and legacy non-http(s) URLs
+ // (e.g. desktop-only `localfile://` previews) cannot reach the send path.
const images = Array.isArray(rawImages)
- ? rawImages.filter(
- (image: any) => typeof image?.url === 'string' && /^(?:data:|https?:)/.test(image.url),
+ ? rawImages.flatMap((image: any, index: number) =>
+ typeof image?.url === 'string' && /^(?:data:image\/|https?:)/i.test(image.url)
+ ? [{ ...image, sourceIndex: index }]
+ : [],
)
: [];
@@ -503,13 +524,29 @@ export class MessageContentProcessor extends BaseProcessor {
}
// Vision not supported: drop the image parts but surface a placeholder so
- // the model still knows the tool produced an image it can't inspect.
+ // the model can pass a stable opaque ref to the visual-analysis fallback.
+ // The signed URL stays out of model-visible text, which prevents the model
+ // from copying opaque image data between tool calls.
if (!canUseVision) {
- const placeholders = Array.from(
- { length: images.length },
- () => VISION_DOWNGRADE_PLACEHOLDER,
- ).join('\n');
- const content = textContent ? `${textContent}\n\n${placeholders}` : placeholders;
+ const fallbackTextContent = stripUploadedImageMarkdown(textContent, images);
+ const placeholders = images
+ .map(({ sourceIndex, url }) => {
+ // Inline image data is safe to send as a structured vision input but
+ // must never be copied into text or exposed as a reusable media ref.
+ if (!message.id || !/^https?:/i.test(url)) return VISION_DOWNGRADE_PLACEHOLDER;
+
+ const ref = createMediaFileRef({
+ index: sourceIndex,
+ messageId: message.id,
+ type: 'image',
+ });
+
+ return `[image omitted: native vision is not supported. Media ref: ${ref}. Do not infer or describe the image. Use an available visual-analysis tool with this ref before answering.]`;
+ })
+ .join('\n');
+ const content = fallbackTextContent
+ ? `${fallbackTextContent}\n\n${placeholders}`
+ : placeholders;
return { ...message, content };
}
diff --git a/packages/context-engine/src/processors/__tests__/MessageContent.test.ts b/packages/context-engine/src/processors/__tests__/MessageContent.test.ts
index 82bcb4a27f3..c16630de768 100644
--- a/packages/context-engine/src/processors/__tests__/MessageContent.test.ts
+++ b/packages/context-engine/src/processors/__tests__/MessageContent.test.ts
@@ -1,3 +1,4 @@
+import { createMediaFileRef } from '@lobechat/const/mediaRef';
import type { ChatAudioItem, ChatImageItem, ChatVideoItem, UIChatMessage } from '@lobechat/types';
import { describe, expect, it, vi } from 'vitest';
@@ -383,12 +384,86 @@ describe('MessageContentProcessor', () => {
const result = await processor.process(createContext(messages));
- // Non-vision provider: image parts are dropped, a placeholder signals the
- // tool produced an image, and the textual result + tool_call_id survive.
- expect(result.messages[0].content).toBe(`1 result\n\n${VISION_DOWNGRADE_PLACEHOLDER}`);
+ const imageRef = createMediaFileRef({ index: 0, messageId: 'tool-1', type: 'image' });
+ const content = result.messages[0].content as string;
+
+ expect(content).toContain(imageRef);
+ expect(content).toContain('visual-analysis tool');
+ expect(content).not.toContain('http://example.com/screenshot.png');
expect(result.messages[0].tool_call_id).toBe('call_abc');
});
+ it('should remove uploaded image markdown URLs before adding a media ref', async () => {
+ mockIsCanUseVision.mockReturnValue(false);
+
+ const processor = new MessageContentProcessor({
+ model: 'any-model',
+ provider: 'any-provider',
+ isCanUseVision: mockIsCanUseVision,
+ fileContext: { enabled: false },
+ });
+ const imageUrl = 'https://example.com/f/image-id?signature=secret';
+ const messages: UIChatMessage[] = [
+ {
+ content: `Read image result\n![image/png](${imageUrl})`,
+ id: 'tool-uploaded-image',
+ pluginState: { images: [{ mediaType: 'image/png', url: imageUrl }] },
+ role: 'tool',
+ tool_call_id: 'call_uploaded_image',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ } as any,
+ ];
+
+ const result = await processor.process(createContext(messages));
+ const content = result.messages[0].content as string;
+
+ expect(content).toContain('Read image result');
+ expect(content).toContain(
+ createMediaFileRef({ index: 0, messageId: 'tool-uploaded-image', type: 'image' }),
+ );
+ expect(content).not.toContain(imageUrl);
+ expect(content).not.toContain('![image/png]');
+ });
+
+ it('should keep inline tool images as structured input only for vision models', async () => {
+ mockIsCanUseVision.mockReturnValue(true);
+
+ const processor = new MessageContentProcessor({
+ model: 'gpt-4-vision',
+ provider: 'openai',
+ isCanUseVision: mockIsCanUseVision,
+ fileContext: { enabled: false },
+ });
+ const dataUrl = 'data:image/png;base64,AAAA';
+ const messages: UIChatMessage[] = [
+ {
+ content: 'inline image',
+ id: 'tool-inline',
+ pluginState: { images: [{ mediaType: 'image/png', url: dataUrl }] },
+ role: 'tool',
+ tool_call_id: 'call_inline',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ } as any,
+ ];
+
+ const result = await processor.process(createContext(messages));
+
+ expect(result.messages[0].content).toEqual([
+ { text: 'inline image', type: 'text' },
+ { image_url: { detail: 'auto', url: dataUrl }, type: 'image_url' },
+ ]);
+
+ mockIsCanUseVision.mockReturnValue(false);
+ const downgraded = await processor.process(createContext(messages));
+
+ expect(downgraded.messages[0].content).toBe(
+ `inline image\n\n${VISION_DOWNGRADE_PLACEHOLDER}`,
+ );
+ expect(downgraded.messages[0].content).not.toContain(dataUrl);
+ });
+
it('should pass through tool messages without images unchanged', async () => {
mockIsCanUseVision.mockReturnValue(true);
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
index c59d5474d08..90b020891ca 100644
--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
@@ -1085,6 +1085,99 @@ describe('createRouterRuntime', () => {
expect(mockChatFail).toHaveBeenCalledTimes(1);
});
+ it('should mark image decoding failures as non-retryable for route observers', async () => {
+ const imageDecodeError = {
+ error: {
+ message:
+ '400 INVALID_ARGUMENT: Failed to decode image data. Please make sure the image is valid.',
+ },
+ errorType: AgentRuntimeErrorType.ProviderBizError,
+ provider: 'test',
+ status: 400,
+ };
+ const mockChatFail = vi.fn().mockRejectedValue(imageDecodeError);
+ const onRouteAttempt = vi.fn().mockResolvedValue(undefined);
+
+ class FailRuntime implements LobeRuntimeAI {
+ chat = mockChatFail;
+ }
+
+ const Runtime = createRouterRuntime({
+ id: 'test-runtime',
+ onRouteAttempt,
+ routers: [
+ {
+ apiType: 'openai',
+ models: ['gemini-vision'],
+ options: [{ apiKey: 'key-1' }, { apiKey: 'key-2' }],
+ runtime: FailRuntime as any,
+ },
+ ],
+ });
+
+ const runtime = new Runtime();
+ await expect(
+ runtime.chat({ model: 'gemini-vision', messages: [], temperature: 0.7 }),
+ ).rejects.toEqual(imageDecodeError);
+
+ expect(mockChatFail).toHaveBeenCalledTimes(1);
+ expect(onRouteAttempt).toHaveBeenCalledTimes(1);
+ expect(onRouteAttempt).toHaveBeenCalledWith(
+ expect.objectContaining({
+ error: imageDecodeError,
+ nonRetryable: true,
+ nonRetryableReason: 'imageDecode',
+ success: false,
+ }),
+ );
+ });
+
+ it('should not label retryable failures as terminal image decoding errors', async () => {
+ const retryableError = {
+ error: {
+ message: 'Unable to process input image',
+ },
+ errorType: AgentRuntimeErrorType.ProviderBizError,
+ provider: 'test',
+ status: 429,
+ };
+ const mockChatFail = vi.fn().mockRejectedValue(retryableError);
+ const onRouteAttempt = vi.fn().mockResolvedValue(undefined);
+
+ class FailRuntime implements LobeRuntimeAI {
+ chat = mockChatFail;
+ }
+
+ const Runtime = createRouterRuntime({
+ id: 'test-runtime',
+ onRouteAttempt,
+ routers: [
+ {
+ apiType: 'openai',
+ models: ['gemini-vision'],
+ options: [{ apiKey: 'key-1' }, { apiKey: 'key-2' }],
+ runtime: FailRuntime as any,
+ },
+ ],
+ });
+
+ const runtime = new Runtime();
+ await expect(
+ runtime.chat({ model: 'gemini-vision', messages: [], temperature: 0.7 }),
+ ).rejects.toEqual(retryableError);
+
+ expect(mockChatFail).toHaveBeenCalledTimes(2);
+ expect(onRouteAttempt).toHaveBeenCalledTimes(2);
+ expect(onRouteAttempt).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({
+ nonRetryable: false,
+ nonRetryableReason: undefined,
+ success: false,
+ }),
+ );
+ });
+
it('should not retry when the response_format schema is invalid', async () => {
const invalidSchemaError = {
errorType: AgentRuntimeErrorType.ProviderBizError,
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
index a155530bae7..58ba0f29581 100644
--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
@@ -39,7 +39,10 @@ import type {
TextToSpeechPayload,
} from '../../types';
import { AgentRuntimeError } from '../../utils/createError';
-import { isNonRetryableRequestError } from '../../utils/isNonRetryableRequestError';
+import {
+ isImageDecodingRequestError,
+ isNonRetryableRequestError,
+} from '../../utils/isNonRetryableRequestError';
import type { ModelIdMappingOptions } from '../../utils/modelIdMapping';
import { postProcessModelList } from '../../utils/postProcessModelList';
import { safeParseJSON } from '../../utils/safeParseJSON';
@@ -110,6 +113,8 @@ export interface RouteAttemptResult {
error?: unknown;
metadata?: Record<string, unknown>;
model: string;
+ nonRetryable?: boolean;
+ nonRetryableReason?: 'imageDecode';
optionIndex: number;
providerId: string;
remark?: string;
@@ -754,6 +759,12 @@ export const createRouterRuntime = ({
);
}
+ const nonRetryable = isNonRetryableRequestError(error);
+ const nonRetryableReason =
+ nonRetryable && isImageDecodingRequestError(error)
+ ? ('imageDecode' as const)
+ : undefined;
+
params
.onRouteAttempt?.({
apiType: resolvedApiType,
@@ -762,6 +773,8 @@ export const createRouterRuntime = ({
error,
metadata,
model,
+ nonRetryable,
+ nonRetryableReason,
optionIndex: index,
providerId: id,
remark,
@@ -773,7 +786,7 @@ export const createRouterRuntime = ({
log('onRouteAttempt callback error: %O', e);
});
- if (isNonRetryableRequestError(error)) {
+ if (nonRetryable) {
throw error;
}
diff --git a/packages/model-runtime/src/utils/isNonRetryableRequestError.test.ts b/packages/model-runtime/src/utils/isNonRetryableRequestError.test.ts
index 3442985b93a..ab690fa5977 100644
--- a/packages/model-runtime/src/utils/isNonRetryableRequestError.test.ts
+++ b/packages/model-runtime/src/utils/isNonRetryableRequestError.test.ts
@@ -1,7 +1,10 @@
import { describe, expect, it } from 'vitest';
import { AgentRuntimeErrorType } from '../types/error';
-import { isNonRetryableRequestError } from './isNonRetryableRequestError';
+import {
+ isImageDecodingRequestError,
+ isNonRetryableRequestError,
+} from './isNonRetryableRequestError';
describe('isNonRetryableRequestError', () => {
it('returns true for ExceededContextWindow errors', () => {
@@ -29,6 +32,35 @@ describe('isNonRetryableRequestError', () => {
).toBe(true);
});
+ it('returns true for provider image decoding request errors', () => {
+ expect(
+ isNonRetryableRequestError({
+ error: {
+ message:
+ '400 INVALID_ARGUMENT: Failed to decode image data. Please make sure the image is valid.',
+ },
+ errorType: AgentRuntimeErrorType.ProviderBizError,
+ status: 400,
+ }),
+ ).toBe(true);
+
+ expect(
+ isNonRetryableRequestError({
+ error: { message: 'Unable to process input image' },
+ errorType: AgentRuntimeErrorType.ProviderBizError,
+ status: 400,
+ }),
+ ).toBe(true);
+
+ expect(
+ isImageDecodingRequestError({
+ error: { message: 'Unable to process input image' },
+ errorType: AgentRuntimeErrorType.ProviderBizError,
+ }),
+ ).toBe(true);
+ expect(isImageDecodingRequestError({ message: 'Invalid request payload' })).toBe(false);
+ });
+
it('returns true for invalid request payload errors', () => {
expect(
isNonRetryableRequestError({
@@ -143,6 +175,14 @@ describe('isNonRetryableRequestError', () => {
});
it('returns false for retryable rate limit and quota errors', () => {
+ expect(
+ isNonRetryableRequestError({
+ error: { message: 'Unable to process input image' },
+ errorType: AgentRuntimeErrorType.ProviderBizError,
+ status: 429,
+ }),
+ ).toBe(false);
+
expect(
isNonRetryableRequestError({
error: { code: 'rate_limit_exceeded', message: 'Rate limit reached for requests' },
diff --git a/packages/model-runtime/src/utils/isNonRetryableRequestError.ts b/packages/model-runtime/src/utils/isNonRetryableRequestError.ts
index 5453a82de45..84361ec7e05 100644
--- a/packages/model-runtime/src/utils/isNonRetryableRequestError.ts
+++ b/packages/model-runtime/src/utils/isNonRetryableRequestError.ts
@@ -54,6 +54,11 @@ const RETRYABLE_MESSAGE_PATTERNS = [
'unauthorized',
];
+const IMAGE_DECODING_MESSAGE_PATTERNS = [
+ 'failed to decode image data',
+ 'unable to process input image',
+];
+
const NON_RETRYABLE_MESSAGE_PATTERNS = [
'assistant message prefill',
'conversation must end with a user message',
@@ -61,6 +66,7 @@ const NON_RETRYABLE_MESSAGE_PATTERNS = [
'context_length_exceeded',
'does not support parameter',
'expected a string',
+ ...IMAGE_DECODING_MESSAGE_PATTERNS,
'input is too long',
'input tokens exceed',
'invalid input',
@@ -161,6 +167,14 @@ const collectStatusCodes = (
return result;
};
+export const isImageDecodingRequestError = (error: unknown): boolean => {
+ const combined = collectErrorStrings(error)
+ .map((value) => value.toLowerCase())
+ .join('\n');
+
+ return IMAGE_DECODING_MESSAGE_PATTERNS.some((pattern) => combined.includes(pattern));
+};
+
export const isNonRetryableRequestError = (error: unknown): boolean => {
const errorStrings = collectErrorStrings(error);
const normalizedStrings = errorStrings.map((value) => value.toLowerCase());
@@ -172,6 +186,12 @@ export const isNonRetryableRequestError = (error: unknown): boolean => {
if (isErrorCausedByContentFilter(error)) return true;
+ // Explicitly retryable HTTP statuses represent route or channel conditions.
+ // They take precedence over provider body text, which can reuse terminal
+ // request phrases such as "unable to process input image" for a 429 response.
+ const statusCodes = collectStatusCodes(error);
+ if (statusCodes.some((statusCode) => RETRYABLE_STATUS_CODES.has(statusCode))) return false;
+
if (normalizedStrings.some((value) => RETRYABLE_ERROR_CODES.has(value))) return false;
if (normalizedStrings.some((value) => NON_RETRYABLE_ERROR_CODES.has(value))) return true;
@@ -179,8 +199,5 @@ export const isNonRetryableRequestError = (error: unknown): boolean => {
if (RETRYABLE_MESSAGE_PATTERNS.some((pattern) => combined.includes(pattern))) return false;
if (NON_RETRYABLE_MESSAGE_PATTERNS.some((pattern) => combined.includes(pattern))) return true;
- const statusCodes = collectStatusCodes(error);
- if (statusCodes.some((statusCode) => RETRYABLE_STATUS_CODES.has(statusCode))) return false;
-
return false;
};
diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.ts
index e8943b02500..6080ce0dbfe 100644
--- a/packages/types/src/tool/builtin.ts
+++ b/packages/types/src/tool/builtin.ts
@@ -305,9 +305,9 @@ export interface BuiltinToolResolveContext {
unsupportedMessageApis?: string[];
};
/**
- * Where this run executes, mirroring the resolved `ExecutionPlan.kind`
- * (`device` / `device-unrouted` / `sandbox` / `none`) plus `local` for the
- * desktop in-process engine. Lets exec-capable tools (e.g. lobe-skills)
+ * Where this run executes, derived from the resolved `ExecutionPlan`. The
+ * routed desktop-local target stays `local`; other plans mirror their `kind`
+ * (`device` / `device-unrouted` / `sandbox` / `none`). Lets exec-capable tools (e.g. lobe-skills)
* rewrite their API descriptions per environment β€” most notably
* `device-unrouted`, where the user picked their local device but it is
* offline and commands silently fall back to the cloud sandbox. Kept as a
diff --git a/src/helpers/executionTarget.test.ts b/src/helpers/executionTarget.test.ts
index 0862253ecaf..4172f679093 100644
--- a/src/helpers/executionTarget.test.ts
+++ b/src/helpers/executionTarget.test.ts
@@ -4,6 +4,7 @@ import { describe, expect, it } from 'vitest';
import {
type ExecutionPlan,
+ executionPlanToManifestExecutionEnv,
executionTargetToRuntimeMode,
isDeviceLockedPlan,
isHeterogeneousSandboxExecutionAvailable,
@@ -428,6 +429,53 @@ describe('executionTargetToRuntimeMode', () => {
});
});
+describe('executionPlanToManifestExecutionEnv', () => {
+ it('preserves the image-capable desktop target only after it is routed', () => {
+ expect(
+ executionPlanToManifestExecutionEnv(
+ {
+ deviceId: 'desktop-device',
+ kind: 'device',
+ target: 'local',
+ },
+ 'desktop-device',
+ ),
+ ).toBe('local');
+ expect(
+ executionPlanToManifestExecutionEnv({
+ kind: 'device-unrouted',
+ reason: 'no-online-device',
+ target: 'local',
+ }),
+ ).toBe('device-unrouted');
+ });
+
+ it('does not advertise desktop capabilities when a local target routes elsewhere', () => {
+ const plan: ExecutionPlan = {
+ deviceId: 'remote-cli-device',
+ kind: 'device',
+ target: 'local',
+ };
+
+ expect(executionPlanToManifestExecutionEnv(plan, 'desktop-device')).toBe('device');
+ expect(executionPlanToManifestExecutionEnv(plan)).toBe('device');
+ });
+
+ it('keeps non-local plan kinds unchanged', () => {
+ expect(
+ executionPlanToManifestExecutionEnv({
+ deviceId: 'remote-device',
+ kind: 'device',
+ target: 'device',
+ }),
+ ).toBe('device');
+ expect(executionPlanToManifestExecutionEnv({ kind: 'sandbox', target: 'sandbox' })).toBe(
+ 'sandbox',
+ );
+ expect(executionPlanToManifestExecutionEnv({ kind: 'none', target: 'none' })).toBe('none');
+ });
+});
+
describe('resolveRuntimeMode', () => {
it('derives from the default target when executionTarget is unset', () => {
// desktop default β†’ local
diff --git a/src/helpers/executionTarget.ts b/src/helpers/executionTarget.ts
index d3d96dce88b..107ea1eb7de 100644
--- a/src/helpers/executionTarget.ts
+++ b/src/helpers/executionTarget.ts
@@ -326,6 +326,23 @@ export type ExecutionPlan = { target: DeviceExecutionTarget } &
| { kind: 'sandbox' }
);
+export type ExecutionManifestEnvironment = ExecutionPlan['kind'] | 'local';
+
+/**
+ * Preserve the desktop-local capability signal after the server resolves that
+ * target to the caller's registered desktop. A per-request device override can
+ * keep `target: local` while routing to another machine, so the device IDs must
+ * match before the manifest advertises desktop-only image reads. Unrouted local
+ * targets keep their plan kind so manifests describe the sandbox degradation.
+ */
+export const executionPlanToManifestExecutionEnv = (
+ plan: ExecutionPlan,
+ localDeviceId?: string,
+): ExecutionManifestEnvironment =>
+ plan.kind === 'device' && plan.target === 'local' && plan.deviceId === localDeviceId
+ ? 'local'
+ : plan.kind;
+
/** Device tools (local-system / remote-device proxy) only exist in device-capable sessions. */
export const isDeviceCapablePlan = (plan: ExecutionPlan): boolean =>
plan.kind === 'device' || plan.kind === 'device-unrouted';
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
index dc591ad7990..de58277f841 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
@@ -1706,7 +1706,7 @@ describe('GatewayActionImpl', () => {
});
};
- it('forwards this desktop deviceId when local execution is selected', async () => {
+ it('forwards this desktop as both the route and local capability hint', async () => {
mockEnv.isDesktop = true;
mockRuntime.isLocal = true;
mockGateway.getDeviceInfo.mockResolvedValue({ deviceId: 'device-local-1' });
@@ -1714,7 +1714,10 @@ describe('GatewayActionImpl', () => {
await send();
expect(aiAgentService.execAgentTask).toHaveBeenCalledWith(
- expect.objectContaining({ deviceId: 'device-local-1' }),
+ expect.objectContaining({
+ deviceId: 'device-local-1',
+ localDeviceId: 'device-local-1',
+ }),
expect.anything(),
);
});
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts
index bc130f75755..018878e1796 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts
@@ -1,7 +1,8 @@
import type { AgentState } from '@lobechat/agent-runtime';
import * as agentRuntime from '@lobechat/agent-runtime';
+import { resolveLocalSystemManifest } from '@lobechat/builtin-tool-local-system';
import type * as LobeChatConst from '@lobechat/const';
-import { type UIChatMessage } from '@lobechat/types';
+import { type LobeChatPluginApi, type UIChatMessage } from '@lobechat/types';
import { act, renderHook } from '@testing-library/react';
import { type EnabledAiModel, ModelProvider } from 'model-bank';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -188,6 +189,7 @@ beforeEach(() => {
resetTestEnvironment();
setupMockSelectors();
spyOnMessageService();
+ desktopFlag.value = false;
serverConfigMock.enableMultimodalUnderstanding = false;
act(() => {
@@ -1227,6 +1229,53 @@ describe('StreamingExecutor actions', () => {
});
});
+ it('should resolve desktop client tool manifests for the local execution environment', () => {
+ desktopFlag.value = true;
+
+ const { result } = renderHook(() => useChatStore());
+ const userMessage = {
+ id: TEST_IDS.USER_MESSAGE_ID,
+ role: 'user',
+ content: TEST_CONTENT.USER_MESSAGE,
+ sessionId: TEST_IDS.SESSION_ID,
+ topicId: TEST_IDS.TOPIC_ID,
+ } as UIChatMessage;
+ const createToolsEngineSpy = vi
+ .spyOn(toolEngineering, 'createAgentToolsEngine')
+ .mockImplementation((_workingModel, _pluginIds, manifestContext) => {
+ const localSystemManifest = resolveLocalSystemManifest(manifestContext ?? {});
+
+ return {
+ generateToolsDetailed: vi.fn().mockReturnValue({
+ enabledManifests: localSystemManifest ? [localSystemManifest] : [],
+ enabledToolIds: localSystemManifest ? [localSystemManifest.identifier] : [],
+ tools: [],
+ }),
+ } as any;
+ });
+
+ const { state } = result.current.internal_createAgentState({
+ messages: [userMessage],
+ parentMessageId: userMessage.id,
+ agentId: TEST_IDS.SESSION_ID,
+ topicId: TEST_IDS.TOPIC_ID,
+ });
+
+ expect(createToolsEngineSpy).toHaveBeenCalledWith(
+ expect.any(Object),
+ undefined,
+ expect.objectContaining({ executionEnv: 'local' }),
+ );
+ const readFile = state.toolManifestMap['lobe-local-system']?.api.find(
+ (api: LobeChatPluginApi) => api.name === 'readFile',
+ );
+
+ expect(readFile?.description).toContain('base64');
+ expect(state.toolManifestMap['lobe-local-system']?.systemRole).toContain(
+ 'Image files are uploaded as visual tool results',
+ );
+ });
+
it('should not inject page editor context outside page scope', () => {
act(() => {
useChatStore.setState({ executeClientAgent: realExecAgentRuntime });
diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
index 3fb007631d6..c01310e83b5 100644
--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
@@ -272,9 +272,9 @@ export class StreamingExecutorActionImpl {
// no function tools are sent. `platformFilter` still gates availability.
mergedToolIds,
// Context-aware builtin manifests: lobe-agent hides callSubAgent in group /
- // sub-agent runs. Replaces the former dropSubAgentInGroup + applyPluginFilters
- // isSubAgent hard-coding.
- { isSubAgent, scope },
+ // sub-agent runs. Desktop client runs also need the local environment so
+ // local-system can advertise IPC-only capabilities such as direct image reads.
+ { executionEnv: isDesktop ? 'local' : undefined, isSubAgent, scope },
);
// When skillActivateMode is 'manual':
// Exclude only discovery tools (activator, skill-store) so runtime-managed defaults
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
index 45d8c2f6902..ccd9f516f39 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -50,11 +50,13 @@ import { createGatewayMemberStreamHandler } from './gatewayMemberStreamHandler';
/**
* When the agent runs against the local machine, resolve this desktop's
- * own gateway deviceId so it can be passed as the run's `deviceId`. The server
- * then presets `activeDeviceId` and injects `lobe-local-system` into the very
- * first LLM payload β€” skipping the extra `activateDevice` round-trip the model
- * is otherwise forced to make whenever more than one device is online (with a
- * single device the server's heuristic already covered it).
+ * own gateway deviceId so it can be passed as the run's routing `deviceId` and
+ * `localDeviceId` capability hint. The server then presets `activeDeviceId`,
+ * injects `lobe-local-system` into the first LLM payload, and advertises direct
+ * image reads only when the routed device still matches this desktop. This
+ * skips the extra `activateDevice` round-trip the model is otherwise forced to
+ * make whenever more than one device is online (with a single device the
+ * server's heuristic already covered it).
*
* Gated on the effective runtime mode (`isLocalSystemEnabledById`), which
* derives from `agencyConfig.executionTarget` β€” only a `local` target presets
@@ -109,7 +111,9 @@ const resolveDesktopDeviceHints = async (
try {
const info = await gatewayConnectionService.getDeviceInfo();
if (!info?.deviceId) return {};
- return isPlatformTask ? { localDeviceId: info.deviceId } : { deviceId: info.deviceId };
+ return isPlatformTask
+ ? { localDeviceId: info.deviceId }
+ : { deviceId: info.deviceId, localDeviceId: info.deviceId };
} catch {
return {};
}