π€― 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
π fix(cli): let lh connect devices read images for vision models (#20971)
YuTengjingc0814c7e7798
diff --git a/apps/cli/src/commands/connect.test.ts b/apps/cli/src/commands/connect.test.tsindex 8dfd68090de..da7b863c716 100644--- a/apps/cli/src/commands/connect.test.ts+++ b/apps/cli/src/commands/connect.test.ts@@ -353,7 +353,13 @@ describe('connect command', () => {type: 'tool_call_request',});- expect(executeToolCall).toHaveBeenCalledWith('readLocalFile', '{"path":"/test"}', undefined);+ // The connected device's credentials ride along so `readFile` can upload images.+ expect(executeToolCall).toHaveBeenCalledWith(+ 'readLocalFile',+ '{"path":"/test"}',+ undefined,+ expect.objectContaining({ token: 'test-token' }),+ );expect(lastSentToolResponse).toEqual({requestId: 'req-1',result: {diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.tsindex ea1215aff15..c635fe7b011 100644--- a/apps/cli/src/commands/connect.ts+++ b/apps/cli/src/commands/connect.ts@@ -517,7 +517,7 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {deps: deviceControlDeps,error,// Read at dispatch time β `auth` may be refreshed mid-session.- getServerUrl: () => auth.serverUrl,+ getAuth: () => auth,info,isDaemonChild,maintenance,@@ -937,7 +937,7 @@ interface GatewayHandlerContext {deps: DeviceControlDeps;error: (msg: string) => void;/** Read at dispatch time β the underlying auth may be refreshed mid-session. */- getServerUrl: () => string;+ getAuth: () => Awaited<ReturnType<typeof resolveToken>>;info: (msg: string) => void;isDaemonChild: boolean;maintenance: CliMaintenance;@@ -955,7 +955,7 @@ function bindGatewayClientHandlers(ctx: GatewayHandlerContext,connectionWorkspaceId?: string,) {- const { deps, error, getServerUrl, info, isDaemonChild, maintenance, recordRequest } = ctx;+ const { deps, error, getAuth, info, isDaemonChild, maintenance, recordRequest } = ctx;// Handle system info requestsclient.on('system_info_request', (request: SystemInfoRequestMessage) => {@@ -984,7 +984,7 @@ function bindGatewayClientHandlers(// slow transport.const startedAt = performance.now();const result = await maintenance- .run(() => executeToolCall(toolCall.apiName, toolCall.arguments, timeout))+ .run(() => executeToolCall(toolCall.apiName, toolCall.arguments, timeout, getAuth())).catch((err: Error) => ({content: '',error: err.message,@@ -1060,7 +1060,7 @@ function bindGatewayClientHandlers(prompt: request.prompt,resumeFallbackSystemContext: request.resumeFallbackSystemContext,resumeSessionId: request.resumeSessionId,- serverUrl: getServerUrl(),+ serverUrl: getAuth().serverUrl,systemContext: request.systemContext,topicId: request.topicId,workspaceId: request.ingestWorkspaceId ?? request.workspaceId ?? connectionWorkspaceId,diff --git a/apps/cli/src/tools/file.ts b/apps/cli/src/tools/file.tsindex f9903620f17..95dfcca95a9 100644--- a/apps/cli/src/tools/file.ts+++ b/apps/cli/src/tools/file.ts@@ -1,9 +1,34 @@+import {+ getLocalImageMimeType,+ type ReadFileParams,+ readLocalFile as readLocalTextFile,+ readLocalImageFile,+ type UploadedImageRecord,+} from '@lobechat/local-file-shell';+export {editLocalFile,globLocalFiles,grepContent,listLocalFiles,- readLocalFile,searchLocalFiles,writeLocalFile,} from '@lobechat/local-file-shell';++/** Uploads a local image to file storage with the connected device's credentials. */+export type ImageUploader = (filePath: string) => Promise<UploadedImageRecord | undefined>;++/**+ * `readFile` for a connected device. Images are uploaded to file storage, as+ * the desktop app does, so vision models can see them instead of hitting+ * "Unsupported binary file type"; every other path reads as text. Without an+ * uploader the image degrades to a placeholder the model can explain.+ */+export const readLocalFile = async (params: ReadFileParams, uploadImage?: ImageUploader) => {+ const imageMimeType = getLocalImageMimeType(params.path);+ if (!imageMimeType) return readLocalTextFile(params);++ return readLocalImageFile(params, imageMimeType, {+ upload: async (filePath) => uploadImage?.(filePath),+ });+};diff --git a/apps/cli/src/tools/index.test.ts b/apps/cli/src/tools/index.test.tsindex d6e2645240e..c162e1d77ed 100644--- a/apps/cli/src/tools/index.test.ts+++ b/apps/cli/src/tools/index.test.ts@@ -9,6 +9,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { executeToolCall } from './index';import * as isolatedWorker from './isolatedWorker';+const { uploadLocalFileMock } = vi.hoisted(() => ({ uploadLocalFileMock: vi.fn() }));++vi.mock('../utils/uploadLocalFile', () => ({ uploadLocalFile: uploadLocalFileMock }));++const auth = { serverUrl: 'https://lobehub.example.com', token: 'jwt', tokenType: 'jwt' as const };+describe('executeToolCall', () => {const tmpDir = path.join(os.tmpdir(), 'cli-tool-dispatch-test-' + process.pid);@@ -34,6 +40,66 @@ describe('executeToolCall', () => {expect((result.state as { content: string }).content).toContain('hello world');});+ describe('readFile on images', () => {+ const jpgBytes = Buffer.from('ffd8ffe000104a464946', 'hex');++ beforeEach(() => {+ uploadLocalFileMock.mockReset();+ });++ it('uploads the image so vision models can see it instead of refusing it as binary', async () => {+ uploadLocalFileMock.mockResolvedValue({+ id: 'file-1',+ url: 'https://files.example.com/a.jpg',+ });+ const filePath = path.join(tmpDir, 'test1.jpg');+ await writeFile(filePath, jpgBytes);++ const result = await executeToolCall(+ 'readFile',+ JSON.stringify({ path: filePath }),+ undefined,+ auth,+ );++ expect(uploadLocalFileMock).toHaveBeenCalledWith(expect.anything(), filePath);+ expect(result.success).toBe(true);+ expect(result.content).toBe('[Image: test1.jpg]');+ expect(result.state).toMatchObject({+ images: [+ { fileId: 'file-1', mediaType: 'image/jpeg', url: 'https://files.example.com/a.jpg' },+ ],+ });+ });++ it('tells the model why it cannot see the image when the upload fails', async () => {+ uploadLocalFileMock.mockRejectedValue(new Error('Not authenticated'));+ const filePath = path.join(tmpDir, 'test1.jpg');+ await writeFile(filePath, jpgBytes);++ const result = await executeToolCall(+ 'readFile',+ JSON.stringify({ path: filePath }),+ undefined,+ auth,+ );++ expect(result.content).toContain('[Image: test1.jpg]');+ expect(result.content).toContain('Not authenticated');+ expect(result.content).not.toContain('Unsupported binary file type');+ });++ it('degrades to a placeholder without credentials instead of uploading', async () => {+ const filePath = path.join(tmpDir, 'test1.jpg');+ await writeFile(filePath, jpgBytes);++ const result = await executeToolCall('readFile', JSON.stringify({ path: filePath }));++ expect(uploadLocalFileMock).not.toHaveBeenCalled();+ expect(result.content).toContain('upload unavailable');+ });+ });+it('should dispatch writeFile', async () => {const filePath = path.join(tmpDir, 'new.txt');diff --git a/apps/cli/src/tools/index.ts b/apps/cli/src/tools/index.tsindex 52510c4618b..955c1ce1abc 100644--- a/apps/cli/src/tools/index.ts+++ b/apps/cli/src/tools/index.ts@@ -1,4 +1,6 @@+import { createLambdaClient } from '../api/client';import { log } from '../utils/logger';+import { uploadLocalFile } from '../utils/uploadLocalFile';import { checkPlatformCapability } from './checkPlatformCapability';import { getAgentProfile } from './getAgentProfile';import { cancelHeteroTask, runHeteroTask } from './heteroTask';@@ -23,6 +25,11 @@ export async function executeToolCall(apiName: string,argsStr: string,timeout?: number,+ /**+ * The connected device's current credentials, read per call so a refreshed+ * token is used. `readFile` uploads images with them.+ */+ auth?: Parameters<typeof createLambdaClient>[0],): Promise<{content: string;error?: string;@@ -49,7 +56,9 @@ export async function executeToolCall(// File/shell tools route through LocalSystemExecutionRuntime so `content` is// the formatted prompt text and `state` carries the structured payload for// client renders β matching the desktop gateway path (PR #15114).- const localResult = await runLocalSystemTool(apiName, finalArgs);+ const localResult = await runLocalSystemTool(apiName, finalArgs, {+ uploadImage: auth && ((filePath) => uploadLocalFile(createLambdaClient(auth), filePath)),+ });if (localResult) {const { error } = localResult;return {diff --git a/apps/cli/src/tools/localSystemRuntime.ts b/apps/cli/src/tools/localSystemRuntime.tsindex 4db6c50a68c..e80714c7e03 100644--- a/apps/cli/src/tools/localSystemRuntime.ts+++ b/apps/cli/src/tools/localSystemRuntime.ts@@ -7,7 +7,14 @@ import { createFileSearchModule } from '@lobechat/local-file-shell';import { type ILocalSystemService, LocalSystemExecutionRuntime } from '@lobechat/tool-runtime';import { CLI_DISPLAY_NAME } from '../constants/identity';-import { editLocalFile, grepContent, listLocalFiles, readLocalFile, writeLocalFile } from './file';+import {+ editLocalFile,+ grepContent,+ type ImageUploader,+ listLocalFiles,+ readLocalFile,+ writeLocalFile,+} from './file';import { getCommandOutput, killCommand, runCommand } from './shell';/**@@ -66,7 +73,18 @@ const localSystemService: ILocalSystemService = {writeFile: writeLocalFile,};-const runtime = new LocalSystemExecutionRuntime(localSystemService);+const createRuntime = (uploadImage?: ImageUploader) =>+ new LocalSystemExecutionRuntime({+ ...localSystemService,+ readLocalFile: (params) => readLocalFile(params, uploadImage),+ });++const defaultRuntime = createRuntime();++export interface LocalSystemToolContext {+ /** Uploads images `readFile` returns, so vision models can see them. */+ uploadImage?: ImageUploader;+}/*** Route file/shell tool calls through `LocalSystemExecutionRuntime` so the@@ -84,7 +102,11 @@ const runtime = new LocalSystemExecutionRuntime(localSystemService);export async function runLocalSystemTool(apiName: string,args: Record<string, any>,+ { uploadImage }: LocalSystemToolContext = {},): Promise<LocalSystemToolOutput | null> {+ // The uploader carries per-call credentials, so it gets its own runtime.+ const runtime = uploadImage ? createRuntime(uploadImage) : defaultRuntime;+// `trustArgsCwd` β args reach the CLI only after the server runtime has// stripped any inbound `cwd` and re-injected the device-bound one, so the// `cwd` in `args` here is server-controlled rather than model-chosen.diff --git a/apps/desktop/src/main/controllers/LocalFileCtr.ts b/apps/desktop/src/main/controllers/LocalFileCtr.tsindex 08f512be60d..83939f2c46e 100644--- a/apps/desktop/src/main/controllers/LocalFileCtr.ts+++ b/apps/desktop/src/main/controllers/LocalFileCtr.ts@@ -76,11 +76,12 @@ import {createLocalFile,editLocalFile,expandTilde,+ getLocalImageMimeType,listLocalFiles,moveLocalFiles,readLocalFile,+ readLocalImageFile,renameLocalFile,- resolveAgainstCwd,writeLocalFile,} from '@lobechat/local-file-shell/file';import type { FileResult, SearchOptions } from '@lobechat/local-file-shell/types';@@ -121,29 +122,6 @@ const formatUploadFailure = ({ kind, reason }: UploadFailure): string => {const SAFE_PATH_PREFIXES = ['/tmp', '/var/tmp'] as const;-/**- * Image extensions `readFile` uploads to file storage instead of refusing as- * binary. The runtime can then route the image to downstream media analysis- * rather than hitting "Unsupported binary file".- *- * AVIF is included for Analyze Media, whose request-boundary normalization- * converts unsupported image formats for its fallback vision model. This does- * not imply native AVIF support across providers. 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> = {- avif: 'image/avif',- 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',@@ -518,79 +496,24 @@ export default class LocalFileCtr extends ControllerModule {// 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];+ // cross IPC and never reach the DB.+ const imageMimeType = getLocalImageMimeType(params.path);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 });-+ return readLocalImageFile(params, imageMimeType, {// Degrade with the real cause so the model can tell a full storage// quota (retrying is pointless) apart from a transient network error.- return buildImageResult(- `[Image: ${filename}] (upload unavailable β ${formatUploadFailure(describeUploadFailure(error))})`,- { createdTime: fileStat.birthtime, modifiedTime: fileStat.mtime },- );- }-- // 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 },- );+ describeUploadError: (error) => {+ logger.warn('Image upload failed:', { error, filePath: params.path });+ return formatUploadFailure(describeUploadFailure(error));+ },+ upload: async (filePath) => {+ const record = await this.app+ .getService(RemoteFileUploadService)+ .uploadLocalFile(filePath);+ if (!record?.url) logger.warn('Image upload returned no record:', { filePath });+ return record;+ },+ });}return readLocalFile(params);diff --git a/packages/local-file-shell/src/file/index.ts b/packages/local-file-shell/src/file/index.tsindex 6cdf0c6379b..c161bf039ae 100644--- a/packages/local-file-shell/src/file/index.ts+++ b/packages/local-file-shell/src/file/index.ts@@ -8,6 +8,8 @@ export type { ListFilesOptions } from './list';export { listLocalFiles } from './list';export { moveLocalFiles } from './move';export { readLocalFile } from './read';+export type { ReadLocalImageFileOptions } from './readImage';+export { getLocalImageMimeType, MAX_IMAGE_READ_BYTES, readLocalImageFile } from './readImage';export { renameLocalFile } from './rename';export { searchLocalFiles } from './search';export { writeLocalFile } from './write';diff --git a/packages/local-file-shell/src/file/readImage.ts b/packages/local-file-shell/src/file/readImage.tsnew file mode 100644index 00000000000..473267ca444--- /dev/null+++ b/packages/local-file-shell/src/file/readImage.ts@@ -0,0 +1,127 @@+import { stat } from 'node:fs/promises';+import path from 'node:path';++import type { ReadFileParams, ReadImageFileResult, UploadedImageRecord } from '../types';+import { resolveAgainstCwd } from './expandTilde';++/**+ * Image extensions `readFile` uploads to file storage instead of refusing as+ * binary. The runtime can then route the image to downstream media analysis+ * rather than hitting "Unsupported binary file".+ *+ * AVIF is included for Analyze Media, whose request-boundary normalization+ * converts unsupported image formats for its fallback vision model. This does+ * not imply native AVIF support across providers. 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> = {+ avif: 'image/avif',+ 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. */+export const MAX_IMAGE_READ_BYTES = 10 * 1024 * 1024;++/** MIME type of a path `readFile` treats as an image, or `undefined` for any other file. */+export const getLocalImageMimeType = (filePath: string): string | undefined =>+ LOCAL_IMAGE_EXT_TO_MIME[path.extname(filePath).toLowerCase().replace('.', '')];++export interface ReadLocalImageFileOptions {+ /**+ * Explains an upload failure to the model. The text follows+ * "upload unavailable β ", so it should say why and what the model can do.+ */+ describeUploadError?: (error: unknown) => string;+ /**+ * Uploads the image at an absolute path to file storage. Returns `undefined`+ * when the host declines, which degrades to a placeholder.+ */+ upload: (filePath: string) => Promise<UploadedImageRecord | undefined>;+}++const defaultDescribeUploadError = (error: unknown): string =>+ `${error instanceof Error ? error.message : String(error)}; the model cannot view this image`;++/**+ * Read an image path for the agent: upload the bytes and return a durable+ * `{ imageFileId, imageUrl }` reference instead of text. Bytes never enter the+ * tool result; the MessageContent processor turns the URL into an `image_url`+ * part for the LLM. Failures degrade to an `[Image: name]` placeholder that+ * tells the model why it cannot see the image, instead of failing the read.+ *+ * Callers check {@link getLocalImageMimeType} first and fall back to+ * `readLocalFile` for every other path.+ */+export async function readLocalImageFile(+ { cwd, path: rawPath }: ReadFileParams,+ mimeType: string,+ { describeUploadError = defaultDescribeUploadError, upload }: ReadLocalImageFileOptions,+): Promise<ReadImageFileResult> {+ const filePath = resolveAgainstCwd(rawPath, cwd) ?? rawPath;+ const filename = path.basename(filePath);++ const buildResult = (+ content: string,+ extra: Partial<ReadImageFileResult> = {},+ ): ReadImageFileResult => ({+ charCount: 0,+ content,+ createdTime: new Date(),+ fileType: mimeType,+ 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 buildResult(`Error accessing or processing file: ${(error as Error).message}`);+ }++ if (!fileStat.isFile()) {+ return buildResult(`Error: Not a regular file: ${filePath}`);+ }++ if (fileStat.size > MAX_IMAGE_READ_BYTES) {+ return buildResult(+ `Error: Image file is too large to preview (${fileStat.size} bytes, limit ${MAX_IMAGE_READ_BYTES}).`,+ );+ }++ const times = { createdTime: fileStat.birthtime, modifiedTime: fileStat.mtime };++ let record: UploadedImageRecord | undefined;+ try {+ record = await upload(filePath);+ } catch (error) {+ return buildResult(+ `[Image: ${filename}] (upload unavailable β ${describeUploadError(error)})`,+ times,+ );+ }++ if (record?.url) {+ return buildResult(`[Image: ${filename}]`, {+ ...times,+ imageFileId: record.id,+ imageUrl: record.url,+ });+ }++ return buildResult(+ `[Image: ${filename}] (upload unavailable β the model cannot view this image)`,+ times,+ );+}diff --git a/packages/local-file-shell/src/types.ts b/packages/local-file-shell/src/types.tsindex 9456882282e..2cae4242bf8 100644--- a/packages/local-file-shell/src/types.ts+++ b/packages/local-file-shell/src/types.ts@@ -149,6 +149,24 @@ export interface ReadFileResult {truncated?: boolean;}+/** Durable reference to an image uploaded to file storage. */+export interface UploadedImageRecord {+ id: string;+ url: string;+}++/**+ * {@link ReadFileResult} for an image path. The bytes are uploaded to file+ * storage instead of being read as text, so a vision model can see the image.+ */+export interface ReadImageFileResult extends ReadFileResult {+ /** File record id of the uploaded image; absent when the upload failed. */+ imageFileId?: string;+ /** Durable URL of the uploaded image; absent when the upload failed. */+ imageUrl?: string;+ isImage: true;+}+export interface WriteFileParams {content: string;/** Working directory a relative `path` resolves against. See {@link ReadFileParams.cwd}. */