🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(local-system): let readFile return images so vision models can see them (#16912)
Arvin Xu8284a6e2b2d8
diff --git a/apps/desktop/src/main/controllers/LocalFileCtr.ts b/apps/desktop/src/main/controllers/LocalFileCtr.tsindex 30f03972982..a2117daf49c 100644--- a/apps/desktop/src/main/controllers/LocalFileCtr.ts+++ b/apps/desktop/src/main/controllers/LocalFileCtr.ts@@ -54,6 +54,7 @@ import {moveLocalFiles,readLocalFile,renameLocalFile,+ resolveAgainstCwd,type SearchOptions,writeLocalFile,} from '@lobechat/local-file-shell';@@ -62,6 +63,7 @@ import { execa } from 'execa';import ContentSearchService from '@/services/contentSearchSrv';import FileSearchService from '@/services/fileSearchSrv';+import RemoteFileUploadService from '@/services/remoteFileUploadSrv';import { createLogger } from '@/utils/logger';import { netFetch } from '@/utils/net-fetch';@@ -73,6 +75,28 @@ const logger = createLogger('controllers:LocalFileCtr');const SAFE_PATH_PREFIXES = ['/tmp', '/var/tmp'] as const;const PROJECT_FILE_GLOB_LIMIT = 5000;+/**+ * Image extensions `readFile` uploads to file storage instead of refusing as+ * binary. The agent then sees the image (vision) via an `image_url` part,+ * rather than hitting "Unsupported binary file".+ *+ * Limited to the formats vision providers accept (Anthropic/OpenAI:+ * png/jpeg/gif/webp) — anything else would be silently dropped by the+ * model-runtime builders, which is worse than the binary refusal. SVG is+ * intentionally absent: it's text, and reading the source is more useful to+ * the model than a rasterization we can't produce here.+ */+const LOCAL_IMAGE_EXT_TO_MIME: Record<string, string> = {+ gif: 'image/gif',+ jpeg: 'image/jpeg',+ jpg: 'image/jpeg',+ png: 'image/png',+ webp: 'image/webp',+};++/** Refuse to load image bytes beyond this size — providers reject them anyway. */+const MAX_IMAGE_READ_BYTES = 10 * 1024 * 1024;+const TEXT_PREVIEW_MIME_TYPES = new Set(['application/graphql','application/javascript',@@ -395,6 +419,79 @@ export default class LocalFileCtr extends ControllerModule {fullContent: params.fullContent,loc: params.loc,});++ // Image files: `local-file-shell` refuses binary, and the agent should be+ // able to actually *see* the image (vision) rather than hit "Unsupported+ // binary file type". Delegate the upload to the embedded CLI+ // (`lh file upload`) and return a durable { fileId, url } — bytes never+ // cross IPC and never reach the DB; the MessageContent processor turns+ // the uploaded URL into an `image_url` part for the LLM.+ const ext = path.extname(params.path).toLowerCase().replace('.', '');+ const imageMimeType = LOCAL_IMAGE_EXT_TO_MIME[ext];+ if (imageMimeType) {+ const filePath = resolveAgainstCwd(params.path, params.cwd) ?? params.path;+ const filename = path.basename(filePath);++ const buildImageResult = (+ content: string,+ extra: Partial<LocalReadFileResult> = {},+ ): LocalReadFileResult => ({+ charCount: 0,+ content,+ createdTime: new Date(),+ fileType: imageMimeType,+ filename,+ isImage: true,+ lineCount: 0,+ loc: [0, 0],+ modifiedTime: new Date(),+ totalCharCount: 0,+ totalLineCount: 0,+ ...extra,+ });++ let fileStat;+ try {+ fileStat = await stat(filePath);+ } catch (error) {+ return buildImageResult(`Error accessing or processing file: ${(error as Error).message}`);+ }++ if (!fileStat.isFile()) {+ return buildImageResult(`Error: Not a regular file: ${filePath}`);+ }++ if (fileStat.size > MAX_IMAGE_READ_BYTES) {+ return buildImageResult(+ `Error: Image file is too large to preview (${fileStat.size} bytes, limit ${MAX_IMAGE_READ_BYTES}).`,+ );+ }++ try {+ const record = await this.app.getService(RemoteFileUploadService).uploadLocalFile(filePath);++ if (record?.url) {+ return buildImageResult(`[Image: ${filename}]`, {+ createdTime: fileStat.birthtime,+ imageFileId: record.id,+ imageUrl: record.url,+ modifiedTime: fileStat.mtime,+ });+ }++ logger.warn('Image upload returned no record:', { filePath });+ } catch (error) {+ logger.warn('Image upload failed:', { error, filePath });+ }++ // Degrade: the placeholder tells the model an image exists that it+ // cannot inspect, instead of failing the read outright.+ return buildImageResult(+ `[Image: ${filename}] (upload unavailable — the model cannot view this image)`,+ { createdTime: fileStat.birthtime, modifiedTime: fileStat.mtime },+ );+ }+return readLocalFile(params);}diff --git a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.readFile.test.ts b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.readFile.test.tsindex 5339f3a2794..ca351b38dde 100644--- a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.readFile.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.readFile.test.ts@@ -33,9 +33,15 @@ vi.mock('@/utils/net-fetch', () => ({ netFetch: vi.fn() }));vi.mock('@/utils/file-system', () => ({ makeSureDirExist: vi.fn() }));+const mockUploadService = {+ uploadLocalFile: vi.fn(),+};+const mockApp = {appStoragePath: '/mock/app/storage',- getService: vi.fn(),+ getService: vi.fn((ServiceClass: any) =>+ ServiceClass?.name === 'RemoteFileUploadService' ? mockUploadService : undefined,+ ),toolDetectorManager: { getBestTool: vi.fn(() => null) },} as unknown as App;@@ -136,6 +142,103 @@ describe('LocalFileCtr — readFile / readFiles (real fs)', () => {});});+ describe('readFile — image files', () => {+ const pngBytes = Buffer.from('89504e470d0a1a0a0000000d49484452', 'hex');++ it('should upload the image in main and return a durable reference', async () => {+ mockUploadService.uploadLocalFile.mockResolvedValue({+ id: 'file-1',+ url: 'https://files.example.com/cat.png',+ });+ const filePath = path.join(tmpDir, 'cat.png');+ await writeFile(filePath, pngBytes);++ const result = await localFileCtr.readFile({ path: filePath });++ expect(mockUploadService.uploadLocalFile).toHaveBeenCalledWith(filePath);+ expect(result.isImage).toBe(true);+ expect(result.fileType).toBe('image/png');+ expect(result.imageFileId).toBe('file-1');+ expect(result.imageUrl).toBe('https://files.example.com/cat.png');+ expect(result.content).toBe('[Image: cat.png]');+ });++ it('should resolve a relative image path against cwd', async () => {+ mockUploadService.uploadLocalFile.mockResolvedValue({+ id: 'file-2',+ url: 'https://files.example.com/nested.jpg',+ });+ await mkdir(path.join(tmpDir, 'assets'), { recursive: true });+ const filePath = path.join(tmpDir, 'assets', 'nested.jpg');+ await writeFile(filePath, pngBytes);++ const result = await localFileCtr.readFile({ cwd: tmpDir, path: 'assets/nested.jpg' });++ // The CLI receives the resolved absolute path, not the relative one.+ expect(mockUploadService.uploadLocalFile).toHaveBeenCalledWith(filePath);+ expect(result.isImage).toBe(true);+ expect(result.fileType).toBe('image/jpeg');+ expect(result.imageUrl).toBe('https://files.example.com/nested.jpg');+ });++ it('should degrade to a placeholder when the upload is declined', async () => {+ mockUploadService.uploadLocalFile.mockResolvedValue(undefined);+ const filePath = path.join(tmpDir, 'declined.png');+ await writeFile(filePath, pngBytes);++ const result = await localFileCtr.readFile({ path: filePath });++ expect(result.isImage).toBe(true);+ expect(result.imageUrl).toBeUndefined();+ expect(result.content).toContain('[Image: declined.png]');+ expect(result.content).toContain('upload unavailable');+ });++ it('should degrade to a placeholder when the upload throws', async () => {+ mockUploadService.uploadLocalFile.mockRejectedValue(new Error('network down'));+ const filePath = path.join(tmpDir, 'failed.png');+ await writeFile(filePath, pngBytes);++ const result = await localFileCtr.readFile({ path: filePath });++ expect(result.isImage).toBe(true);+ expect(result.imageUrl).toBeUndefined();+ expect(result.content).toContain('[Image: failed.png]');+ });++ it('should return a readable error for a missing image', async () => {+ const result = await localFileCtr.readFile({ path: path.join(tmpDir, 'missing.png') });++ expect(result.isImage).toBe(true);+ expect(result.imageUrl).toBeUndefined();+ expect(result.content).toContain('Error accessing or processing file');+ expect(mockUploadService.uploadLocalFile).not.toHaveBeenCalled();+ });++ it('should refuse oversized images instead of loading them', async () => {+ const filePath = path.join(tmpDir, 'huge.png');+ await writeFile(filePath, Buffer.alloc(10 * 1024 * 1024 + 1));++ const result = await localFileCtr.readFile({ path: filePath });++ expect(result.isImage).toBe(true);+ expect(result.imageUrl).toBeUndefined();+ expect(result.content).toContain('too large');+ expect(mockUploadService.uploadLocalFile).not.toHaveBeenCalled();+ });++ it('should read svg as text, not as an image', async () => {+ const filePath = path.join(tmpDir, 'icon.svg');+ const svg = '<svg xmlns="http://www.w3.org/2000/svg"></svg>';+ await writeFile(filePath, svg);++ const result = await localFileCtr.readFile({ path: filePath });++ expect(result.isImage).toBeUndefined();+ expect(result.content).toContain('<svg');+ });+ });+describe('readFiles', () => {it('should read multiple files successfully', async () => {const file1 = path.join(tmpDir, 'a.txt');diff --git a/apps/desktop/src/main/modules/cliEmbedding/generateCliWrapper.ts b/apps/desktop/src/main/modules/cliEmbedding/generateCliWrapper.tsindex f3cac834747..f1eaa4f8200 100644--- a/apps/desktop/src/main/modules/cliEmbedding/generateCliWrapper.ts+++ b/apps/desktop/src/main/modules/cliEmbedding/generateCliWrapper.ts@@ -22,7 +22,7 @@ function resolveElectronBinary(): string {/*** Resolve the CLI script path inside packaged resources.*/-function resolveCliScript(): string {+export function resolveCliScript(): string {if (app.isPackaged) {return path.join(process.resourcesPath, 'bin', 'lobe-cli.js');}diff --git a/apps/desktop/src/main/modules/cliEmbedding/index.ts b/apps/desktop/src/main/modules/cliEmbedding/index.tsindex bb91404ec40..d2507f8edf4 100644--- a/apps/desktop/src/main/modules/cliEmbedding/index.ts+++ b/apps/desktop/src/main/modules/cliEmbedding/index.ts@@ -1 +1 @@-export { generateCliWrapper, getCliWrapperDir } from './generateCliWrapper';+export { generateCliWrapper, getCliWrapperDir, resolveCliScript } from './generateCliWrapper';diff --git a/apps/desktop/src/main/services/__tests__/remoteFileUploadSrv.test.ts b/apps/desktop/src/main/services/__tests__/remoteFileUploadSrv.test.tsnew file mode 100644index 00000000000..5f22bd1ef1f--- /dev/null+++ b/apps/desktop/src/main/services/__tests__/remoteFileUploadSrv.test.ts@@ -0,0 +1,105 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { type App } from '@/core/App';++import RemoteFileUploadService from '../remoteFileUploadSrv';++const { execFileMock } = vi.hoisted(() => ({+ execFileMock: vi.fn(),+}));++vi.mock('node:child_process', () => ({+ execFile: execFileMock,+}));++// promisify(execFile) uses the custom-promisify symbol when present; easiest+// is to make the mock already promisified.+vi.mock('node:util', () => ({+ promisify: (fn: any) => fn,+}));++vi.mock('@/modules/cliEmbedding', () => ({+ resolveCliScript: () => '/app/resources/bin/lobe-cli.js',+}));++vi.mock('@/utils/logger', () => ({+ createLogger: () => ({+ debug: vi.fn(),+ error: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ }),+}));++const mockRemoteServerConfigCtr = {+ getAccessToken: vi.fn(),+ getRemoteServerUrl: vi.fn(),+};++const mockApp = {+ getController: vi.fn(() => mockRemoteServerConfigCtr),+} as unknown as App;++describe('RemoteFileUploadService.uploadLocalFile', () => {+ let service: RemoteFileUploadService;++ beforeEach(() => {+ vi.clearAllMocks();+ mockRemoteServerConfigCtr.getRemoteServerUrl.mockResolvedValue('https://server.example.com/');+ mockRemoteServerConfigCtr.getAccessToken.mockResolvedValue('token-abc');+ service = new RemoteFileUploadService(mockApp);+ });++ it('runs the embedded CLI with the desktop session injected and parses the record', async () => {+ execFileMock.mockResolvedValue({+ stdout: JSON.stringify({ id: 'file-1', url: 'https://files.example.com/cat.png' }),+ });++ const record = await service.uploadLocalFile('/tmp/cat.png');++ expect(record).toEqual({ id: 'file-1', url: 'https://files.example.com/cat.png' });++ const [execPath, args, opts] = execFileMock.mock.calls[0];+ expect(execPath).toBe(process.execPath);+ expect(args).toEqual([+ '/app/resources/bin/lobe-cli.js',+ 'file',+ 'upload',+ '/tmp/cat.png',+ '--json',+ 'id,url',+ ]);+ expect(opts.env.ELECTRON_RUN_AS_NODE).toBe('1');+ expect(opts.env.LOBEHUB_JWT).toBe('token-abc');+ // Trailing slash is stripped for LOBEHUB_SERVER.+ expect(opts.env.LOBEHUB_SERVER).toBe('https://server.example.com');+ });++ it('still runs without a desktop session — lh falls back to its own login', async () => {+ mockRemoteServerConfigCtr.getAccessToken.mockResolvedValue(null);+ execFileMock.mockResolvedValue({+ stdout: JSON.stringify({ id: 'file-2', url: 'https://files.example.com/b.png' }),+ });++ const record = await service.uploadLocalFile('/tmp/b.png');++ expect(record).toEqual({ id: 'file-2', url: 'https://files.example.com/b.png' });+ const [, , opts] = execFileMock.mock.calls[0];+ expect(opts.env.LOBEHUB_JWT).toBeUndefined();+ expect(opts.env.LOBEHUB_SERVER).toBeUndefined();+ });++ it('returns undefined when the CLI output has no record', async () => {+ execFileMock.mockResolvedValue({ stdout: '{}' });++ expect(await service.uploadLocalFile('/tmp/none.png')).toBeUndefined();+ });++ it('propagates CLI failures (non-zero exit) to the caller', async () => {+ execFileMock.mockRejectedValue(new Error('No authentication found'));++ await expect(service.uploadLocalFile('/tmp/fail.png')).rejects.toThrow(+ 'No authentication found',+ );+ });+});diff --git a/apps/desktop/src/main/services/remoteFileUploadSrv.ts b/apps/desktop/src/main/services/remoteFileUploadSrv.tsnew file mode 100644index 00000000000..ebfe7195619--- /dev/null+++ b/apps/desktop/src/main/services/remoteFileUploadSrv.ts@@ -0,0 +1,62 @@+import { execFile } from 'node:child_process';+import process from 'node:process';+import { promisify } from 'node:util';++import RemoteServerConfigCtr from '@/controllers/RemoteServerConfigCtr';+import { resolveCliScript } from '@/modules/cliEmbedding';+import { createLogger } from '@/utils/logger';++import { ServiceModule } from './index';++const logger = createLogger('services:RemoteFileUploadService');++const UPLOAD_TIMEOUT_MS = 60_000;++export interface UploadedFileRecord {+ id: string;+ url: string;+}++/**+ * Upload local files to the server's file storage from the MAIN process by+ * delegating to the embedded CLI — `lh file upload <path> --json` already+ * implements the whole flow (hash dedup, pre-signed S3 PUT, file record).+ *+ * Runs the CLI script with the app's own binary via `ELECTRON_RUN_AS_NODE=1`+ * (what the generated `lobehub` shell wrapper does), so nothing is spawned+ * through a shell and no PATH install is required. The desktop session is+ * injected via `LOBEHUB_JWT` / `LOBEHUB_SERVER` (same convention as CliCtr+ * and the hetero spawn paths); without one, `lh` falls back to its own+ * stored login.+ */+export default class RemoteFileUploadService extends ServiceModule {+ async uploadLocalFile(filePath: string): Promise<UploadedFileRecord | undefined> {+ const env: NodeJS.ProcessEnv = { ...process.env, ELECTRON_RUN_AS_NODE: '1' };++ const remoteCtr = this.app.getController(RemoteServerConfigCtr);+ if (remoteCtr) {+ const [token, serverUrl] = await Promise.all([+ remoteCtr.getAccessToken(),+ remoteCtr.getRemoteServerUrl(),+ ]);+ if (token && serverUrl) {+ env.LOBEHUB_JWT = token;+ env.LOBEHUB_SERVER = serverUrl.replace(/\/$/, '');+ }+ }++ const { stdout } = await promisify(execFile)(+ process.execPath,+ [resolveCliScript(), 'file', 'upload', filePath, '--json', 'id,url'],+ { env, timeout: UPLOAD_TIMEOUT_MS },+ );++ const record = JSON.parse(stdout.trim()) as Partial<UploadedFileRecord>;+ if (!record?.id || !record.url) {+ logger.warn('CLI upload returned no file record:', { filePath, stdout });+ return undefined;+ }++ return { id: record.id, url: record.url };+ }+}diff --git a/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/ReadFileView.tsx b/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/ReadFileView.tsxindex e4632594139..95108c0db56 100644--- a/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/ReadFileView.tsx+++ b/packages/builtin-tool-local-system/src/client/Render/ReadLocalFile/ReadFileView.tsx@@ -1,6 +1,6 @@import { useToolRenderCapabilities } from '@lobechat/shared-tool-ui';import type { ReadFileState } from '@lobechat/tool-runtime';-import { ActionIcon, Flexbox, Icon, Markdown, Text } from '@lobehub/ui';+import { ActionIcon, Flexbox, Icon, Image, Markdown, PreviewGroup, Text } from '@lobehub/ui';import { createStaticStyles } from 'antd-style';import { AlignLeft, Asterisk, ExternalLink, FolderOpen } from 'lucide-react';import React, { memo } from 'react';@@ -94,6 +94,7 @@ const ReadFileView = memo<ReadFileState>(fileType,charCount,content,+ images,totalLines,totalCharCount,loc,@@ -198,7 +199,20 @@ const ReadFileView = memo<ReadFileState>(className={styles.previewBox}style={{ height: isHtml ? 240 : undefined, maxHeight: 240 }}>- {isHtml ? (+ {images && images.length > 0 ? (+ <PreviewGroup>+ <Flexbox horizontal gap={8} style={{ flexWrap: 'wrap', padding: 8 }}>+ {images.map((image, index) => (+ <Image+ alt={filename || image.mediaType || ''}+ key={image.url || index}+ src={image.url}+ style={{ borderRadius: 8, maxHeight: 224, objectFit: 'contain' }}+ />+ ))}+ </Flexbox>+ </PreviewGroup>+ ) : isHtml ? (<InlineHtmlPreview content={content} />) : fileType === 'md' ? (<Markdown style={{ overflow: 'auto' }}>{content}</Markdown>diff --git a/packages/context-engine/src/processors/MessageContent.ts b/packages/context-engine/src/processors/MessageContent.tsindex dee9d270373..239d5874067 100644--- a/packages/context-engine/src/processors/MessageContent.ts+++ b/packages/context-engine/src/processors/MessageContent.ts@@ -12,6 +12,7 @@ declare module '../types' {interface PipelineContextMetadataOverrides {assistantMessagesProcessed?: number;messageContentProcessed?: number;+ toolMessagesProcessed?: number;userMessagesProcessed?: number;}}@@ -104,6 +105,7 @@ export class MessageContentProcessor extends BaseProcessor {let processedCount = 0;let userMessagesProcessed = 0;let assistantMessagesProcessed = 0;+ let toolMessagesProcessed = 0;// Process the content of each messagefor (let i = 0; i < clonedContext.messages.length; i++) {@@ -124,6 +126,12 @@ export class MessageContentProcessor extends BaseProcessor {assistantMessagesProcessed++;processedCount++;}+ } else if (message.role === 'tool') {+ updatedMessage = await this.processToolMessage(message);+ if (updatedMessage !== message) {+ toolMessagesProcessed++;+ processedCount++;+ }}if (updatedMessage !== message) {@@ -140,9 +148,10 @@ export class MessageContentProcessor extends BaseProcessor {clonedContext.metadata.messageContentProcessed = processedCount;clonedContext.metadata.userMessagesProcessed = userMessagesProcessed;clonedContext.metadata.assistantMessagesProcessed = assistantMessagesProcessed;+ clonedContext.metadata.toolMessagesProcessed = toolMessagesProcessed;log(- `Message content processing completed, processed ${processedCount} messages (user: ${userMessagesProcessed}, assistant: ${assistantMessagesProcessed})`,+ `Message content processing completed, processed ${processedCount} messages (user: ${userMessagesProcessed}, assistant: ${assistantMessagesProcessed}, tool: ${toolMessagesProcessed})`,);return this.markAsExecuted(clonedContext);@@ -436,6 +445,76 @@ export class MessageContentProcessor extends BaseProcessor {};}+ /**+ * Process tool message content.+ *+ * Tool messages carry the results of tool calls. When a tool returns images+ * (e.g. `readFile` on an image file), they're carried on `pluginState.images`+ * — the same convention as the CC `Read`-on-image echo, where each entry is+ * `{ url, mediaType, ... }` after upload. Convert them to `image_url` content+ * parts so vision-capable models can actually inspect the tool result, and+ * downgrade to text-only when the active model lacks vision — non-vision+ * providers reject `image_url` parts outright.+ *+ * `pluginState` (not `imageList`) is used because the builtin-tool result+ * pipeline already persists `result.state` onto the tool message's+ * `pluginState`, so no extra wiring is needed to carry tool-produced images.+ *+ * Tool messages MUST keep `tool_call_id` (and `name`): providers pair the+ * result with the originating tool call by it.+ */+ 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.+ const images = Array.isArray(rawImages)+ ? rawImages.filter(+ (image: any) => typeof image?.url === 'string' && /^(?:data:|https?:)/.test(image.url),+ )+ : [];++ // Fast path: no usable images — plain text tool result passes through unchanged.+ if (images.length === 0) return message;++ const canUseVision = !!this.config.isCanUseVision?.(this.config.model, this.config.provider);++ // Normalize text content (historical messages may already be multimodal).+ let textContent = '';+ if (typeof message.content === 'string') {+ textContent = message.content;+ } else if (Array.isArray(message.content)) {+ textContent = message.content+ .filter((part: any) => part?.type === 'text' && typeof part.text === 'string')+ .map((part: any) => part.text)+ .join('\n\n');+ }++ // 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.+ if (!canUseVision) {+ const placeholders = Array.from(+ { length: images.length },+ () => VISION_DOWNGRADE_PLACEHOLDER,+ ).join('\n');+ const content = textContent ? `${textContent}\n\n${placeholders}` : placeholders;++ return { ...message, content };+ }++ const contentParts: UserMessageContentPart[] = [];++ if (textContent) {+ contentParts.push({ text: textContent, type: 'text' });+ }++ contentParts.push(...(await this.processImageList(images)));++ return { ...message, content: contentParts };+ }+/*** Convert MessageContentPart[] (internal format) to OpenAI-compatible UserMessageContentPart[]*diff --git a/packages/context-engine/src/processors/__tests__/MessageContent.test.ts b/packages/context-engine/src/processors/__tests__/MessageContent.test.tsindex 13ff685f6e1..743455b09a2 100644--- a/packages/context-engine/src/processors/__tests__/MessageContent.test.ts+++ b/packages/context-engine/src/processors/__tests__/MessageContent.test.ts@@ -318,6 +318,141 @@ describe('MessageContentProcessor', () => {});});+ describe('Tool message with images', () => {+ it('should convert tool message imageList to image_url parts when vision is supported', async () => {+ mockIsCanUseVision.mockReturnValue(true);++ const processor = new MessageContentProcessor({+ model: 'gpt-4-vision',+ provider: 'openai',+ isCanUseVision: mockIsCanUseVision,+ fileContext: { enabled: false },+ });++ const messages: UIChatMessage[] = [+ {+ content: '1 result',+ id: 'tool-1',+ pluginState: {+ images: [{ url: 'http://example.com/screenshot.png', mediaType: 'image/png' }],+ },+ role: 'tool',+ tool_call_id: 'call_abc',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ } as any,+ ];++ const result = await processor.process(createContext(messages));++ const message = result.messages[0];+ // tool_call_id is preserved so the provider can pair the result with the call.+ expect(message.tool_call_id).toBe('call_abc');+ expect(message.content).toEqual([+ { text: '1 result', type: 'text' },+ {+ image_url: { detail: 'auto', url: 'http://example.com/screenshot.png' },+ type: 'image_url',+ },+ ]);+ });++ it('should downgrade tool message images to placeholder when vision is not supported', async () => {+ mockIsCanUseVision.mockReturnValue(false);++ const processor = new MessageContentProcessor({+ model: 'any-model',+ provider: 'any-provider',+ isCanUseVision: mockIsCanUseVision,+ fileContext: { enabled: false },+ });++ const messages: UIChatMessage[] = [+ {+ content: '1 result',+ id: 'tool-1',+ pluginState: {+ images: [{ url: 'http://example.com/screenshot.png', mediaType: 'image/png' }],+ },+ role: 'tool',+ tool_call_id: 'call_abc',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ } as any,+ ];++ 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}`);+ expect(result.messages[0].tool_call_id).toBe('call_abc');+ });++ it('should pass through tool messages without images unchanged', async () => {+ mockIsCanUseVision.mockReturnValue(true);++ const processor = new MessageContentProcessor({+ model: 'gpt-4-vision',+ provider: 'openai',+ isCanUseVision: mockIsCanUseVision,+ fileContext: { enabled: false },+ });++ const messages: UIChatMessage[] = [+ {+ content: 'plain text result',+ id: 'tool-1',+ role: 'tool',+ tool_call_id: 'call_abc',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ } as any,+ ];++ const result = await processor.process(createContext(messages));++ expect(result.messages[0].content).toBe('plain text result');+ expect(result.messages[0].tool_call_id).toBe('call_abc');+ });++ it('should ignore image entries without a fetchable URL', async () => {+ mockIsCanUseVision.mockReturnValue(true);++ const processor = new MessageContentProcessor({+ model: 'gpt-4-vision',+ provider: 'openai',+ isCanUseVision: mockIsCanUseVision,+ fileContext: { enabled: false },+ });++ const messages: UIChatMessage[] = [+ {+ content: '[Image: cat.png]',+ id: 'tool-1',+ pluginState: {+ images: [+ // Malformed entry without a url — must never reach the payload.+ { mediaType: 'image/png' },+ // Legacy desktop-only preview URL — unfetchable by the send path.+ { mediaType: 'image/png', url: 'localfile://file/tmp/cat.png?token=abc' },+ ],+ },+ role: 'tool',+ tool_call_id: 'call_abc',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ } as any,+ ];++ const result = await processor.process(createContext(messages));++ // No usable image: the tool message passes through as plain text.+ expect(result.messages[0].content).toBe('[Image: cat.png]');+ expect(result.messages[0].tool_call_id).toBe('call_abc');+ });+ });+describe('File context processing', () => {it('should add file context when enabled', async () => {mockIsCanUseVision.mockReturnValue(false);diff --git a/packages/electron-client-ipc/src/types/localSystem.ts b/packages/electron-client-ipc/src/types/localSystem.tsindex e94e486e12c..ae9fd8d8d7d 100644--- a/packages/electron-client-ipc/src/types/localSystem.ts+++ b/packages/electron-client-ipc/src/types/localSystem.ts@@ -182,6 +182,25 @@ export interface LocalReadFileResult {createdTime: Date;filename: string;fileType: string;+ /**+ * File record id of the uploaded image. Present only when+ * {@link LocalReadFileResult.isImage} is true and the main process+ * successfully uploaded the bytes to file storage.+ */+ imageFileId?: string;+ /**+ * Durable URL of the uploaded image. The main process uploads image reads+ * to file storage directly (base64 never crosses IPC or reaches the DB);+ * the tool layer forwards this URL to vision models. Absent when the+ * upload was declined/failed — `content` then carries a placeholder.+ */+ imageUrl?: string;+ /**+ * True when the path resolves to an image file. The binary is NOT placed+ * in `content`; instead {@link LocalReadFileResult.imageUrl} references+ * the uploaded bytes so vision models can inspect the image.+ */+ isImage?: boolean;/*** Line count of the content within the specified `loc` range.*/diff --git a/packages/local-file-shell/src/file/index.ts b/packages/local-file-shell/src/file/index.tsindex cefcf9ebbd8..1801a35bd98 100644--- a/packages/local-file-shell/src/file/index.ts+++ b/packages/local-file-shell/src/file/index.ts@@ -1,5 +1,5 @@export { editLocalFile } from './edit';-export { expandTilde } from './expandTilde';+export { expandTilde, resolveAgainstCwd } from './expandTilde';export { globLocalFiles } from './glob';export { grepContent } from './grep';export type { ListFilesOptions } from './list';diff --git a/packages/model-runtime/src/core/contextBuilders/openai.test.ts b/packages/model-runtime/src/core/contextBuilders/openai.test.tsindex e2746ba14b9..3cdfa8ffa92 100644--- a/packages/model-runtime/src/core/contextBuilders/openai.test.ts+++ b/packages/model-runtime/src/core/contextBuilders/openai.test.ts@@ -352,6 +352,90 @@ describe('convertOpenAIMessages', () => {expect((result[0] as any).reasoning_content).toBe('some reasoning content');});+ describe('tool messages with image parts', () => {+ it('should flatten the tool message to text and re-attach images as a user message', async () => {+ vi.mocked(parseDataUri).mockReturnValue({ type: 'url', base64: null, mimeType: null });++ const messages = [+ {+ role: 'assistant',+ content: '',+ tool_calls: [+ { id: 'call_1', type: 'function', function: { name: 'readFile', arguments: '{}' } },+ ],+ },+ {+ role: 'tool',+ tool_call_id: 'call_1',+ content: [+ { type: 'text', text: '[Image: cat.png]' },+ { type: 'image_url', image_url: { url: 'https://files.example.com/cat.png' } },+ ],+ },+ { role: 'user', content: 'what do you see?' },+ ] as OpenAI.ChatCompletionMessageParam[];++ const result = await convertOpenAIMessages(messages);++ expect(result).toEqual([+ messages[0],+ // Tool message content must be text-only for the OpenAI API.+ { role: 'tool', tool_call_id: 'call_1', content: '[Image: cat.png]' },+ {+ role: 'user',+ content: [+ { type: 'text', text: 'Image output of tool call call_1:' },+ { type: 'image_url', image_url: { url: 'https://files.example.com/cat.png' } },+ ],+ },+ { role: 'user', content: 'what do you see?' },+ ]);+ });++ it('should keep the tool batch contiguous when multiple tool results carry images', async () => {+ vi.mocked(parseDataUri).mockReturnValue({ type: 'url', base64: null, mimeType: null });++ const messages = [+ {+ role: 'assistant',+ content: '',+ tool_calls: [+ { id: 'call_1', type: 'function', function: { name: 'readFile', arguments: '{}' } },+ { id: 'call_2', type: 'function', function: { name: 'readFile', arguments: '{}' } },+ ],+ },+ {+ role: 'tool',+ tool_call_id: 'call_1',+ content: [{ type: 'image_url', image_url: { url: 'https://files.example.com/a.png' } }],+ },+ {+ role: 'tool',+ tool_call_id: 'call_2',+ content: 'plain text result',+ },+ ] as OpenAI.ChatCompletionMessageParam[];++ const result = await convertOpenAIMessages(messages);++ // No user message may interleave between the tool results of one batch.+ expect(result.map((m) => m.role)).toEqual(['assistant', 'tool', 'tool', 'user']);+ expect(result[1]).toEqual({+ role: 'tool',+ tool_call_id: 'call_1',+ content: '[Image output attached below]',+ });+ expect(result[2]).toEqual(messages[2]);+ expect(result[3]).toEqual({+ role: 'user',+ content: [+ { type: 'text', text: 'Image output of tool call call_1:' },+ { type: 'image_url', image_url: { url: 'https://files.example.com/a.png' } },+ ],+ });+ });+ });+describe('DeepSeek reasoning_content compatibility', () => {it('should derive reasoning_content from reasoning.content for deepseek models', async () => {const messages = [@@ -523,6 +607,40 @@ describe('convertOpenAIResponseInputs', () => {]);});+ it('工具响应带图片时应保持 output 纯文本并追加 user 图片消息', async () => {+ vi.mocked(parseDataUri).mockReturnValue({ type: 'url', base64: null, mimeType: null });++ const messages: OpenAIChatMessage[] = [+ {+ content: [+ { text: '[Image: cat.png]', type: 'text' },+ { image_url: { url: 'https://files.example.com/cat.png' }, type: 'image_url' },+ ] as any,+ role: 'tool',+ tool_call_id: 'call_123',+ },+ ];++ const result = await convertOpenAIResponseInputs(messages);++ expect(result).toEqual([+ {+ call_id: 'call_123',+ // function_call_output.output is text-only — images must not land here.+ output: '[Image: cat.png]',+ type: 'function_call_output',+ },+ {+ content: [+ { text: 'Image output of tool call call_123:', type: 'input_text' },+ { image_url: 'https://files.example.com/cat.png', type: 'input_image' },+ ],+ role: 'user',+ type: 'message',+ },+ ]);+ });+it('应该正确转换包含图片的消息', async () => {const messages: OpenAIChatMessage[] = [{diff --git a/packages/model-runtime/src/core/contextBuilders/openai.ts b/packages/model-runtime/src/core/contextBuilders/openai.tsindex ae1c794c9cb..8b7e8531b8c 100644--- a/packages/model-runtime/src/core/contextBuilders/openai.ts+++ b/packages/model-runtime/src/core/contextBuilders/openai.ts@@ -26,9 +26,7 @@ const isDeepSeekModel = (model: string | undefined) =>typeof model === 'string' && model.toLowerCase().includes('deepseek');type OpenAICompatibleContentPart =- | ExtendedChatCompletionContentPart- | OpenAI.ChatCompletionContentPart- | UserMessageContentPart;+ ExtendedChatCompletionContentPart | OpenAI.ChatCompletionContentPart | UserMessageContentPart;const isInternalThinkingContentPart = (content: OpenAICompatibleContentPart,@@ -78,11 +76,67 @@ export const convertMessageContent = async (return content;};+/**+ * OpenAI tool messages only accept text content — the Chat Completions API+ * rejects `image_url` parts inside a `role: 'tool'` message. When a tool+ * result carries images (e.g. builtin `readFile` on an image file), flatten+ * the tool message to text and re-attach the images as a `user` message+ * placed AFTER the contiguous tool-result batch: every tool message must+ * directly follow the assistant message holding its `tool_calls`, so nothing+ * may be interleaved inside the batch.+ */+const extractToolMessageImages = (+ converted: OpenAI.ChatCompletionMessageParam[],+): OpenAI.ChatCompletionMessageParam[] => {+ const output: OpenAI.ChatCompletionMessageParam[] = [];+ let pendingToolImages: { parts: OpenAI.ChatCompletionContentPart[]; toolCallId?: string }[] = [];++ const flushToolImages = () => {+ if (pendingToolImages.length === 0) return;++ const content = pendingToolImages.flatMap((pending) => [+ { text: `Image output of tool call ${pending.toolCallId}:`, type: 'text' as const },+ ...pending.parts,+ ]);+ output.push({ content, role: 'user' });+ pendingToolImages = [];+ };++ for (const message of converted) {+ if (message.role !== 'tool') flushToolImages();++ if (message.role === 'tool' && Array.isArray(message.content)) {+ const parts = message.content as any[];+ const imageParts = parts.filter((c) => c?.type === 'image_url' || c?.type === 'video_url');+ const text = parts+ .filter((c) => c?.type === 'text' && typeof c.text === 'string')+ .map((c) => c.text)+ .join('\n\n');++ if (imageParts.length > 0) {+ pendingToolImages.push({ parts: imageParts, toolCallId: message.tool_call_id });+ }++ output.push({+ ...message,+ content: text || (imageParts.length > 0 ? '[Image output attached below]' : ''),+ });+ continue;+ }++ output.push(message);+ }++ flushToolImages();++ return output;+};+export const convertOpenAIMessages = async (messages: OpenAI.ChatCompletionMessageParam[],options?: ConvertMessageContentOptions,) => {- return (await Promise.all(+ const converted = (await Promise.all(messages.map(async (message) => {const msg = message as any;@@ -133,6 +187,8 @@ export const convertOpenAIMessages = async (return result;}),)) as OpenAI.ChatCompletionMessageParam[];++ return extractToolMessageImages(converted);};export const convertOpenAIResponseInputs = async (@@ -201,12 +257,59 @@ export const convertOpenAIResponseInputs = async ()return items;+ // `function_call_output.output` is text-only. When the tool result+ // carries images (e.g. builtin `readFile` on an image file), keep the+ // output textual and re-attach the images as a follow-up user message+ // item — Responses pairs outputs to calls by `call_id`, so a message+ // item between outputs is fine.+ let outputText = message.content as string;+ let imageParts: UserMessageContentPart[] = [];++ if (Array.isArray(message.content)) {+ const parts = message.content as any[];+ imageParts = parts.filter((c) => c?.type === 'image_url');+ outputText =+ parts+ .filter((c) => c?.type === 'text' && typeof c.text === 'string')+ .map((c) => c.text)+ .join('\n\n') || (imageParts.length > 0 ? '[Image output attached below]' : '');+ }+items.push({call_id: message.tool_call_id,- output: message.content,+ output: outputText,type: 'function_call_output',} as OpenAI.Responses.ResponseFunctionToolCallOutputItem);+ if (imageParts.length > 0) {+ const imageContent = (+ await Promise.all(+ imageParts.map(async (c) => {+ const image = await convertMessageContent(+ c as OpenAI.ChatCompletionContentPart,+ options,+ );+ const url = (image as OpenAI.ChatCompletionContentPartImage).image_url?.url;+ return url ? { image_url: url, type: 'input_image' as const } : undefined;+ }),+ )+ ).filter((c) => !!c);++ if (imageContent.length > 0) {+ items.push({+ content: [+ {+ text: `Image output of tool call ${message.tool_call_id}:`,+ type: 'input_text' as const,+ },+ ...imageContent,+ ],+ role: 'user',+ type: 'message',+ } as OpenAI.Responses.ResponseInputItem);+ }+ }+return items;}diff --git a/packages/tool-runtime/src/ComputerRuntime.ts b/packages/tool-runtime/src/ComputerRuntime.tsindex d317c5afda9..b9e9d613ddb 100644--- a/packages/tool-runtime/src/ComputerRuntime.ts+++ b/packages/tool-runtime/src/ComputerRuntime.ts@@ -106,6 +106,32 @@ export abstract class ComputerRuntime {}const r = result.result || {};++ // Image file: `local-file-shell`'s readLocalFile refuses binary, so the+ // IPC layer uploads the bytes to file storage and returns a durable+ // reference instead. Carry it on `state.images` — the MessageContent+ // tool-message processor turns the uploaded URL into an `image_url`+ // part so vision-capable models can actually see the image.+ if (r.isImage && r.imageUrl) {+ const filename = r.filename || args.path;+ const placeholder = r.content || `[Image: ${filename}]`;+ const state: ReadFileState = {+ content: placeholder,+ filename,+ fileType: r.fileType,+ images: [+ { fileId: r.imageFileId, mediaType: r.fileType || 'image/png', url: r.imageUrl },+ ],+ path: args.path,+ };++ return {+ content: placeholder,+ state,+ success: true,+ };+ }+const fileContent = r.content || '';const state: ReadFileState = {diff --git a/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts b/packages/tool-runtime/src/LocalSystemExecutionRuntime.tsindex 42f0f1b0646..ab1ae1c2bec 100644--- a/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts+++ b/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts@@ -261,6 +261,12 @@ export class LocalSystemExecutionRuntime extends ComputerRuntime {content: raw.content,fileType: raw.fileType,filename: raw.filename,+ // Image results: set by LocalFileCtr when the path resolves to an+ // image (uploaded in main), so ComputerRuntime can route them to+ // `state.images`.+ imageFileId: raw.imageFileId,+ imageUrl: raw.imageUrl,+ isImage: raw.isImage,loc: raw.loc,totalCharCount: raw.totalCharCount,totalLineCount: raw.totalLineCount,diff --git a/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts b/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.tsindex a4b74e849c6..166a8fd7be2 100644--- a/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts+++ b/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts@@ -94,3 +94,65 @@ describe('LocalSystemExecutionRuntime.globFiles', () => {});});});++describe('LocalSystemExecutionRuntime.readFile', () => {+ it('routes uploaded image results onto state.images', async () => {+ const service = createService({+ readLocalFile: vi.fn().mockResolvedValue({+ content: '[Image: cat.png]',+ fileType: 'image/png',+ filename: 'cat.png',+ imageFileId: 'file-1',+ imageUrl: 'https://files.example.com/cat.png',+ isImage: true,+ }),+ });+ const runtime = new LocalSystemExecutionRuntime(service);++ const output = await runtime.readFile({ path: '/tmp/cat.png' });++ expect(output.success).toBe(true);+ // The uploaded reference flows onto state.images so the MessageContent+ // tool-message processor can turn it into an image_url part.+ expect(output.state?.images).toEqual([+ { fileId: 'file-1', mediaType: 'image/png', url: 'https://files.example.com/cat.png' },+ ]);+ expect(output.content).toBe('[Image: cat.png]');+ });++ it('degrades to the text path when the image upload was declined (no url)', async () => {+ const service = createService({+ readLocalFile: vi.fn().mockResolvedValue({+ content: '[Image: cat.png] (upload unavailable — the model cannot view this image)',+ fileType: 'image/png',+ filename: 'cat.png',+ isImage: true,+ }),+ });+ const runtime = new LocalSystemExecutionRuntime(service);++ const output = await runtime.readFile({ path: '/tmp/cat.png' });++ expect(output.success).toBe(true);+ expect(output.state?.images).toBeUndefined();+ expect(output.content).toContain('[Image: cat.png]');+ });++ it('leaves text-file results unchanged (no images on state)', async () => {+ const service = createService({+ readLocalFile: vi.fn().mockResolvedValue({+ content: 'hello',+ fileType: 'txt',+ filename: 'a.txt',+ totalCharCount: 5,+ totalLineCount: 1,+ }),+ });+ const runtime = new LocalSystemExecutionRuntime(service);++ const output = await runtime.readFile({ path: '/tmp/a.txt' });++ expect(output.state?.images).toBeUndefined();+ expect(output.content).toContain('hello');+ });+});diff --git a/packages/tool-runtime/src/types.ts b/packages/tool-runtime/src/types.tsindex 9656f8df312..f6d26115c47 100644--- a/packages/tool-runtime/src/types.ts+++ b/packages/tool-runtime/src/types.ts@@ -114,6 +114,21 @@ export interface ListFilesState {totalCount?: number;}+/**+ * An image produced by a tool result — always an already-uploaded reference+ * (the producer uploads to file storage before emitting; raw base64 must+ * never reach the DB). Same shape as the hetero+ * `HeterogeneousToolResultImage` post-upload.+ */+export interface ToolResultImage {+ /** File record id in the file store. */+ fileId?: string;+ /** MIME type, e.g. `image/png`. */+ mediaType: string;+ /** Durable, fetchable URL. */+ url: string;+}+export interface ReadFileState {/** Character count of the returned content */charCount?: number;@@ -123,6 +138,13 @@ export interface ReadFileState {filename?: string;/** Detected file type (e.g., 'ts', 'md', 'json') */fileType?: string;+ /**+ * Images produced by reading an image file. Carried in `pluginState.images`+ * on the tool message; the MessageContent tool-message processor turns each+ * into an `image_url` part so vision-capable models can actually inspect the+ * file the agent read. Empty/absent for text files.+ */+ images?: ToolResultImage[];/** Line range as tuple [start, end] */loc?: [number, number];path: string;diff --git a/src/store/chat/slices/plugin/actions/pluginTypes.ts b/src/store/chat/slices/plugin/actions/pluginTypes.tsindex 30f2e93fdaa..cef94566599 100644--- a/src/store/chat/slices/plugin/actions/pluginTypes.ts+++ b/src/store/chat/slices/plugin/actions/pluginTypes.ts@@ -65,7 +65,10 @@ export class PluginTypesActionImpl {}if (effectiveSource === 'composio') {- return await this.#get().invokeComposioTypePlugin(id, { ...payload, source: effectiveSource });+ return await this.#get().invokeComposioTypePlugin(id, {+ ...payload,+ source: effectiveSource,+ });}if (effectiveSource === 'lobehubSkill') {