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: surface readFile image-upload and analyzeMedia failure reasons to the model (#19977)

Arvin Xu010e5ac96d93
diff --git a/apps/cli/src/utils/uploadLocalFile.test.ts b/apps/cli/src/utils/uploadLocalFile.test.ts
index af28ab2879e..339428b1422 100644
--- a/apps/cli/src/utils/uploadLocalFile.test.ts
+++ b/apps/cli/src/utils/uploadLocalFile.test.ts
@@ -59,4 +59,28 @@ describe('uploadFileBuffer', () => {
pathname: expect.stringMatching(/^files\//),
});
});
+
+ it('names the socket-level cause when the storage PUT fails at the network layer', async () => {
+ const networkError = Object.assign(new TypeError('fetch failed'), {
+ cause: Object.assign(new Error('read ECONNRESET'), { code: 'ECONNRESET' }),
+ });
+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(networkError));
+ const abortS3Upload = vi.fn().mockResolvedValue({ success: true });
+ const client = {
+ file: { checkFileHash: { mutate: vi.fn().mockResolvedValue({ isExist: false }) } },
+ upload: {
+ abortS3Upload: { mutate: abortS3Upload },
+ createS3PreSignedUrl: { mutate: vi.fn().mockResolvedValue('https://s3/presigned') },
+ },
+ } as unknown as Parameters<typeof uploadFileBuffer>[0];
+
+ await expect(
+ uploadFileBuffer(client, {
+ buffer: Buffer.from('file'),
+ fileName: 'shot.png',
+ fileType: 'image/png',
+ }),
+ ).rejects.toThrow('Upload to storage failed: fetch failed (ECONNRESET)');
+ expect(abortS3Upload).toHaveBeenCalled();
+ });
});
diff --git a/apps/cli/src/utils/uploadLocalFile.ts b/apps/cli/src/utils/uploadLocalFile.ts
index 50980237fe9..1dd33c44106 100644
--- a/apps/cli/src/utils/uploadLocalFile.ts
+++ b/apps/cli/src/utils/uploadLocalFile.ts
@@ -68,6 +68,14 @@ export const uploadFileBuffer = async (
body: buffer,
headers: { 'Content-Type': fileType },
method: 'PUT',
+ }).catch((error: unknown) => {
+ // undici only says "fetch failed"; the socket-level cause is what
+ // tells a reset/timeout apart from a DNS or proxy problem.
+ const cause = (error as { cause?: { code?: string; message?: string } })?.cause;
+ const detail = cause?.code || cause?.message;
+ throw new Error(
+ `Upload to storage failed: ${(error as Error)?.message ?? String(error)}${detail ? ` (${detail})` : ''}`,
+ );
});
if (!uploadRes.ok) {
throw new Error(`Upload failed: ${uploadRes.status} ${uploadRes.statusText}`);
diff --git a/apps/desktop/src/main/controllers/LocalFileCtr.ts b/apps/desktop/src/main/controllers/LocalFileCtr.ts
index 3af6f808b2c..8dedd092f8a 100644
--- a/apps/desktop/src/main/controllers/LocalFileCtr.ts
+++ b/apps/desktop/src/main/controllers/LocalFileCtr.ts
@@ -75,7 +75,10 @@ import { dialog, shell } from 'electron';
import ContentSearchService from '@/services/contentSearchSrv';
import FileSearchService from '@/services/fileSearchSrv';
-import RemoteFileUploadService from '@/services/remoteFileUploadSrv';
+import RemoteFileUploadService, {
+ describeUploadFailure,
+ type UploadFailure,
+} from '@/services/remoteFileUploadSrv';
import { createLogger } from '@/utils/logger';
import { netFetch } from '@/utils/net-fetch';
@@ -84,6 +87,23 @@ import { ControllerModule, IpcMethod } from './index';
// Create logger
const logger = createLogger('controllers:LocalFileCtr');
+const formatUploadFailure = ({ kind, reason }: UploadFailure): string => {
+ switch (kind) {
+ case 'storage_quota': {
+ return `the user's LobeHub file storage is full (${reason}), so the model cannot view this image. Retrying will not help; the user needs to free up space in their file library or upgrade their plan`;
+ }
+ case 'network': {
+ return `network error while uploading (${reason}), already retried, so the model cannot view this image. It may work if the file is read again later`;
+ }
+ case 'auth': {
+ return `the desktop app is not signed in to LobeHub (${reason}), so the model cannot view this image`;
+ }
+ default: {
+ return `${reason}; the model cannot view this image`;
+ }
+ }
+};
+
const SAFE_PATH_PREFIXES = ['/tmp', '/var/tmp'] as const;
/**
@@ -486,6 +506,13 @@ export default class LocalFileCtr extends ControllerModule {
logger.warn('Image upload returned no record:', { filePath });
} catch (error) {
logger.warn('Image upload failed:', { error, filePath });
+
+ // 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
diff --git a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.readFile.test.ts b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.readFile.test.ts
index 5295a08b5c0..6351b2eff09 100644
--- a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.readFile.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.readFile.test.ts
@@ -215,6 +215,41 @@ describe('LocalFileCtr β€” readFile / readFiles (real fs)', () => {
expect(result.content).toContain('[Image: failed.png]');
});
+ it('should surface the storage-quota reason instead of a generic placeholder', async () => {
+ mockUploadService.uploadLocalFile.mockRejectedValue(
+ new Error(
+ 'Command failed: lobe-cli.js file upload shot17.png --json id,url\n[ERROR] storage_block:upgrade_required',
+ ),
+ );
+ const filePath = path.join(tmpDir, 'shot17.png');
+ await writeFile(filePath, pngBytes);
+
+ const result = await localFileCtr.readFile({ path: filePath });
+
+ expect(result.imageUrl).toBeUndefined();
+ expect(result.content).toContain('[Image: shot17.png]');
+ expect(result.content).toContain('storage_block:upgrade_required');
+ expect(result.content).toMatch(/file storage is full/i);
+ expect(result.content).toMatch(/retrying will not help/i);
+ });
+
+ it('should tell a network upload failure apart from a full storage', async () => {
+ mockUploadService.uploadLocalFile.mockRejectedValue(
+ new Error(
+ 'Command failed: lobe-cli.js file upload a.png\n[ERROR] fetch failed: ECONNRESET',
+ ),
+ );
+ const filePath = path.join(tmpDir, 'net.png');
+ await writeFile(filePath, pngBytes);
+
+ const result = await localFileCtr.readFile({ path: filePath });
+
+ expect(result.content).toContain('[Image: net.png]');
+ expect(result.content).toMatch(/network/i);
+ expect(result.content).toContain('ECONNRESET');
+ expect(result.content).not.toMatch(/storage is full/i);
+ });
+
it('should return a readable error for a missing image', async () => {
const result = await localFileCtr.readFile({ path: path.join(tmpDir, 'missing.png') });
diff --git a/apps/desktop/src/main/modules/networkProxy/__tests__/socksHttpBridge.test.ts b/apps/desktop/src/main/modules/networkProxy/__tests__/socksHttpBridge.test.ts
new file mode 100644
index 00000000000..ffe4f30969e
--- /dev/null
+++ b/apps/desktop/src/main/modules/networkProxy/__tests__/socksHttpBridge.test.ts
@@ -0,0 +1,101 @@
+import { createServer as createHttpServer, type Server } from 'node:http';
+import { type AddressInfo, connect, createServer, type Server as NetServer } from 'node:net';
+
+import type { NetworkProxySettings } from '@lobechat/electron-client-ipc';
+import { ProxyAgent, request } from 'undici';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { type SocksHttpBridge, startSocksHttpBridge } from '../socksHttpBridge';
+
+vi.mock('@/utils/logger', () => ({
+ createLogger: () => ({ debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() }),
+}));
+
+const listen = async <T extends NetServer | Server>(server: T): Promise<number> => {
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ return (server.address() as AddressInfo).port;
+};
+
+/** Minimal no-auth SOCKS5 server that records every CONNECT destination. */
+const createSocksServer = (destinations: string[]) =>
+ createServer((client) => {
+ client.once('data', () => {
+ client.write(Buffer.from([0x05, 0x00]));
+ client.once('data', (req) => {
+ const atyp = req[3];
+ let host: string;
+ let offset: number;
+ if (atyp === 0x03) {
+ const length = req[4];
+ host = req.subarray(5, 5 + length).toString();
+ offset = 5 + length;
+ } else {
+ host = [...req.subarray(4, 8)].join('.');
+ offset = 8;
+ }
+ const port = req.readUInt16BE(offset);
+ destinations.push(`${host}:${port}`);
+
+ const upstream = connect(port, host, () => {
+ client.write(Buffer.from([0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0]));
+ upstream.pipe(client);
+ client.pipe(upstream);
+ });
+ upstream.on('error', () => client.destroy());
+ client.on('error', () => upstream.destroy());
+ });
+ });
+ });
+
+describe('startSocksHttpBridge', () => {
+ let socksServer: NetServer;
+ let target: Server;
+ let bridge: SocksHttpBridge | undefined;
+ let destinations: string[];
+ let socksConfig: NetworkProxySettings;
+ let targetPort: number;
+
+ beforeEach(async () => {
+ destinations = [];
+ socksServer = createSocksServer(destinations);
+ target = createHttpServer((_req, res) => res.end('hello through socks'));
+ const socksPort = await listen(socksServer);
+ targetPort = await listen(target);
+ socksConfig = {
+ enableProxy: true,
+ proxyPort: String(socksPort),
+ proxyRequireAuth: false,
+ proxyServer: '127.0.0.1',
+ proxyType: 'socks5',
+ };
+ });
+
+ afterEach(async () => {
+ await bridge?.close();
+ bridge = undefined;
+ await new Promise((resolve) => target.close(resolve));
+ await new Promise((resolve) => socksServer.close(resolve));
+ });
+
+ it('tunnels an HTTP-proxy client through the SOCKS5 proxy', async () => {
+ bridge = await startSocksHttpBridge(socksConfig);
+
+ const response = await request(`http://127.0.0.1:${targetPort}/`, {
+ dispatcher: new ProxyAgent({ uri: bridge.url }),
+ });
+
+ expect(response.statusCode).toBe(200);
+ expect(await response.body.text()).toBe('hello through socks');
+ expect(destinations).toEqual([`127.0.0.1:${targetPort}`]);
+ });
+
+ it('refuses clients without the bridge credential', async () => {
+ bridge = await startSocksHttpBridge(socksConfig);
+ const { origin } = new URL(bridge.url);
+
+ await expect(
+ request(`http://127.0.0.1:${targetPort}/`, { dispatcher: new ProxyAgent({ uri: origin }) }),
+ ).rejects.toThrow(/407/);
+ expect(destinations).toEqual([]);
+ });
+});
diff --git a/apps/desktop/src/main/modules/networkProxy/dispatcher.ts b/apps/desktop/src/main/modules/networkProxy/dispatcher.ts
index 7834f55d363..b1d5095de58 100644
--- a/apps/desktop/src/main/modules/networkProxy/dispatcher.ts
+++ b/apps/desktop/src/main/modules/networkProxy/dispatcher.ts
@@ -10,6 +10,26 @@ import { ProxyUrlBuilder } from './urlBuilder';
// Create logger
const logger = createLogger('modules:networkProxy:dispatcher');
+/**
+ * Parse a `socks5://` proxy URL into the fetch-socks proxy list.
+ */
+export const toSocksProxies = (proxyUrl: string): SocksProxies => {
+ const url = new URL(proxyUrl);
+ return [
+ {
+ host: url.hostname,
+ port: parseInt(url.port, 10),
+ type: 5,
+ ...(url.username && url.password
+ ? {
+ password: url.password,
+ userId: url.username,
+ }
+ : {}),
+ },
+ ];
+};
+
/**
* Proxy dispatcher manager
*/
@@ -94,24 +114,8 @@ export class ProxyDispatcherManager {
static createProxyAgent(proxyType: string, proxyUrl: string) {
try {
if (proxyType === 'socks5') {
- // Parse SOCKS5 proxy URL
- const url = new URL(proxyUrl);
- const socksProxies: SocksProxies = [
- {
- host: url.hostname,
- port: parseInt(url.port, 10),
- type: 5,
- ...(url.username && url.password
- ? {
- password: url.password,
- userId: url.username,
- }
- : {}),
- },
- ];
-
// Use fetch-socks to handle SOCKS5 proxy
- return socksDispatcher(socksProxies);
+ return socksDispatcher(toSocksProxies(proxyUrl));
} else {
// undici's ProxyAgent supports http, https
return new ProxyAgent({ uri: proxyUrl });
diff --git a/apps/desktop/src/main/modules/networkProxy/socksHttpBridge.ts b/apps/desktop/src/main/modules/networkProxy/socksHttpBridge.ts
new file mode 100644
index 00000000000..f58325cccfb
--- /dev/null
+++ b/apps/desktop/src/main/modules/networkProxy/socksHttpBridge.ts
@@ -0,0 +1,146 @@
+import { randomBytes, timingSafeEqual } from 'node:crypto';
+import { createServer } from 'node:http';
+import type { AddressInfo, Socket } from 'node:net';
+
+import type { NetworkProxySettings } from '@lobechat/electron-client-ipc';
+import { socksConnector } from 'fetch-socks';
+
+import { createLogger } from '@/utils/logger';
+
+import { toSocksProxies } from './dispatcher';
+import { ProxyUrlBuilder } from './urlBuilder';
+
+const logger = createLogger('modules:networkProxy:socksHttpBridge');
+
+const BRIDGE_USER = 'lobehub';
+
+export interface SocksHttpBridge {
+ close: () => Promise<void>;
+ /** `http://user:[email protected]:<port>`, ready to use as HTTP(S)_PROXY. */
+ url: string;
+}
+
+const parseAuthority = (authority = ''): { hostname: string; port: string } | undefined => {
+ try {
+ const { hostname, port } = new URL(`http://${authority}`);
+ if (!hostname || !port) return undefined;
+ // URL keeps IPv6 literals bracketed; the SOCKS client wants them bare.
+ return { hostname: hostname.replace(/^\[(.*)\]$/, '$1'), port };
+ } catch {
+ return undefined;
+ }
+};
+
+const rejectConnect = (socket: Socket, status: string, headers = '') => {
+ socket.end(`HTTP/1.1 ${status}\r\n${headers}Connection: close\r\n\r\n`);
+};
+
+/**
+ * Loopback HTTP CONNECT proxy that tunnels through the user's SOCKS5 proxy.
+ *
+ * Node's env-proxy mode (`NODE_USE_ENV_PROXY`) only understands HTTP(S)_PROXY,
+ * so a Node child β€” the embedded CLI β€” cannot use a SOCKS5 proxy through
+ * `ALL_PROXY`. Point its HTTP(S)_PROXY at this bridge instead; the SOCKS hop
+ * reuses the same fetch-socks client as the main process dispatcher. The URL
+ * carries a random credential so other local processes cannot borrow the
+ * user's proxy while the bridge is up.
+ */
+export const startSocksHttpBridge = async (
+ config: NetworkProxySettings,
+): Promise<SocksHttpBridge> => {
+ const connect = socksConnector(toSocksProxies(ProxyUrlBuilder.build(config)));
+ const token = randomBytes(24).toString('base64url');
+ const expectedAuth = Buffer.from(
+ `Basic ${Buffer.from(`${BRIDGE_USER}:${token}`).toString('base64')}`,
+ );
+ const sockets = new Set<Socket>();
+
+ const isAuthorized = (header: string | undefined) => {
+ const actual = Buffer.from(header ?? '');
+ return actual.length === expectedAuth.length && timingSafeEqual(actual, expectedAuth);
+ };
+
+ const server = createServer((_request, response) => {
+ // Node's env proxy tunnels plain http:// targets with CONNECT too.
+ response.writeHead(405, { Connection: 'close' }).end();
+ });
+
+ server.on('connection', (socket) => {
+ sockets.add(socket);
+ socket.once('close', () => sockets.delete(socket));
+ });
+
+ server.on('connect', (request, clientSocket: Socket, head: Buffer) => {
+ clientSocket.on('error', () => undefined);
+
+ if (!isAuthorized(request.headers['proxy-authorization'])) {
+ rejectConnect(
+ clientSocket,
+ '407 Proxy Authentication Required',
+ 'Proxy-Authenticate: Basic realm="lobehub"\r\n',
+ );
+ return;
+ }
+
+ const target = parseAuthority(request.url);
+ if (!target) {
+ rejectConnect(clientSocket, '400 Bad Request');
+ return;
+ }
+
+ connect(
+ { hostname: target.hostname, port: target.port, protocol: 'http:' } as Parameters<
+ typeof connect
+ >[0],
+ (error, upstream) => {
+ if (error || !upstream) {
+ logger.warn('SOCKS5 tunnel failed:', {
+ error: error?.message,
+ target: `${target.hostname}:${target.port}`,
+ });
+ rejectConnect(clientSocket, '502 Bad Gateway');
+ return;
+ }
+ if (clientSocket.destroyed) {
+ upstream.destroy();
+ return;
+ }
+
+ const upstreamSocket = upstream as Socket;
+ sockets.add(upstreamSocket);
+ upstreamSocket.once('close', () => sockets.delete(upstreamSocket));
+ upstreamSocket.on('error', () => clientSocket.destroy());
+ clientSocket.on('error', () => upstreamSocket.destroy());
+ clientSocket.once('close', () => upstreamSocket.destroy());
+ upstreamSocket.once('close', () => clientSocket.destroy());
+
+ clientSocket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
+ if (head.length > 0) upstreamSocket.write(head);
+ upstreamSocket.pipe(clientSocket);
+ clientSocket.pipe(upstreamSocket);
+ },
+ );
+ });
+
+ await new Promise<void>((resolve, reject) => {
+ server.once('error', reject);
+ server.listen(0, '127.0.0.1', () => {
+ server.off('error', reject);
+ resolve();
+ });
+ });
+
+ const { port } = server.address() as AddressInfo;
+ let closePromise: Promise<void> | undefined;
+
+ return {
+ close: () => {
+ closePromise ??= new Promise((resolve) => {
+ server.close(() => resolve());
+ for (const socket of sockets) socket.destroy();
+ });
+ return closePromise;
+ },
+ url: `http://${BRIDGE_USER}:${token}@127.0.0.1:${port}`,
+ };
+};
diff --git a/apps/desktop/src/main/services/__tests__/remoteFileUploadSrv.test.ts b/apps/desktop/src/main/services/__tests__/remoteFileUploadSrv.test.ts
index 025d6a7b3ce..7d121e13c44 100644
--- a/apps/desktop/src/main/services/__tests__/remoteFileUploadSrv.test.ts
+++ b/apps/desktop/src/main/services/__tests__/remoteFileUploadSrv.test.ts
@@ -1,8 +1,8 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { type App } from '@/core/App';
-import RemoteFileUploadService from '../remoteFileUploadSrv';
+import RemoteFileUploadService, { describeUploadFailure } from '../remoteFileUploadSrv';
const { execFileMock } = vi.hoisted(() => ({
execFileMock: vi.fn(),
@@ -18,6 +18,21 @@ vi.mock('node:util', () => ({
promisify: (fn: any) => fn,
}));
+const { bridgeCloseMock, startSocksHttpBridgeMock } = vi.hoisted(() => {
+ const bridgeCloseMock = vi.fn(async () => undefined);
+ return {
+ bridgeCloseMock,
+ startSocksHttpBridgeMock: vi.fn(async () => ({
+ close: bridgeCloseMock,
+ url: 'http://lobehub:[email protected]:54321',
+ })),
+ };
+});
+
+vi.mock('@/modules/networkProxy/socksHttpBridge', () => ({
+ startSocksHttpBridge: startSocksHttpBridgeMock,
+}));
+
vi.mock('@/modules/cliEmbedding', () => ({
resolveCliScript: () => '/app/resources/bin/lobe-cli.js',
}));
@@ -27,10 +42,83 @@ const mockRemoteServerConfigCtr = {
getRemoteServerUrl: vi.fn(),
};
+const mockStoreManager = {
+ get: vi.fn(),
+};
+
const mockApp = {
getController: vi.fn(() => mockRemoteServerConfigCtr),
+ storeManager: mockStoreManager,
} as unknown as App;
+/** The shape `execFile` rejects with when the child exits non-zero. */
+const execFileError = (filePath: string, stderr: string) =>
+ Object.assign(
+ new Error(
+ `Command failed: /Applications/LobeHub.app/Contents/MacOS/LobeHub /app/resources/bin/lobe-cli.js file upload ${filePath} --json id,url\n${stderr}`,
+ ),
+ { code: 1, killed: false, signal: null, stderr, stdout: '' },
+ );
+
+describe('describeUploadFailure', () => {
+ it('ignores the command line when classifying β€” a path is not an error', () => {
+ const failure = describeUploadFailure(
+ execFileError('/tmp/network-diagram.png', '[ERROR] Unsupported file type: image/x-foo\n'),
+ );
+
+ expect(failure).toEqual({ kind: 'unknown', reason: 'Unsupported file type: image/x-foo' });
+ });
+
+ it('does not read auth keywords out of the uploaded path', () => {
+ const failure = describeUploadFailure(
+ execFileError('/Users/me/login/401.png', '[ERROR] Unsupported file type: image/x-foo\n'),
+ );
+
+ expect(failure.kind).toBe('unknown');
+ });
+
+ it('does not read network keywords out of a path the CLI echoes back', () => {
+ const failure = describeUploadFailure(
+ execFileError(
+ '/tmp/network-timeout.png',
+ '[ERROR] File not found: /tmp/network-timeout.png\n',
+ ),
+ );
+
+ expect(failure).toEqual({
+ kind: 'unknown',
+ reason: 'File not found: /tmp/network-timeout.png',
+ });
+ });
+
+ it('still classifies the real CLI network error line', () => {
+ const failure = describeUploadFailure(
+ execFileError(
+ '/tmp/cat.png',
+ '[ERROR] Upload to storage failed: fetch failed (ECONNRESET)\n',
+ ),
+ );
+
+ expect(failure).toEqual({
+ kind: 'network',
+ reason: 'Upload to storage failed: fetch failed (ECONNRESET)',
+ });
+ });
+
+ it('still classifies storage quota and auth failures', () => {
+ expect(
+ describeUploadFailure(
+ execFileError('/tmp/cat.png', '[ERROR] storage_block:upgrade_required\n'),
+ ),
+ ).toEqual({ kind: 'storage_quota', reason: 'storage_block:upgrade_required' });
+ expect(
+ describeUploadFailure(
+ execFileError('/tmp/cat.png', '[ERROR] No authentication found. Run `lh login`.\n'),
+ ).kind,
+ ).toBe('auth');
+ });
+});
+
describe('RemoteFileUploadService.uploadLocalFile', () => {
let service: RemoteFileUploadService;
@@ -38,6 +126,7 @@ describe('RemoteFileUploadService.uploadLocalFile', () => {
vi.clearAllMocks();
mockRemoteServerConfigCtr.getRemoteServerUrl.mockResolvedValue('https://server.example.com/');
mockRemoteServerConfigCtr.getAccessToken.mockResolvedValue('token-abc');
+ mockStoreManager.get.mockReturnValue(undefined);
service = new RemoteFileUploadService(mockApp);
});
@@ -86,6 +175,242 @@ describe('RemoteFileUploadService.uploadLocalFile', () => {
expect(await service.uploadLocalFile('/tmp/none.png')).toBeUndefined();
});
+ it('forwards the in-app network proxy to the `lh file upload` child process', async () => {
+ mockStoreManager.get.mockImplementation((key: string) =>
+ key === 'networkProxy'
+ ? { enableProxy: true, proxyPort: '7890', proxyServer: '127.0.0.1', proxyType: 'http' }
+ : undefined,
+ );
+ execFileMock.mockResolvedValue({
+ stdout: JSON.stringify({ id: 'file-3', url: 'https://files.example.com/c.png' }),
+ });
+
+ await service.uploadLocalFile('/tmp/cat.png');
+
+ const [, , opts] = execFileMock.mock.calls[0];
+ expect(opts.env.HTTPS_PROXY).toBe('http://127.0.0.1:7890');
+ expect(opts.env.HTTP_PROXY).toBe('http://127.0.0.1:7890');
+ // Node's fetch only honours HTTP(S)_PROXY when env-proxy mode is on.
+ expect(opts.env.NODE_USE_ENV_PROXY).toBe('1');
+ });
+
+ it('bridges a SOCKS5 proxy to the child, which only honours HTTP(S)_PROXY', async () => {
+ const socksConfig = {
+ enableProxy: true,
+ proxyBypass: 'localhost',
+ proxyPort: '1080',
+ proxyRequireAuth: false,
+ proxyServer: '127.0.0.1',
+ proxyType: 'socks5',
+ };
+ mockStoreManager.get.mockImplementation((key: string) =>
+ key === 'networkProxy' ? socksConfig : undefined,
+ );
+ execFileMock.mockResolvedValue({
+ stdout: JSON.stringify({ id: 'file-5', url: 'https://files.example.com/e.png' }),
+ });
+
+ await service.uploadLocalFile('/tmp/e.png');
+
+ expect(startSocksHttpBridgeMock).toHaveBeenCalledWith(socksConfig);
+ const [, , opts] = execFileMock.mock.calls[0];
+ expect(opts.env.HTTPS_PROXY).toBe('http://lobehub:[email protected]:54321');
+ expect(opts.env.HTTP_PROXY).toBe('http://lobehub:[email protected]:54321');
+ expect(opts.env.NO_PROXY).toBe('localhost');
+ expect(opts.env.NODE_USE_ENV_PROXY).toBe('1');
+ expect(bridgeCloseMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('closes the SOCKS5 bridge when the upload fails', async () => {
+ mockStoreManager.get.mockImplementation((key: string) =>
+ key === 'networkProxy'
+ ? { enableProxy: true, proxyPort: '1080', proxyServer: '127.0.0.1', proxyType: 'socks5' }
+ : undefined,
+ );
+ execFileMock.mockRejectedValue(
+ execFileError('/tmp/f.png', '[ERROR] storage_block:upgrade_required\n'),
+ );
+
+ await expect(service.uploadLocalFile('/tmp/f.png')).rejects.toThrow();
+ expect(bridgeCloseMock).toHaveBeenCalledTimes(1);
+ });
+
+ describe('with proxy variables inherited from the parent environment', () => {
+ const INHERITED = {
+ all_proxy: 'socks5://inherited-all:1080',
+ http_proxy: 'http://inherited-lower:3128',
+ https_proxy: 'http://inherited-lower:3128',
+ no_proxy: '*',
+ };
+ let saved: Record<string, string | undefined>;
+
+ beforeEach(() => {
+ saved = Object.fromEntries(Object.keys(INHERITED).map((key) => [key, process.env[key]]));
+ Object.assign(process.env, INHERITED);
+ });
+
+ afterEach(() => {
+ for (const [key, value] of Object.entries(saved)) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ });
+
+ // Node's env-proxy mode reads `http_proxy || HTTP_PROXY` (and the same
+ // for https_proxy / no_proxy), so an inherited lowercase value would win
+ // over the in-app proxy unless both cases are set.
+ it('overrides lowercase proxy variables with the in-app HTTP proxy', async () => {
+ mockStoreManager.get.mockImplementation((key: string) =>
+ key === 'networkProxy'
+ ? {
+ enableProxy: true,
+ proxyBypass: 'localhost',
+ proxyPort: '7890',
+ proxyServer: '127.0.0.1',
+ proxyType: 'http',
+ }
+ : undefined,
+ );
+ execFileMock.mockResolvedValue({
+ stdout: JSON.stringify({ id: 'file-6', url: 'https://files.example.com/g.png' }),
+ });
+
+ await service.uploadLocalFile('/tmp/g.png');
+
+ const [, , opts] = execFileMock.mock.calls[0];
+ expect(opts.env.http_proxy).toBe('http://127.0.0.1:7890');
+ expect(opts.env.https_proxy).toBe('http://127.0.0.1:7890');
+ expect(opts.env.HTTP_PROXY).toBe('http://127.0.0.1:7890');
+ expect(opts.env.HTTPS_PROXY).toBe('http://127.0.0.1:7890');
+ expect(opts.env.no_proxy).toBe('localhost');
+ expect(opts.env.NO_PROXY).toBe('localhost');
+ expect(opts.env.all_proxy).toBeUndefined();
+ });
+
+ it('overrides lowercase proxy variables with the SOCKS5 bridge', async () => {
+ mockStoreManager.get.mockImplementation((key: string) =>
+ key === 'networkProxy'
+ ? { enableProxy: true, proxyPort: '1080', proxyServer: '127.0.0.1', proxyType: 'socks5' }
+ : undefined,
+ );
+ execFileMock.mockResolvedValue({
+ stdout: JSON.stringify({ id: 'file-7', url: 'https://files.example.com/h.png' }),
+ });
+
+ await service.uploadLocalFile('/tmp/h.png');
+
+ const [, , opts] = execFileMock.mock.calls[0];
+ expect(opts.env.http_proxy).toBe('http://lobehub:[email protected]:54321');
+ expect(opts.env.https_proxy).toBe('http://lobehub:[email protected]:54321');
+ // No bypass configured in-app β€” an inherited `no_proxy=*` must not
+ // silently route every request around the bridge.
+ expect(opts.env.no_proxy).toBeUndefined();
+ expect(opts.env.NO_PROXY).toBeUndefined();
+ expect(opts.env.all_proxy).toBeUndefined();
+ expect(opts.env.ALL_PROXY).toBeUndefined();
+ });
+
+ it('leaves inherited proxy variables alone when the in-app proxy is off', async () => {
+ execFileMock.mockResolvedValue({
+ stdout: JSON.stringify({ id: 'file-8', url: 'https://files.example.com/i.png' }),
+ });
+
+ await service.uploadLocalFile('/tmp/i.png');
+
+ const [, , opts] = execFileMock.mock.calls[0];
+ expect(opts.env.http_proxy).toBe('http://inherited-lower:3128');
+ expect(opts.env.no_proxy).toBe('*');
+ });
+ });
+
+ describe('upload deadline', () => {
+ // readFile's client deadline is 30s; the upload (all attempts included)
+ // must settle before it so the model gets the fallback, not a timeout.
+ let now: number;
+
+ beforeEach(() => {
+ now = 1_000_000;
+ vi.spyOn(Date, 'now').mockImplementation(() => now);
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('caps every attempt inside the readFile deadline', async () => {
+ execFileMock.mockResolvedValue({
+ stdout: JSON.stringify({ id: 'file-9', url: 'https://files.example.com/j.png' }),
+ });
+
+ await service.uploadLocalFile('/tmp/j.png');
+
+ const [, , opts] = execFileMock.mock.calls[0];
+ expect(opts.timeout).toBeLessThan(30_000);
+ });
+
+ it('does not start a retry that cannot finish before the deadline', async () => {
+ execFileMock.mockImplementation(async () => {
+ // The first attempt fails late β€” 20s in.
+ now += 20_000;
+ throw new Error('[ERROR] fetch failed: ECONNRESET');
+ });
+
+ await expect(service.uploadLocalFile('/tmp/k.png')).rejects.toThrow('ECONNRESET');
+ expect(execFileMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('gives a retry only the time left in the budget', async () => {
+ execFileMock
+ .mockImplementationOnce(async () => {
+ now += 5000;
+ throw new Error('[ERROR] fetch failed: ECONNRESET');
+ })
+ .mockResolvedValue({
+ stdout: JSON.stringify({ id: 'file-10', url: 'https://files.example.com/l.png' }),
+ });
+
+ await service.uploadLocalFile('/tmp/l.png');
+
+ expect(execFileMock).toHaveBeenCalledTimes(2);
+ const [, , second] = execFileMock.mock.calls[1];
+ // The retry starts 5s in and must still end before readFile's deadline.
+ expect(5000 + second.timeout).toBeLessThan(30_000);
+ });
+ });
+
+ it('does not retry a non-network failure whose path mentions "network"', async () => {
+ execFileMock.mockRejectedValue(
+ execFileError('/tmp/network-diagram.png', '[ERROR] Unsupported file type: image/x-foo\n'),
+ );
+
+ await expect(service.uploadLocalFile('/tmp/network-diagram.png')).rejects.toThrow(
+ 'Unsupported file type',
+ );
+ expect(execFileMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('retries a transient network failure', async () => {
+ execFileMock
+ .mockRejectedValueOnce(new Error('[ERROR] fetch failed: ECONNRESET'))
+ .mockResolvedValue({
+ stdout: JSON.stringify({ id: 'file-4', url: 'https://files.example.com/d.png' }),
+ });
+
+ const record = await service.uploadLocalFile('/tmp/d.png');
+
+ expect(record).toEqual({ id: 'file-4', url: 'https://files.example.com/d.png' });
+ expect(execFileMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not retry a storage quota rejection', async () => {
+ execFileMock.mockRejectedValue(new Error('[ERROR] storage_block:upgrade_required'));
+
+ await expect(service.uploadLocalFile('/tmp/full.png')).rejects.toThrow(
+ 'storage_block:upgrade_required',
+ );
+ expect(execFileMock).toHaveBeenCalledTimes(1);
+ });
+
it('propagates CLI failures (non-zero exit) to the caller', async () => {
execFileMock.mockRejectedValue(new Error('No authentication found'));
diff --git a/apps/desktop/src/main/services/remoteFileUploadSrv.ts b/apps/desktop/src/main/services/remoteFileUploadSrv.ts
index ebfe7195619..5b2b67703af 100644
--- a/apps/desktop/src/main/services/remoteFileUploadSrv.ts
+++ b/apps/desktop/src/main/services/remoteFileUploadSrv.ts
@@ -4,19 +4,123 @@ import { promisify } from 'node:util';
import RemoteServerConfigCtr from '@/controllers/RemoteServerConfigCtr';
import { resolveCliScript } from '@/modules/cliEmbedding';
+import { buildProxyEnv } from '@/modules/networkProxy/envBuilder';
+import { type SocksHttpBridge, startSocksHttpBridge } from '@/modules/networkProxy/socksHttpBridge';
import { createLogger } from '@/utils/logger';
import { ServiceModule } from './index';
const logger = createLogger('services:RemoteFileUploadService');
-const UPLOAD_TIMEOUT_MS = 60_000;
+/**
+ * Budget for the whole upload, retries included. readFile runs under a 30s
+ * client deadline; the upload must settle before it so the model gets the
+ * degraded `[Image: …] (upload unavailable β€” …)` result rather than a
+ * `client_executor_timeout`. `execFile` kills the child when its share runs
+ * out, so nothing keeps uploading after the tool call has returned.
+ */
+const UPLOAD_DEADLINE_MS = 25_000;
+const UPLOAD_MAX_ATTEMPTS = 3;
+const UPLOAD_RETRY_BASE_DELAY_MS = 300;
+/** Not worth starting an attempt with less time than this left. */
+const UPLOAD_MIN_ATTEMPT_MS = 5000;
+
+/**
+ * Proxy variables Node's env-proxy mode reads. Lowercase takes precedence
+ * (`http_proxy || HTTP_PROXY`), so both cases must be set β€” or cleared β€” for
+ * the in-app proxy to win over whatever the desktop process inherited.
+ */
+const PROXY_ENV_KEYS = ['HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'NO_PROXY'] as const;
+
+const withProxyEnv = (
+ base: NodeJS.ProcessEnv,
+ proxyEnv: Record<string, string>,
+): NodeJS.ProcessEnv => {
+ if (Object.keys(proxyEnv).length === 0) return { ...base };
+
+ const env: NodeJS.ProcessEnv = { ...base, NODE_USE_ENV_PROXY: '1' };
+ for (const key of PROXY_ENV_KEYS) {
+ const value = proxyEnv[key];
+ for (const name of [key, key.toLowerCase()]) {
+ if (value === undefined) delete env[name];
+ else env[name] = value;
+ }
+ }
+ return env;
+};
export interface UploadedFileRecord {
id: string;
url: string;
}
+export type UploadFailureKind = 'auth' | 'network' | 'storage_quota' | 'unknown';
+
+export interface UploadFailure {
+ kind: UploadFailureKind;
+ /** The CLI's own error line, e.g. `storage_block:upgrade_required`. */
+ reason: string;
+}
+
+const MAX_REASON_LENGTH = 300;
+
+const NETWORK_ERROR_PATTERN =
+ /fetch failed|network|socket hang up|timed? ?out|econnreset|econnrefused|etimedout|enotfound|eai_again|epipe|und_err|upload failed: 5\d\d/i;
+const AUTH_ERROR_PATTERN = /unauthori[sz]ed|no authentication|not logged in|\blogin\b|\b401\b/i;
+
+const COMMAND_LINE_PREFIX = 'Command failed:';
+
+/**
+ * Absolute paths (the uploaded file echoed back in e.g. `File not found: …`)
+ * are data, not error text β€” `/tmp/network-diagram.png` is not a network error.
+ */
+const PATH_TOKEN_PATTERN = /(?<=^|[\s"'(:=])(?:~|[a-z]:)?[/\\][^\s"')]*/gi;
+
+/**
+ * Reduce a failed `lh file upload` run to a reason the model can act on. The
+ * CLI prints `[ERROR] <message>` on stderr and exits 1; `execFile` folds that
+ * into `Command failed: <cmd>\n<stderr>`. Only the CLI's own error line (and
+ * the errno code, if any) is classified β€” never the command line, which
+ * carries the file path.
+ */
+export const describeUploadFailure = (error: unknown): UploadFailure => {
+ const raw = error as {
+ code?: number | string;
+ killed?: boolean;
+ message?: string;
+ signal?: string;
+ stderr?: string;
+ };
+
+ if (raw?.killed && raw.signal) {
+ return { kind: 'network', reason: 'upload timed out' };
+ }
+
+ const output = raw?.stderr?.trim() ? raw.stderr : (raw?.message ?? String(error));
+ const errorLine = output
+ // eslint-disable-next-line no-control-regex
+ .replaceAll(/\u001B\[[\d;]*m/g, '')
+ .split('\n')
+ .map((line) => line.trim())
+ .findLast((line) => line && !line.startsWith(COMMAND_LINE_PREFIX));
+ const reason = (errorLine?.replace(/^.*?\[ERROR\]\s*/, '') || 'unknown error').slice(
+ 0,
+ MAX_REASON_LENGTH,
+ );
+
+ const classifiable = [
+ reason.replaceAll(PATH_TOKEN_PATTERN, ''),
+ typeof raw?.code === 'string' ? raw.code : '',
+ ].join(' ');
+
+ const storageBlock = classifiable.match(/storage_block:[\w-]+/);
+ if (storageBlock) return { kind: 'storage_quota', reason: storageBlock[0] };
+ if (AUTH_ERROR_PATTERN.test(classifiable)) return { kind: 'auth', reason };
+ if (NETWORK_ERROR_PATTERN.test(classifiable)) return { kind: 'network', reason };
+
+ return { kind: 'unknown', reason };
+};
+
/**
* 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
@@ -31,8 +135,37 @@ export interface UploadedFileRecord {
*/
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 deadline = Date.now() + UPLOAD_DEADLINE_MS;
+
+ // The in-app proxy only covers the main process's undici dispatcher; the
+ // CLI child needs it as env, plus env-proxy mode so its fetch honours it.
+ // Env-proxy mode only reads HTTP(S)_PROXY, so a SOCKS5 proxy is exposed
+ // to the child through a loopback HTTP CONNECT bridge.
+ const proxyConfig = this.app.storeManager.get('networkProxy');
+ const proxyEnv = buildProxyEnv(proxyConfig);
+ let socksBridge: SocksHttpBridge | undefined;
+ if (proxyEnv.ALL_PROXY && proxyConfig?.proxyType === 'socks5') {
+ socksBridge = await startSocksHttpBridge(proxyConfig);
+ delete proxyEnv.ALL_PROXY;
+ proxyEnv.HTTP_PROXY = socksBridge.url;
+ proxyEnv.HTTPS_PROXY = socksBridge.url;
+ }
+ const env = withProxyEnv(process.env, proxyEnv);
+ env.ELECTRON_RUN_AS_NODE = '1';
+
+ try {
+ return await this.uploadWithEnv(filePath, env, deadline);
+ } finally {
+ await socksBridge?.close();
+ }
+ }
+
+ private async uploadWithEnv(
+ filePath: string,
+ env: NodeJS.ProcessEnv,
+ deadline: number,
+ ): Promise<UploadedFileRecord | undefined> {
const remoteCtr = this.app.getController(RemoteServerConfigCtr);
if (remoteCtr) {
const [token, serverUrl] = await Promise.all([
@@ -45,11 +178,7 @@ export default class RemoteFileUploadService extends ServiceModule {
}
}
- const { stdout } = await promisify(execFile)(
- process.execPath,
- [resolveCliScript(), 'file', 'upload', filePath, '--json', 'id,url'],
- { env, timeout: UPLOAD_TIMEOUT_MS },
- );
+ const stdout = await this.runUploadWithRetry(filePath, env, deadline);
const record = JSON.parse(stdout.trim()) as Partial<UploadedFileRecord>;
if (!record?.id || !record.url) {
@@ -59,4 +188,44 @@ export default class RemoteFileUploadService extends ServiceModule {
return { id: record.id, url: record.url };
}
+
+ /**
+ * Retry only transient network failures (a flaky PUT to object storage);
+ * quota, auth and validation rejections fail the same way every time.
+ * Every attempt β€” and the pause before it β€” comes out of one shared
+ * {@link UPLOAD_DEADLINE_MS} budget.
+ */
+ private async runUploadWithRetry(
+ filePath: string,
+ env: NodeJS.ProcessEnv,
+ deadline: number,
+ ): Promise<string> {
+ for (let attempt = 1; ; attempt++) {
+ try {
+ const { stdout } = await promisify(execFile)(
+ process.execPath,
+ [resolveCliScript(), 'file', 'upload', filePath, '--json', 'id,url'],
+ { env, timeout: Math.max(deadline - Date.now(), 1) },
+ );
+ return stdout;
+ } catch (error) {
+ const failure = describeUploadFailure(error);
+ const retryDelay = UPLOAD_RETRY_BASE_DELAY_MS * attempt;
+ if (
+ failure.kind !== 'network' ||
+ attempt >= UPLOAD_MAX_ATTEMPTS ||
+ deadline - Date.now() - retryDelay < UPLOAD_MIN_ATTEMPT_MS
+ ) {
+ throw error;
+ }
+
+ logger.warn('Image upload failed, retrying:', {
+ attempt,
+ filePath,
+ reason: failure.reason,
+ });
+ await new Promise((resolve) => setTimeout(resolve, retryDelay));
+ }
+ }
+ }
}
diff --git a/apps/server/src/services/toolExecution/__tests__/index.test.ts b/apps/server/src/services/toolExecution/__tests__/index.test.ts
index 1132a6a9298..a1571774168 100644
--- a/apps/server/src/services/toolExecution/__tests__/index.test.ts
+++ b/apps/server/src/services/toolExecution/__tests__/index.test.ts
@@ -25,6 +25,37 @@ vi.mock('@/server/services/deviceGateway/scopedDevices', () => ({
}));
describe('ToolExecutionService', () => {
+ it('keeps a readable content when a runtime throws a plain budget error object', async () => {
+ // The lobehub provider rejects with a plain object (not an Error) whose
+ // message is nested under `error.message`.
+ const budgetError = {
+ budget: { availableCredits: 0, requiredCredits: 1219, shortfallCredits: 1219 },
+ error: { message: 'Budget exceeded' },
+ errorType: 'InsufficientBudgetForModel',
+ provider: 'lobehub',
+ };
+ const service = new ToolExecutionService({
+ builtinToolsExecutor: { execute: vi.fn().mockRejectedValue(budgetError) } as any,
+ mcpService: {} as any,
+ });
+
+ const result = await service.executeTool(
+ {
+ apiName: 'analyzeMedia',
+ arguments: '{}',
+ id: 'call_budget',
+ identifier: 'lobe-agent',
+ type: 'builtin',
+ },
+ { toolManifestMap: {} },
+ );
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('Budget exceeded');
+ expect(result.content).toContain('InsufficientBudgetForModel');
+ expect(result.error).toMatchObject({ errorType: 'InsufficientBudgetForModel' });
+ });
+
it('keeps a failed command HTTP status as command output', async () => {
const output = 'curl: (22) The requested URL returned error: 403';
const service = new ToolExecutionService({
diff --git a/apps/server/src/services/toolExecution/index.ts b/apps/server/src/services/toolExecution/index.ts
index e3650b5ba95..90e18697c70 100644
--- a/apps/server/src/services/toolExecution/index.ts
+++ b/apps/server/src/services/toolExecution/index.ts
@@ -90,6 +90,40 @@ const normalizeExecutionError = (error: unknown, fallbackMessage: string) => {
return { code: normalized.code, kind: normalized.kind, message };
};
+/**
+ * Readable text for a thrown tool failure. Model runtimes reject with plain
+ * objects (e.g. `{ errorType: 'InsufficientBudgetForModel', error: { message } }`)
+ * that have no top-level `message`; reading only `.message` turned those into
+ * an undefined tool result, which the model then saw as `<empty_content>`.
+ */
+const getThrownErrorText = (error: unknown): string => {
+ if (typeof error === 'string') return error;
+ if (error instanceof Error) return error.message || error.name;
+ if (!error || typeof error !== 'object') return String(error);
+
+ const raw = error as {
+ error?: { message?: unknown };
+ errorType?: unknown;
+ message?: unknown;
+ type?: unknown;
+ };
+ const message = [raw.message, raw.error?.message].find(
+ (value): value is string => typeof value === 'string' && value.length > 0,
+ );
+ const errorType = [raw.errorType, raw.type].find(
+ (value): value is string => typeof value === 'string' && value.length > 0,
+ );
+
+ if (message && errorType) return `${errorType}: ${message}`;
+ if (message || errorType) return (message || errorType)!;
+
+ try {
+ return JSON.stringify(error);
+ } catch {
+ return 'Unknown tool execution error';
+ }
+};
+
export class ToolExecutionService {
private builtinToolsExecutor: BuiltinToolsExecutor;
private mcpService: MCPService;
@@ -194,7 +228,7 @@ export class ToolExecutionService {
} catch (error) {
const executionTime = Date.now() - startTime;
log('Error executing tool %s:%s: %O', identifier, apiName, error);
- const errorMessage = (error as Error).message;
+ const errorMessage = getThrownErrorText(error);
const denial = getToolAccessDeniedError(error, errorMessage);
const content = denial ? JSON.stringify({ error: denial }) : errorMessage;
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 30a7c11b789..1fbcd213db4 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts
@@ -218,6 +218,41 @@ describe('lobeAgentRuntime', () => {
expect([...pixel.subarray(0, 3)]).toEqual([255, 255, 255]);
});
+ it('should explain that media analysis needs LobeHub credits when the budget is exhausted', async () => {
+ mockChat.mockRejectedValueOnce({
+ budget: { availableCredits: 0, requiredCredits: 1219, shortfallCredits: 1219 },
+ error: { message: 'Budget exceeded' },
+ errorType: 'InsufficientBudgetForModel',
+ provider: 'test-provider',
+ });
+ const runtime = lobeAgentRuntime.factory(baseContext);
+
+ const result = await runtime.analyzeMedia({
+ question: 'what is this?',
+ urls: ['https://example.com/image.png'],
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toMatchObject({ code: 'InsufficientBudgetForModel' });
+ expect(result.content).toContain('credits');
+ expect(result.content).toContain('test-provider/vision-model');
+ expect(result.content).toMatch(/own API key/i);
+ });
+
+ it('should reject loopback media urls before calling the multimodal model', async () => {
+ const runtime = lobeAgentRuntime.factory(baseContext);
+
+ const result = await runtime.analyzeMedia({
+ question: 'what is this?',
+ urls: ['http://127.0.0.1:8899/D.jpg'],
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('local or private network address');
+ expect(mockChat).not.toHaveBeenCalled();
+ expect(mockImageUrlToBase64).not.toHaveBeenCalled();
+ });
+
it('should detect suffixless images after downloading without transcoding supported formats', async () => {
const runtime = lobeAgentRuntime.factory(baseContext);
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts
index 1aaf97baf30..dfa856cea76 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts
@@ -23,7 +23,7 @@ import type { LobeChatDatabase } from '@lobechat/database';
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 { ChatErrorType, RequestTrigger } from '@lobechat/types';
import { nanoid } from '@lobechat/utils';
import { parseDataUri } from '@lobechat/utils/uriParser';
@@ -68,6 +68,24 @@ const buildError = (content: string, code: string): BuiltinServerRuntimeOutput =
success: false,
});
+/**
+ * Quota rejections from the configured multimodal provider. analyzeMedia always
+ * runs on the platform-configured model, so a user chatting with their own API
+ * key can still hit the LobeHub credit budget here.
+ */
+const CREDIT_ERROR_TYPES = new Set<string>([
+ ChatErrorType.FreePlanLimit,
+ ChatErrorType.InsufficientBudgetForModel,
+ ChatErrorType.SubscriptionPlanLimit,
+]);
+
+const getCreditErrorType = (error: unknown): string | undefined => {
+ if (!error || typeof error !== 'object') return;
+ const errorType = (error as { errorType?: unknown }).errorType;
+
+ return typeof errorType === 'string' && CREDIT_ERROR_TYPES.has(errorType) ? errorType : undefined;
+};
+
const BASE64_CONTENT_PATTERN = /^[A-Z\d+/]+={0,2}$/i;
const MAX_INLINE_IMAGE_PIXELS = 25_000_000;
/**
@@ -505,24 +523,36 @@ class LobeAgentExecutionRuntime {
stream: false,
} satisfies ChatStreamPayload;
- const response = await runtime.chat(payload, {
- callback: {
- onCompletion: (data) => {
- usage = data.usage;
- },
- onContentPart: (part) => {
- if (part.partType === 'text') content += part.content;
+ try {
+ const response = await runtime.chat(payload, {
+ callback: {
+ onCompletion: (data) => {
+ usage = data.usage;
+ },
+ onContentPart: (part) => {
+ if (part.partType === 'text') content += part.content;
+ },
+ onText: (text) => {
+ content += text;
+ },
},
- onText: (text) => {
- content += text;
+ metadata: {
+ trigger: RequestTrigger.MultimodalAnalysis,
},
- },
- metadata: {
- trigger: RequestTrigger.MultimodalAnalysis,
- },
- });
+ });
- await consumeStreamUntilDone(response);
+ await consumeStreamUntilDone(response);
+ } catch (error) {
+ const creditErrorType = getCreditErrorType(error);
+ if (!creditErrorType) throw error;
+
+ return buildError(
+ `Media analysis could not run: it uses the platform model "${provider}/${model}", which is billed to the user's LobeHub credits, and those credits are exhausted (${creditErrorType}). ` +
+ "The user's own API key for the chat model is not used by this tool, so retrying will not help. " +
+ 'Tell the user to top up or upgrade their LobeHub plan, or to switch the conversation to a vision-capable model on their own API key.',
+ creditErrorType,
+ );
+ }
return {
content: content.trim(),
diff --git a/packages/builtin-tool-lobe-agent/src/media.test.ts b/packages/builtin-tool-lobe-agent/src/media.test.ts
index 2e092982889..e0bcf8afd80 100644
--- a/packages/builtin-tool-lobe-agent/src/media.test.ts
+++ b/packages/builtin-tool-lobe-agent/src/media.test.ts
@@ -29,7 +29,7 @@ describe('media', () => {
'https://example.com/image.png',
'http://example.com/video.mp4',
'data:audio/mpeg;base64,abcd',
- 'data:image/png;base64,abcd',
+ 'data:image/png;base64,iVBORw0KGgo=',
'data:video/mp4;base64,abcd',
'data:text/plain;base64,abcd',
'ftp://example.com/image.png',
@@ -41,7 +41,7 @@ describe('media', () => {
'https://example.com/image.png',
'http://example.com/video.mp4',
'data:audio/mpeg;base64,abcd',
- 'data:image/png;base64,abcd',
+ 'data:image/png;base64,iVBORw0KGgo=',
'data:video/mp4;base64,abcd',
],
});
@@ -68,6 +68,34 @@ describe('media', () => {
);
});
+ it('should reject media urls the analysis model can never fetch', () => {
+ const pngDataUrl =
+ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';
+ const validation = validateMediaUrls([
+ 'http://127.0.0.1:8899/D.jpg',
+ 'http://localhost:3000/shot.png',
+ 'http://192.168.1.10/cam.jpg',
+ 'http://[::1]/a.png',
+ 'data:image/jpeg;base64,PLACEHOLDER',
+ 'https://example.com/image.png',
+ pngDataUrl,
+ ]);
+
+ expect(validation.validUrls).toEqual(['https://example.com/image.png', pngDataUrl]);
+ expect(validation.unreachableUrls).toEqual([
+ 'http://127.0.0.1:8899/D.jpg',
+ 'http://localhost:3000/shot.png',
+ 'http://192.168.1.10/cam.jpg',
+ 'http://[::1]/a.png',
+ ]);
+ expect(validation.invalidDataUrls).toEqual(['data:image/jpeg;base64,PLACEHOLDER']);
+
+ const message = formatMediaUrlValidationError(validation);
+ expect(message).toContain('local or private network address');
+ expect(message).toContain('http://127.0.0.1:8899/D.jpg');
+ expect(message).toContain('not a decodable image');
+ });
+
it('should create media file refs for message attachments', () => {
const items = createMediaFileItems(
{ id: 'msg-1' },
diff --git a/packages/builtin-tool-lobe-agent/src/media.ts b/packages/builtin-tool-lobe-agent/src/media.ts
index 952092fccc9..b808ab33538 100644
--- a/packages/builtin-tool-lobe-agent/src/media.ts
+++ b/packages/builtin-tool-lobe-agent/src/media.ts
@@ -1,5 +1,6 @@
import { createMediaFileRef, createMediaLocalRef } from '@lobechat/const/mediaRef';
import type { ChatAudioItem, ChatImageItem, ChatVideoItem } from '@lobechat/types';
+import { isLocalOrPrivateUrl } from '@lobechat/utils/url';
export interface MediaFileItem {
description: string;
@@ -49,10 +50,14 @@ export interface AnalyzeMediaNormalizedInput {
}
export interface MediaUrlValidationResult {
+ /** Inline image data whose bytes are not an image (e.g. `base64,PLACEHOLDER`). */
+ invalidDataUrls: string[];
invalidUrls: string[];
oversizedUrls: string[];
tooManyUrls: boolean;
totalUrls: number;
+ /** Loopback / private-network URLs the remote analysis model can never fetch. */
+ unreachableUrls: string[];
validUrls: string[];
}
@@ -85,10 +90,45 @@ export const isAllowedMediaUrl = (url: string) => {
}
};
+const INLINE_IMAGE_DATA_URL_PATTERN = /^data:image\/(png|jpe?g|gif|webp);base64,/i;
+
+const IMAGE_SIGNATURES: Record<string, number[][]> = {
+ gif: [[0x47, 0x49, 0x46, 0x38]],
+ jpeg: [[0xff, 0xd8, 0xff]],
+ jpg: [[0xff, 0xd8, 0xff]],
+ png: [[0x89, 0x50, 0x4e, 0x47]],
+ webp: [[0x52, 0x49, 0x46, 0x46]],
+};
+
+/**
+ * Cheap magic-byte check for inline raster images, so a placeholder such as
+ * `data:image/jpeg;base64,PLACEHOLDER` fails fast with a clear message instead
+ * of an opaque provider error. Other data URLs are left to the provider.
+ */
+const hasUndecodableInlineImage = (url: string) => {
+ const match = url.match(INLINE_IMAGE_DATA_URL_PATTERN);
+ if (!match) return false;
+
+ const payload = url.slice(match[0].length, match[0].length + 16);
+ let head: string;
+ try {
+ head = atob(payload);
+ } catch {
+ return true;
+ }
+
+ const signatures = IMAGE_SIGNATURES[match[1].toLowerCase()];
+ return !signatures.some((signature) =>
+ signature.every((byte, index) => head.charCodeAt(index) === byte),
+ );
+};
+
export const validateMediaUrls = (urls: string[]): MediaUrlValidationResult => {
const validUrls: string[] = [];
const invalidUrls: string[] = [];
+ const invalidDataUrls: string[] = [];
const oversizedUrls: string[] = [];
+ const unreachableUrls: string[] = [];
for (const url of urls.slice(0, MAX_MEDIA_URLS)) {
if (url.length > MAX_MEDIA_URL_LENGTH) {
@@ -96,18 +136,24 @@ export const validateMediaUrls = (urls: string[]): MediaUrlValidationResult => {
continue;
}
- if (isAllowedMediaUrl(url)) {
- validUrls.push(url);
- } else {
+ if (!isAllowedMediaUrl(url)) {
invalidUrls.push(url);
+ } else if (isLocalOrPrivateUrl(url)) {
+ unreachableUrls.push(url);
+ } else if (hasUndecodableInlineImage(url)) {
+ invalidDataUrls.push(url);
+ } else {
+ validUrls.push(url);
}
}
return {
+ invalidDataUrls,
invalidUrls,
oversizedUrls,
tooManyUrls: urls.length > MAX_MEDIA_URLS,
totalUrls: urls.length,
+ unreachableUrls,
validUrls,
};
};
@@ -141,15 +187,33 @@ export const formatMediaUrlValidationError = (validation: MediaUrlValidationResu
);
}
+ if (validation.unreachableUrls.length > 0) {
+ messages.push(
+ `Media URLs point to a local or private network address that the analysis model cannot reach: ${validation.unreachableUrls
+ .map(formatMediaUrlForError)
+ .join(
+ ', ',
+ )}. Attach the file (or read it with readFile) and pass its ref, or use a public URL.`,
+ );
+ }
+
+ if (validation.invalidDataUrls.length > 0) {
+ messages.push(
+ `Inline image data is not a decodable image: ${validation.invalidDataUrls
+ .map(formatMediaUrlForError)
+ .join(', ')}. Pass real base64 image bytes, not a placeholder.`,
+ );
+ }
+
if (validation.invalidUrls.length > 0) {
messages.push(
- `Unsupported media URLs: ${validation.invalidUrls.map(formatMediaUrlForError).join(', ')}.`,
+ `Unsupported media URLs: ${validation.invalidUrls.map(formatMediaUrlForError).join(', ')}. Only http:, https:, data:audio/*, data:image/* and data:video/* URLs are supported.`,
);
}
if (messages.length === 0) return;
- return `${messages.join(' ')} Only http:, https:, data:audio/*, data:image/* and data:video/* URLs are supported.`;
+ return messages.join(' ');
};
export const hasMediaFiles = (message: unknown): message is MediaSourceMessage =>
diff --git a/packages/database/src/models/__tests__/messages/message.create.test.ts b/packages/database/src/models/__tests__/messages/message.create.test.ts
index 7f2cbd9dcb1..f2177c763d5 100644
--- a/packages/database/src/models/__tests__/messages/message.create.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.create.test.ts
@@ -191,6 +191,35 @@ describe('MessageModel Create Tests', () => {
expect(pluginResult[0].identifier).toBe('plugin1');
});
+ it('should persist pluginError when creating a failed tool message', async () => {
+ // agent-runtime's createToolMessage passes the tool failure as pluginError
+ // together with an empty content; dropping it leaves the model with an
+ // `<empty_content>` tool result and no clue why the call failed.
+ const result = await messageModel.create({
+ content: undefined as unknown as string,
+ plugin: {
+ apiName: 'analyzeMedia',
+ arguments: '{}',
+ identifier: 'lobe-agent',
+ type: 'builtin',
+ },
+ pluginError: {
+ errorType: 'InsufficientBudgetForModel',
+ kind: 'stop',
+ message: 'budget exceeded',
+ },
+ role: 'tool',
+ sessionId: '1',
+ tool_call_id: 'call_budget',
+ });
+
+ const [row] = await serverDB
+ .select()
+ .from(messagePlugins)
+ .where(eq(messagePlugins.id, result.id));
+ expect(row.error).toMatchObject({ errorType: 'InsufficientBudgetForModel' });
+ });
+
it('should clamp oversized plugin identifiers when creating a tool message', async () => {
const oversizedApiName = `api-${'a'.repeat(40_000)}`;
const oversizedIdentifier = `plugin-${'i'.repeat(40_000)}`;
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index ad9aa496e88..f02836439b5 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -366,6 +366,7 @@ interface CreateMessageRelationParams {
fileChunks?: CreateMessageParams['fileChunks'];
files?: CreateMessageParams['files'];
plugin?: CreateMessageParams['plugin'];
+ pluginError?: CreateMessageParams['pluginError'];
pluginIntervention?: CreateMessageParams['pluginIntervention'];
pluginState?: CreateMessageParams['pluginState'];
ragQueryId?: CreateMessageParams['ragQueryId'];
@@ -3263,6 +3264,7 @@ export class MessageModel {
files,
model: fromModel,
plugin,
+ pluginError,
pluginIntervention,
pluginState,
provider: fromProvider,
@@ -3282,6 +3284,7 @@ export class MessageModel {
fileChunks,
files,
plugin,
+ pluginError,
pluginIntervention,
pluginState,
ragQueryId,
@@ -3323,6 +3326,7 @@ export class MessageModel {
fileChunks,
files,
plugin,
+ pluginError,
pluginIntervention,
pluginState,
ragQueryId,
@@ -3338,6 +3342,9 @@ export class MessageModel {
trx.insert(messagePlugins).values({
apiName: clampToolIdentifier(plugin?.apiName),
arguments: sanitizeNullBytes(plugin?.arguments),
+ // A tool that fails on its first write only has pluginError to explain
+ // itself; without it the model reads an empty tool result.
+ error: sanitizeNullBytes(pluginError),
id,
identifier: clampToolIdentifier(plugin?.identifier),
intervention: pluginIntervention,