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.

✨ feat(sandbox): upload images read via readFile so vision models can see them (#21336)

Coooolfand021690a6076
diff --git a/apps/server/src/routers/tools/market.ts b/apps/server/src/routers/tools/market.ts
index a0cb4fd914f..1d5d3f57ee7 100644
--- a/apps/server/src/routers/tools/market.ts
+++ b/apps/server/src/routers/tools/market.ts
@@ -25,6 +25,7 @@ import {
processContentBlocks,
} from '@/server/services/mcp/contentProcessor';
import { createSandboxService, resolveSandboxSessionConfig } from '@/server/services/sandbox';
+import { isSandboxAuthError } from '@/server/services/sandbox/errors';
import { preprocessLhCommand } from '@/server/services/toolExecution/preprocessLhCommand';
import { SkillConnectionErrorCode } from '@/types/skillConnectionError';
@@ -37,20 +38,6 @@ import {
const log = debug('lobe-server:tools:market');
-const isSandboxAuthError = (error?: { message?: string; name?: string }) => {
- const code = error?.name;
- const message = error?.message || '';
-
- return (
- code === 'invalid_token' ||
- code === 'token_expired' ||
- code === 'unauthorized' ||
- message.toLowerCase().includes('invalid_token') ||
- message.toLowerCase().includes('token expired') ||
- message.toLowerCase().includes('unauthorized')
- );
-};
-
const throwSandboxAuthError = () => {
throw new TRPCError({
code: 'UNAUTHORIZED',
diff --git a/apps/server/src/services/market/index.ts b/apps/server/src/services/market/index.ts
index 61655aaf8ee..d17eaa506a3 100644
--- a/apps/server/src/services/market/index.ts
+++ b/apps/server/src/services/market/index.ts
@@ -1,6 +1,11 @@
import { type LobeToolManifest } from '@lobechat/context-engine';
import { CacheRevalidate, CacheTag } from '@lobechat/types';
-import { MarketSDK, type OrgRef, orgRefToPathSegment } from '@lobehub/market-sdk';
+import {
+ MarketSDK,
+ type OrgRef,
+ orgRefToPathSegment,
+ type RunBuildInToolsContext,
+} from '@lobehub/market-sdk';
import debug from 'debug';
import { type NextRequest } from 'next/server';
import pMap from 'p-map';
@@ -486,14 +491,10 @@ export class MarketService {
/**
* Export file from sandbox to upload URL
*/
- async exportFile(params: { path: string; topicId: string; uploadUrl: string; userId: string }) {
- const { path, uploadUrl, topicId, userId } = params;
+ async exportFile(params: { path: string; uploadUrl: string }, context: RunBuildInToolsContext) {
+ const { path, uploadUrl } = params;
- return this.market.plugins.runBuildInTool(
- 'exportFile',
- { path, uploadUrl },
- { topicId, userId },
- );
+ return this.market.plugins.runBuildInTool('exportFile', { path, uploadUrl }, context);
}
/**
diff --git a/apps/server/src/services/sandbox/__tests__/errors.test.ts b/apps/server/src/services/sandbox/__tests__/errors.test.ts
new file mode 100644
index 00000000000..b660767e332
--- /dev/null
+++ b/apps/server/src/services/sandbox/__tests__/errors.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it } from 'vitest';
+
+import { isSandboxAccessDeniedError, isSandboxAuthError } from '../errors';
+
+describe('isSandboxAuthError', () => {
+ it.each(['invalid_token', 'token_expired', 'unauthorized'])(
+ 'matches the auth code %s',
+ (name) => {
+ expect(isSandboxAuthError({ name })).toBe(true);
+ },
+ );
+
+ it.each([
+ 'The INVALID_TOKEN was rejected by Market',
+ 'Your Token Expired, please re-authenticate',
+ 'Request failed: UNAUTHORIZED',
+ ])('matches the message %s case-insensitively', (message) => {
+ expect(isSandboxAuthError({ message })).toBe(true);
+ });
+
+ it.each([
+ { message: 'no such file', name: 'not_found' },
+ { message: 'export failed' },
+ { name: 'forbidden' },
+ ])('does not match non-auth error %o', (error) => {
+ expect(isSandboxAuthError(error)).toBe(false);
+ });
+
+ it('does not match a missing error', () => {
+ expect(isSandboxAuthError(undefined)).toBe(false);
+ });
+});
+
+describe('isSandboxAccessDeniedError', () => {
+ it('matches the structured access-denied marker', () => {
+ expect(isSandboxAccessDeniedError({ kind: 'stop' })).toBe(true);
+ });
+
+ it.each([{ kind: 'retry' }, { kind: 'replan' }, { message: 'denied' }])(
+ 'does not match %o',
+ (error) => {
+ expect(isSandboxAccessDeniedError(error)).toBe(false);
+ },
+ );
+
+ it('does not match a missing error', () => {
+ expect(isSandboxAccessDeniedError(undefined)).toBe(false);
+ });
+});
diff --git a/apps/server/src/services/sandbox/__tests__/service.test.ts b/apps/server/src/services/sandbox/__tests__/service.test.ts
index ce9312bb1f1..2570ef0ed85 100644
--- a/apps/server/src/services/sandbox/__tests__/service.test.ts
+++ b/apps/server/src/services/sandbox/__tests__/service.test.ts
@@ -3,7 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { FileService } from '@/server/services/file';
import type { MarketService } from '@/server/services/market';
-import type { SandboxProvider } from '../types';
+import type { SandboxProvider, SandboxProviderKind } from '../types';
describe('normalizeSandboxCommandResult', () => {
it('preserves recreation when the command fails inside a successful response', async () => {
@@ -332,3 +332,311 @@ describe('SandboxMiddlewareService', () => {
expect(fileService.createFileRecord).not.toHaveBeenCalled();
});
});
+
+describe('SandboxMiddlewareService readFile images', () => {
+ beforeEach(() => {
+ vi.resetModules();
+ vi.restoreAllMocks();
+ });
+
+ const createProvider = ({
+ callTool = vi.fn(),
+ exportFile = true,
+ exportFileToUploadUrl = vi.fn(async () => ({
+ result: { mime_type: 'image/png' },
+ success: true,
+ })),
+ kind = 'onlyboxes',
+ }: {
+ callTool?: SandboxProvider['callTool'];
+ exportFile?: boolean;
+ exportFileToUploadUrl?: SandboxProvider['exportFileToUploadUrl'];
+ kind?: SandboxProviderKind;
+ } = {}) =>
+ ({
+ capabilities: {
+ backgroundCommands: true,
+ exportFile,
+ files: true,
+ languages: ['python'],
+ persistentSession: true,
+ shell: true,
+ skillScripts: true,
+ },
+ callTool,
+ exportFileToUploadUrl,
+ kind,
+ }) satisfies SandboxProvider;
+
+ const createFileService = ({ contentLength = 1234, contentType = 'image/png' } = {}) =>
+ ({
+ createFileRecord: vi.fn(async () => ({ fileId: 'file-1', url: '/f/file-1' })),
+ createPreSignedUpload: vi.fn(async () => ({
+ headers: {},
+ url: 'https://uploads.example.com/put',
+ })),
+ getFileMetadata: vi.fn(async () => ({ contentLength, contentType })),
+ }) as unknown as FileService;
+
+ const createService = async (
+ provider: SandboxProvider,
+ {
+ agentShareVisitor,
+ fileService,
+ }: {
+ agentShareVisitor?: { shareId: string; visitorUserId: string };
+ fileService?: FileService;
+ } = {},
+ ) => {
+ const { SandboxMiddlewareService } = await import('../service');
+
+ return new SandboxMiddlewareService(provider, {
+ agentShareVisitor,
+ fileService,
+ marketService: {} as MarketService,
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+ };
+
+ it.each(['readFile', 'readLocalFile'])(
+ 'intercepts %s for an image path and uploads it for preview',
+ async (toolName) => {
+ const provider = createProvider();
+ const fileService = createFileService();
+ const service = await createService(provider, { fileService });
+
+ const result = await service.callTool(toolName, { path: '/mnt/data/chart.png' });
+
+ expect(provider.callTool).not.toHaveBeenCalled();
+ expect(provider.exportFileToUploadUrl).toHaveBeenCalledWith(
+ expect.objectContaining({ filename: 'chart.png', path: '/mnt/data/chart.png' }),
+ );
+ expect(fileService.createPreSignedUpload).toHaveBeenCalledWith(
+ expect.stringMatching(/\/topic-1\/[0-9a-f-]{36}-chart\.png$/),
+ );
+ expect(result).toEqual({
+ result: {
+ content: '[Image: chart.png]',
+ fileType: 'image/png',
+ filename: 'chart.png',
+ imageFileId: 'file-1',
+ imageUrl: '/f/file-1',
+ isImage: true,
+ },
+ success: true,
+ });
+ // Ordinary runs stamp no share provenance on the file record.
+ expect(fileService.createFileRecord.mock.calls[0][0]).not.toHaveProperty('metadata');
+ },
+ );
+
+ it('stamps agentShare provenance on the file record for visitor runs', async () => {
+ const provider = createProvider();
+ const fileService = createFileService();
+ const service = await createService(provider, {
+ agentShareVisitor: { shareId: 'share-1', visitorUserId: 'visitor-1' },
+ fileService,
+ });
+
+ const result = await service.callTool('readFile', { path: '/mnt/data/chart.png' });
+
+ expect(provider.callTool).not.toHaveBeenCalled();
+ expect(fileService.createFileRecord).toHaveBeenCalledWith(
+ expect.objectContaining({
+ metadata: { agentShare: { shareId: 'share-1', visitorUserId: 'visitor-1' } },
+ }),
+ );
+ expect(result.result?.imageUrl).toBe('/f/file-1');
+ });
+
+ it('intercepts image reads for market providers too', async () => {
+ const provider = createProvider({ kind: 'market' });
+ const fileService = createFileService();
+ const service = await createService(provider, { fileService });
+
+ const result = await service.callTool('readLocalFile', { path: '/mnt/data/chart.png' });
+
+ expect(provider.callTool).not.toHaveBeenCalled();
+ expect(result).toMatchObject({
+ result: {
+ content: '[Image: chart.png]',
+ fileType: 'image/png',
+ filename: 'chart.png',
+ imageFileId: 'file-1',
+ imageUrl: '/f/file-1',
+ isImage: true,
+ },
+ success: true,
+ });
+ });
+
+ it('passes non-image reads through to the provider', async () => {
+ const callTool = vi.fn(async () => ({
+ result: { content: 'hello' },
+ success: true,
+ }));
+ const provider = createProvider({ callTool });
+ const fileService = createFileService();
+ const service = await createService(provider, { fileService });
+
+ const params = { path: '/mnt/data/notes.txt' };
+ const result = await service.callTool('readLocalFile', params);
+
+ expect(provider.callTool).toHaveBeenCalledWith('readLocalFile', params);
+ expect(result).toEqual({ result: { content: 'hello' }, success: true });
+ expect(provider.exportFileToUploadUrl).not.toHaveBeenCalled();
+ });
+
+ it('passes svg reads through to the provider instead of treating them as images', async () => {
+ const callTool = vi.fn(async () => ({
+ result: { content: '<svg></svg>' },
+ success: true,
+ }));
+ const provider = createProvider({ callTool });
+ const fileService = createFileService();
+ const service = await createService(provider, { fileService });
+
+ const result = await service.callTool('readLocalFile', { path: '/mnt/data/icon.svg' });
+
+ expect(provider.callTool).toHaveBeenCalledWith('readLocalFile', {
+ path: '/mnt/data/icon.svg',
+ });
+ expect(result).toEqual({ result: { content: '<svg></svg>' }, success: true });
+ expect(provider.exportFileToUploadUrl).not.toHaveBeenCalled();
+ });
+
+ it('returns an upload-unavailable placeholder without a fileService', async () => {
+ const provider = createProvider();
+ const service = await createService(provider);
+
+ const result = await service.callTool('readLocalFile', { path: '/mnt/data/chart.png' });
+
+ expect(provider.callTool).not.toHaveBeenCalled();
+ expect(provider.exportFileToUploadUrl).not.toHaveBeenCalled();
+ expect(result).toMatchObject({
+ result: { filename: 'chart.png', fileType: 'image/png', isImage: true },
+ success: true,
+ });
+ expect(result.result?.content).toContain('upload unavailable');
+ expect(result.result?.imageUrl).toBeUndefined();
+ });
+
+ it('returns an upload-unavailable placeholder when the provider cannot export files', async () => {
+ const provider = createProvider({ exportFile: false });
+ const fileService = createFileService();
+ const service = await createService(provider, { fileService });
+
+ const result = await service.callTool('readLocalFile', { path: '/mnt/data/chart.png' });
+
+ expect(provider.callTool).not.toHaveBeenCalled();
+ expect(provider.exportFileToUploadUrl).not.toHaveBeenCalled();
+ expect(result).toMatchObject({
+ result: { filename: 'chart.png', isImage: true },
+ success: true,
+ });
+ expect(result.result?.content).toContain('upload unavailable');
+ expect(result.result?.imageUrl).toBeUndefined();
+ });
+
+ it('degrades to a placeholder when the export fails', async () => {
+ const provider = createProvider({
+ exportFileToUploadUrl: vi.fn(async () => ({
+ error: { message: 'no such file' },
+ success: false,
+ })),
+ });
+ const fileService = createFileService();
+ const service = await createService(provider, { fileService });
+
+ const result = await service.callTool('readLocalFile', { path: '/mnt/data/chart.png' });
+
+ expect(provider.callTool).not.toHaveBeenCalled();
+ expect(result.success).toBe(true);
+ expect(result.result?.content).toContain('no such file');
+ expect(result.result?.isImage).toBe(true);
+ expect(result.result?.imageUrl).toBeUndefined();
+ });
+
+ // The execInSandbox route turns an auth error into the Market re-auth
+ // prompt; a placeholder would swallow it.
+ it('keeps export auth failures as failed tool results', async () => {
+ const provider = createProvider({
+ exportFileToUploadUrl: vi.fn(async () => ({
+ error: { message: 'token expired', name: 'token_expired' },
+ success: false,
+ })),
+ });
+ const fileService = createFileService();
+ const service = await createService(provider, { fileService });
+
+ const result = await service.callTool('readLocalFile', { path: '/mnt/data/chart.png' });
+
+ expect(result).toMatchObject({
+ error: { name: 'token_expired' },
+ success: false,
+ });
+ expect(result.result?.imageUrl).toBeUndefined();
+ });
+
+ // `getToolAccessDeniedError` refusals carry `kind: 'stop'` — degrading them
+ // to a placeholder would let the model retry a call that must halt the run.
+ it('keeps access-denied export failures as failed tool results', async () => {
+ const accessDeniedError = {
+ code: 'FORBIDDEN',
+ hint: 'Stop the affected operation and report this error.',
+ kind: 'stop' as const,
+ message: 'Tool access was denied',
+ };
+ const provider = createProvider({
+ exportFileToUploadUrl: vi.fn(async () => ({
+ error: accessDeniedError,
+ success: false,
+ })),
+ });
+ const fileService = createFileService();
+ const service = await createService(provider, { fileService });
+
+ const result = await service.callTool('readLocalFile', { path: '/mnt/data/chart.png' });
+
+ expect(result).toMatchObject({
+ error: { kind: 'stop' },
+ success: false,
+ });
+ expect(result.result?.imageUrl).toBeUndefined();
+ });
+
+ it('rejects images above the preview size limit', async () => {
+ const provider = createProvider();
+ const fileService = createFileService({ contentLength: 11 * 1024 * 1024 });
+ const service = await createService(provider, { fileService });
+
+ const result = await service.callTool('readLocalFile', { path: '/mnt/data/chart.png' });
+
+ expect(result.success).toBe(true);
+ expect(result.result?.content).toMatch(/^Error: Image file is too large/);
+ expect(result.result?.isImage).toBe(true);
+ expect(result.result?.imageUrl).toBeUndefined();
+ });
+
+ it('treats uppercase image extensions as images', async () => {
+ const provider = createProvider();
+ const fileService = createFileService();
+ const service = await createService(provider, { fileService });
+
+ const result = await service.callTool('readLocalFile', { path: '/mnt/data/PHOTO.PNG' });
+
+ expect(provider.callTool).not.toHaveBeenCalled();
+ expect(result).toMatchObject({
+ result: {
+ content: '[Image: PHOTO.PNG]',
+ fileType: 'image/png',
+ filename: 'PHOTO.PNG',
+ imageFileId: 'file-1',
+ imageUrl: '/f/file-1',
+ isImage: true,
+ },
+ success: true,
+ });
+ });
+});
diff --git a/apps/server/src/services/sandbox/errors.ts b/apps/server/src/services/sandbox/errors.ts
new file mode 100644
index 00000000000..e5d5f890e37
--- /dev/null
+++ b/apps/server/src/services/sandbox/errors.ts
@@ -0,0 +1,30 @@
+/**
+ * Shared sandbox error predicates.
+ *
+ * `isSandboxAuthError` gates the execInSandbox re-auth prompt, so it must
+ * agree with the Market transport's auth error vocabulary in both directions:
+ * a name the SDK stops using, or a message wording it never produced, turns a
+ * recoverable re-auth into a generic tool failure.
+ */
+export const isSandboxAuthError = (error?: { message?: string; name?: string }) => {
+ const code = error?.name;
+ const message = error?.message || '';
+
+ return (
+ code === 'invalid_token' ||
+ code === 'token_expired' ||
+ code === 'unauthorized' ||
+ message.toLowerCase().includes('invalid_token') ||
+ message.toLowerCase().includes('token expired') ||
+ message.toLowerCase().includes('unauthorized')
+ );
+};
+
+/**
+ * The structured access-denied marker `getToolAccessDeniedError` emits. `kind`
+ * is not part of `ServiceResult['error']` — it survives only because callers
+ * spread the producer's object — so it is read through `unknown`, not the
+ * declared shape.
+ */
+export const isSandboxAccessDeniedError = (error: unknown) =>
+ typeof error === 'object' && error !== null && 'kind' in error && error.kind === 'stop';
diff --git a/apps/server/src/services/sandbox/providers/market.test.ts b/apps/server/src/services/sandbox/providers/market.test.ts
index fc04a97b146..820ba95d003 100644
--- a/apps/server/src/services/sandbox/providers/market.test.ts
+++ b/apps/server/src/services/sandbox/providers/market.test.ts
@@ -247,7 +247,7 @@ describe('MarketSandboxProvider', () => {
* reach Market in the request body.
*/
describe('MarketSandboxProvider · persistence fields on the wire', () => {
- const callWithRealSDK = async () => {
+ const setupRealSDK = async () => {
const { MarketSDK } = await import('@lobehub/market-sdk');
const fetchMock = vi.fn(async () => ({
headers: new Headers({ 'content-type': 'application/json' }),
@@ -260,7 +260,15 @@ describe('MarketSandboxProvider · persistence fields on the wire', () => {
const sdk = new MarketSDK({ baseURL: 'https://market.test' });
const provider = new MarketSandboxProvider({
- marketService: { getSDK: () => sdk } as unknown as MarketService,
+ marketService: {
+ // The real MarketService.exportFile is the same thin pass-through;
+ // stubbing it this way keeps the wire assertion on the SDK boundary.
+ exportFile: (
+ params: { path: string; uploadUrl: string },
+ context: Record<string, unknown>,
+ ) => sdk.plugins.runBuildInTool('exportFile', params, context as never),
+ getSDK: () => sdk,
+ } as unknown as MarketService,
sandboxCwd: 'inst-a',
sandboxInstanceId: 'env-abc',
sandboxMode: 'persistent',
@@ -268,13 +276,23 @@ describe('MarketSandboxProvider · persistence fields on the wire', () => {
userId: 'user_1',
} as never);
+ const requestBody = () => {
+ const call = fetchMock.mock.calls.find(([url]) =>
+ String(url).includes('/v1/plugins/run-buildin-tools'),
+ );
+ return call ? JSON.parse(String((call[1] as RequestInit).body)) : undefined;
+ };
+
+ return { provider, requestBody };
+ };
+
+ const callWithRealSDK = async () => {
+ const { provider, requestBody } = await setupRealSDK();
+
await provider.callTool('runCommand', { command: 'pwd' }).catch(() => undefined);
vi.unstubAllGlobals();
- const call = fetchMock.mock.calls.find(([url]) =>
- String(url).includes('/v1/plugins/run-buildin-tools'),
- );
- return call ? JSON.parse(String((call[1] as RequestInit).body)) : undefined;
+ return requestBody();
};
it('sends sandboxMode, sandboxInstanceId and sandboxCwd in the request body', async () => {
@@ -288,4 +306,26 @@ describe('MarketSandboxProvider · persistence fields on the wire', () => {
sandboxMode: 'persistent',
});
});
+
+ // exportFile ran without the session fields, so in persistent topics it
+ // looked for the file in a throwaway sandbox and could never find it.
+ it('sends the same session fields for exportFile', async () => {
+ const { provider, requestBody } = await setupRealSDK();
+
+ await provider
+ .exportFileToUploadUrl({
+ filename: 'a.png',
+ path: '/root/work/a.png',
+ uploadUrl: 'https://uploads.example.com/put',
+ })
+ .catch(() => undefined);
+ vi.unstubAllGlobals();
+
+ expect(requestBody()).toMatchObject({
+ sandboxCwd: 'inst-a',
+ sandboxInstanceId: 'env-abc',
+ sandboxMode: 'persistent',
+ toolName: 'exportFile',
+ });
+ });
});
diff --git a/apps/server/src/services/sandbox/providers/market.ts b/apps/server/src/services/sandbox/providers/market.ts
index 739091e7a02..2cd219e6564 100644
--- a/apps/server/src/services/sandbox/providers/market.ts
+++ b/apps/server/src/services/sandbox/providers/market.ts
@@ -144,15 +144,33 @@ export class MarketSandboxProvider implements SandboxProvider {
path,
uploadUrl,
}: SandboxProviderFileExportRequest): Promise<SandboxProviderFileExportResult> {
- const { marketService, topicId, userId } = this.options;
+ const {
+ marketService,
+ sandboxCwd,
+ sandboxInstanceId,
+ sandboxMode,
+ sandboxSpecification,
+ sandboxWorkingDir,
+ topicId,
+ userId,
+ } = this.options;
try {
- const response = await marketService.exportFile({
- path,
- topicId,
- uploadUrl,
- userId,
- });
+ const response = await marketService.exportFile(
+ { path, uploadUrl },
+ {
+ // Named one by one for the same reason callTool's context is — see
+ // the comment there: a dropped field silently runs the export in a
+ // throwaway sandbox that cannot see the persistent volume's file.
+ sandboxCwd,
+ sandboxInstanceId,
+ sandboxMode,
+ sandboxSpecification: sandboxSpecification as Record<string, unknown> | undefined,
+ sandboxWorkingDir,
+ topicId,
+ userId,
+ },
+ );
log('Sandbox exportFile response: %O', response);
diff --git a/apps/server/src/services/sandbox/service.ts b/apps/server/src/services/sandbox/service.ts
index 8d5a88d93a1..2765c6fff7a 100644
--- a/apps/server/src/services/sandbox/service.ts
+++ b/apps/server/src/services/sandbox/service.ts
@@ -1,8 +1,12 @@
+import { randomUUID } from 'node:crypto';
+import posixPath from 'node:path/posix';
+
import {
type SandboxCallToolResult,
type SandboxExportFileResult,
selectSandboxInitFiles,
} from '@lobechat/builtin-tool-cloud-sandbox';
+import { getLocalImageMimeType, MAX_IMAGE_READ_BYTES } from '@lobechat/local-file-shell/read-image';
import debug from 'debug';
import { sha256 } from 'js-sha256';
@@ -19,6 +23,7 @@ import {
environmentInitReport,
SANDBOX_ENVIRONMENT_INIT_TIMEOUT_MS,
} from './environmentInit';
+import { isSandboxAccessDeniedError, isSandboxAuthError } from './errors';
import type {
SandboxCommandResult,
SandboxProvider,
@@ -30,6 +35,9 @@ import type {
const log = debug('lobe-server:sandbox:service');
+/** `readLocalFile` is the legacy name still used by ComputerRuntime and remote sandboxes. */
+const READ_FILE_TOOL_NAMES = new Set(['readFile', 'readLocalFile']);
+
export class SandboxMiddlewareService implements SandboxService {
readonly capabilities: SandboxProviderCapabilities;
readonly kind: SandboxProviderKind;
@@ -54,6 +62,12 @@ export class SandboxMiddlewareService implements SandboxService {
const report = await this.ensureEnvironmentInitialized();
if (report) this.pendingEnvironmentReport = report;
await this.ensureFilesInitialized();
+
+ if (READ_FILE_TOOL_NAMES.has(toolName) && typeof params.path === 'string') {
+ const mimeType = getLocalImageMimeType(params.path);
+ if (mimeType) return this.readSandboxImageFile(params.path, mimeType);
+ }
+
const result = await this.provider.callTool(toolName, params);
// Held until a shell result can carry it: a first call that lists or
@@ -113,6 +127,72 @@ export class SandboxMiddlewareService implements SandboxService {
}
}
+ /**
+ * Sandbox counterpart of `readLocalImageFile`: remote readers decode files as
+ * UTF-8, so image bytes either fail or come back as mojibake. Upload the
+ * image through the export pipeline instead and return the same
+ * `{ isImage, imageUrl, imageFileId }` shape the device path produces, which
+ * ComputerRuntime routes to `state.images`. Failures degrade to an
+ * `[Image: name]` placeholder rather than failing the read.
+ */
+ private async readSandboxImageFile(
+ filePath: string,
+ mimeType: string,
+ ): Promise<SandboxCallToolResult> {
+ const filename = posixPath.basename(filePath);
+ const buildResult = (content: string, extra: Record<string, unknown> = {}) => ({
+ result: { content, fileType: mimeType, filename, isImage: true, ...extra },
+ success: true,
+ });
+
+ if (!this.provider.capabilities.exportFile || !this.options.fileService) {
+ return buildResult(
+ `[Image: ${filename}] (upload unavailable — this sandbox cannot export files; the model cannot view this image)`,
+ );
+ }
+
+ const exported = await this.exportAndUploadFile(filePath, filename, {
+ // A visitor's image preview gets the same share provenance the upload
+ // path stamps, so it never surfaces in the creator's library while
+ // `/f/:id` stays openable.
+ ...(this.options.agentShareVisitor
+ ? { metadata: { agentShare: this.options.agentShareVisitor } }
+ : {}),
+ storageName: `${randomUUID()}-${filename}`,
+ });
+
+ if (!exported.success) {
+ // Auth failures must stay failed so the execInSandbox route re-prompts
+ // for Market auth; access-denied refusals must stop the run. Neither may
+ // be softened into the upload-unavailable placeholder.
+ if (isSandboxAuthError(exported.error) || isSandboxAccessDeniedError(exported.error)) {
+ return { error: exported.error, result: null, success: false };
+ }
+
+ return buildResult(
+ `[Image: ${filename}] (upload unavailable — ${exported.error?.message || 'export failed'}; the model cannot view this image)`,
+ );
+ }
+
+ if (!exported.url) {
+ return buildResult(
+ `[Image: ${filename}] (upload unavailable — export failed; the model cannot view this image)`,
+ );
+ }
+
+ if (exported.size !== undefined && exported.size > MAX_IMAGE_READ_BYTES) {
+ return buildResult(
+ `Error: Image file is too large to preview (${exported.size} bytes, limit ${MAX_IMAGE_READ_BYTES}).`,
+ );
+ }
+
+ return buildResult(`[Image: ${filename}]`, {
+ fileType: exported.mimeType?.startsWith('image/') ? exported.mimeType : mimeType,
+ imageFileId: exported.fileId,
+ imageUrl: exported.url,
+ });
+ }
+
/**
* Sync the files the user uploaded in this topic/session into the sandbox the
* first time this service instance is used. Best-effort: any failure is
diff --git a/apps/server/src/services/sandbox/types.ts b/apps/server/src/services/sandbox/types.ts
index e8270a280c9..97dd1312ce2 100644
--- a/apps/server/src/services/sandbox/types.ts
+++ b/apps/server/src/services/sandbox/types.ts
@@ -4,6 +4,7 @@ import type {
SandboxMode,
} from '@lobechat/builtin-tool-cloud-sandbox';
import type { LobeChatDatabase } from '@lobechat/database';
+import type { AgentShareVisitorContext } from '@lobechat/types';
import type { FileService } from '@/server/services/file';
import type { MarketService } from '@/server/services/market';
@@ -89,6 +90,8 @@ export interface SandboxSessionContext {
}
export interface SandboxServiceOptions extends SandboxSessionContext {
+ /** Set for Agent Share visitor runs; image previews get the same `metadata.agentShare` provenance as other visitor file writes. */
+ agentShareVisitor?: Pick<AgentShareVisitorContext, 'shareId' | 'visitorUserId'>;
fileService?: FileService;
marketService: MarketService;
/** Used to look up topic/session files when bootstrapping the sandbox. */
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/cloudSandbox.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/cloudSandbox.test.ts
index 03ebb4c3407..4eb17274965 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/cloudSandbox.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/cloudSandbox.test.ts
@@ -283,4 +283,34 @@ describe('cloudSandboxRuntime', () => {
expect.objectContaining({ isShareVisitorRun: true }),
);
});
+
+ // The sandbox service stamps `metadata.agentShare` on visitor file writes
+ // (e.g. readFile image previews) so they stay out of the creator's library.
+ // It must see only the provenance ids — never permission fields like
+ // toolGrants from the full visitor context.
+ it('passes only the visitor provenance ids to the sandbox service for share-visitor runs', async () => {
+ const { cloudSandboxRuntime } = await import('../cloudSandbox');
+ await cloudSandboxRuntime.factory(
+ buildContext({
+ agentShareVisitor: {
+ agentId: 'agent-1',
+ shareId: 'share-1',
+ toolGrants: [{ apiName: 'readFile', identifier: 'lobe-cloud-sandbox' }],
+ visitorUserId: 'visitor-1',
+ },
+ }),
+ );
+
+ expect(mocks.createSandboxService.mock.calls[0][0].agentShareVisitor).toEqual({
+ shareId: 'share-1',
+ visitorUserId: 'visitor-1',
+ });
+ });
+
+ it('passes no agentShareVisitor to the sandbox service for ordinary runs', async () => {
+ const { cloudSandboxRuntime } = await import('../cloudSandbox');
+ await cloudSandboxRuntime.factory(buildContext());
+
+ expect(mocks.createSandboxService.mock.calls[0][0].agentShareVisitor).toBeUndefined();
+ });
});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts b/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts
index 0beafd9d536..b8a71b02cda 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts
@@ -159,6 +159,12 @@ export const cloudSandboxRuntime: ServerRuntimeRegistration = {
);
const fileService = new FileService(context.serverDB, context.userId, workspaceId);
const sandboxService = createSandboxService({
+ agentShareVisitor: context.agentShareVisitor
+ ? {
+ shareId: context.agentShareVisitor.shareId,
+ visitorUserId: context.agentShareVisitor.visitorUserId,
+ }
+ : undefined,
fileService,
marketService,
sandboxCwd: sandbox.cwd,
diff --git a/packages/local-file-shell/package.json b/packages/local-file-shell/package.json
index a9959aa6cb1..057fde6adb7 100644
--- a/packages/local-file-shell/package.json
+++ b/packages/local-file-shell/package.json
@@ -10,6 +10,7 @@
"./file-search": "./src/fileSearch/index.ts",
"./git": "./src/git/index.ts",
"./logger": "./src/logger.ts",
+ "./read-image": "./src/file/readImage.ts",
"./shell": "./src/shell/index.ts",
"./types": "./src/types.ts"
},