Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🪄 fix: Reuse Downloaded Artifacts for Image Reads (#15454)
Danny Avilac8939c973043
diff --git a/api/server/services/Files/Code/preflight.js b/api/server/services/Files/Code/preflight.jsindex 5b67c75d00..b985b039bf 100644--- a/api/server/services/Files/Code/preflight.js+++ b/api/server/services/Files/Code/preflight.js@@ -34,6 +34,7 @@ const preflightCodeOutputBatch = async ({ req, artifact, codeExecutionContext })inspectContent,codeApiBaseUrl: codeExecutionContext?.baseUrl,executionProfile: codeExecutionContext?.executionProfile,+ executionRouteKey: codeExecutionContext?.executionRouteKey,}),onInspectionUnavailable: (index) => {logger.warn(diff --git a/api/server/services/Files/Code/preflight.spec.js b/api/server/services/Files/Code/preflight.spec.jsindex 6c0ce47e6e..317618a579 100644--- a/api/server/services/Files/Code/preflight.spec.js+++ b/api/server/services/Files/Code/preflight.spec.js@@ -52,6 +52,7 @@ describe('preflightCodeOutputBatch Code API routing', () => {codeExecutionContext: {baseUrl: 'https://code-stateful.example.com',executionProfile: 'stateful',+ executionRouteKey: 'stateful:route',},});@@ -64,6 +65,7 @@ describe('preflightCodeOutputBatch Code API routing', () => {inspectContent: true,codeApiBaseUrl: 'https://code-stateful.example.com',executionProfile: 'stateful',+ executionRouteKey: 'stateful:route',});});});diff --git a/api/server/services/Files/Code/process.js b/api/server/services/Files/Code/process.jsindex a3c2e5283f..e3ad5b6c06 100644--- a/api/server/services/Files/Code/process.js+++ b/api/server/services/Files/Code/process.js@@ -28,6 +28,8 @@ const {buildCodeEnvDownloadQuery,claimCodeDestination,createCodeDestinationSet,+ CODE_OUTPUT_PREFLIGHT_MAX_BYTES,+ CODE_OUTPUT_PREFLIGHT_MAX_COUNT,CODE_API_EXPECTED_PROFILE_HEADER,sortCodeFilesByDestinationPriority,} = require('@librechat/api');@@ -57,6 +59,136 @@ const { determineFileType } = require('~/server/utils');const axios = createAxiosInstance();+/** Request-scoped references to buffers already fetched by artifact preflight.+ * The request object is the ownership boundary, and WeakMap keeps completed+ * requests from retaining generated-file bytes. */+const preparedCodeOutputBuffers = new WeakMap();++const codeOutputBufferKey = (routeKey, sessionId, fileId) => `${routeKey}\0${sessionId}\0${fileId}`;++const getCodeOutputRouteKey = ({ executionRouteKey, codeApiBaseUrl, executionProfile }) =>+ executionRouteKey ?? codeApiBaseUrl ?? executionProfile ?? 'default';++const normalizeSandboxArtifactName = (filePath) => {+ if (typeof filePath !== 'string' || filePath.length === 0) {+ return null;+ }+ if (filePath.includes('\\')) {+ return null;+ }+ const posixPath = filePath;+ let relativePath = posixPath;+ if (posixPath.startsWith('/mnt/data/')) {+ relativePath = posixPath.slice('/mnt/data/'.length);+ } else if (posixPath.startsWith('/')) {+ return null;+ }+ if (relativePath.split('/').some((segment) => segment === '.' || segment === '..')) {+ return null;+ }+ const normalized = path.posix.normalize(relativePath).replace(/^\.\//, '');+ if (+ normalized.length === 0 ||+ normalized === '.' ||+ normalized === '..' ||+ normalized.startsWith('../')+ ) {+ return null;+ }+ return normalized;+};++const cachePreparedCodeOutputBuffer = ({+ req,+ id,+ name,+ session_id,+ buffer,+ codeApiBaseUrl,+ executionProfile,+ executionRouteKey,+}) => {+ if (+ !req ||+ (typeof req !== 'object' && typeof req !== 'function') ||+ typeof id !== 'string' ||+ typeof session_id !== 'string' ||+ !Buffer.isBuffer(buffer)+ ) {+ return;+ }+ let cache = preparedCodeOutputBuffers.get(req);+ if (!cache) {+ cache = { buffers: new Map(), totalBytes: 0 };+ preparedCodeOutputBuffers.set(req, cache);+ }+ const routeKey = getCodeOutputRouteKey({ executionRouteKey, codeApiBaseUrl, executionProfile });+ const key = codeOutputBufferKey(routeKey, session_id, id);+ const existing = cache.buffers.get(key);+ if (existing) {+ cache.totalBytes -= existing.buffer.length;+ cache.buffers.delete(key);+ }+ if (buffer.length > CODE_OUTPUT_PREFLIGHT_MAX_BYTES) {+ return;+ }+ while (+ cache.buffers.size >= CODE_OUTPUT_PREFLIGHT_MAX_COUNT ||+ cache.totalBytes + buffer.length > CODE_OUTPUT_PREFLIGHT_MAX_BYTES+ ) {+ const oldestKey = cache.buffers.keys().next().value;+ if (oldestKey == null) {+ break;+ }+ const oldest = cache.buffers.get(oldestKey);+ cache.buffers.delete(oldestKey);+ cache.totalBytes -= oldest.buffer.length;+ }+ cache.buffers.set(key, { name, buffer });+ cache.totalBytes += buffer.length;+};++const getPreparedCodeOutputBuffer = ({+ req,+ file_path,+ session_id,+ files,+ codeApiBaseUrl,+ executionProfile,+ executionRouteKey,+}) => {+ if (!req || (typeof req !== 'object' && typeof req !== 'function') || !Array.isArray(files)) {+ return null;+ }+ const cache = preparedCodeOutputBuffers.get(req);+ const requestedName = normalizeSandboxArtifactName(file_path);+ if (!cache || !requestedName) {+ return null;+ }++ const routeKey = getCodeOutputRouteKey({ executionRouteKey, codeApiBaseUrl, executionProfile });+ for (const file of files) {+ if (!file || typeof file.id !== 'string' || typeof file.name !== 'string') {+ continue;+ }+ if (normalizeSandboxArtifactName(file.name) !== requestedName) {+ continue;+ }+ const storageSessionId = file.storage_session_id ?? file.session_id ?? session_id;+ if (typeof storageSessionId !== 'string') {+ continue;+ }+ const key = codeOutputBufferKey(routeKey, storageSessionId, file.id);+ const cached = cache.buffers.get(key);+ if (cached && normalizeSandboxArtifactName(cached.name) === requestedName) {+ cache.buffers.delete(key);+ cache.totalBytes -= cached.buffer.length;+ return cached.buffer;+ }+ }+ return null;+};+class CodeOutputDownloadLimitError extends Error {constructor(maxBytes) {super(`Generated file exceeds the ${maxBytes}-byte transport limit`);@@ -140,6 +272,7 @@ const downloadCodeOutputBuffer = async ({* @param {number} [params.maxBytes] - Remaining aggregate inspection budget.* @param {string} [params.codeApiBaseUrl] - Trusted per-agent Code API endpoint.* @param {'default'|'stateful'} [params.executionProfile] - Trusted execution profile.+ * @param {string} [params.executionRouteKey] - Trusted deployment-local route identity.*/const prepareCodeOutputForInspection = async ({req,@@ -150,6 +283,7 @@ const prepareCodeOutputForInspection = async ({inspectContent = true,codeApiBaseUrl,executionProfile = 'default',+ executionRouteKey,}) => {const { fileSizeLimit } = getCodeOutputFileSettings(req);const transportLimit =@@ -162,6 +296,16 @@ const prepareCodeOutputForInspection = async ({codeApiBaseUrl,executionProfile,});+ cachePreparedCodeOutputBuffer({+ req,+ id,+ name,+ session_id,+ buffer,+ codeApiBaseUrl,+ executionProfile,+ executionRouteKey,+ });const safeName = sanitizeArtifactPath(name);const fallbackType = inferMimeType(name, '') || 'application/octet-stream';if (!inspectContent) {@@ -1494,8 +1638,11 @@ async function readSandboxFile({}/**- * Reads a small image file out of the code-execution sandbox as base64 so- * `read_file` can surface it to vision-capable models. `readSandboxFile`'s+ * Reads a small code artifact as base64 so `read_file` can surface it to+ * vision-capable models. Reuses bytes fetched by the current request's+ * artifact preflight when the requested path resolves to the exact returned+ * file ref; otherwise falls back to the code-execution sandbox.+ * `readSandboxFile`'s* `cat` round-trips stdout through codeapi's JSON transport, which lossily* replaces non-UTF-8 bytes and corrupts image data. The in-sandbox reader* base64-encodes the bytes instead, so the payload stays ASCII-safe across@@ -1515,6 +1662,7 @@ async function readSandboxFile({* @param {string} [params.runtime_session_hint] - Per-conversation stateful runtime-session hint.* @param {number} [params.maxBytes] - In-sandbox size cap; larger files return `{ tooLarge, bytes }`.* @param {ServerRequest} [params.req] - Current authenticated request, used to mint Code API auth.+ * @param {string} [params.executionRouteKey] - Trusted deployment-local route identity.* @returns {Promise<{base64: string, bytes: number}* | {tooLarge: true, reason: 'size' | 'round_trips', bytes: number} | null>}* `null` when codeapi is unavailable; throws on transport / read errors.@@ -1526,9 +1674,27 @@ async function readSandboxImage({runtime_session_hint,codeApiBaseUrl,executionProfile,+ executionRouteKey,maxBytes,req,}) {+ const limit = typeof maxBytes === 'number' && maxBytes > 0 ? maxBytes : 5 * megabyte;+ const preparedBuffer = getPreparedCodeOutputBuffer({+ req,+ file_path,+ session_id,+ files,+ codeApiBaseUrl,+ executionProfile,+ executionRouteKey,+ });+ if (preparedBuffer) {+ if (preparedBuffer.length > limit) {+ return { tooLarge: true, reason: 'size', bytes: preparedBuffer.length };+ }+ return { base64: preparedBuffer.toString('base64'), bytes: preparedBuffer.length };+ }+const baseURL = codeApiBaseUrl ?? getCodeBaseURL();if (!baseURL) {return null;@@ -1541,7 +1707,7 @@ async function readSandboxImage({return readWindowedSandboxImage({filePath: file_path,baseUrl: baseURL,- limit: typeof maxBytes === 'number' && maxBytes > 0 ? maxBytes : 5 * megabyte,+ limit,readChunk: ({ code }) =>execSandboxImageChunk({baseURL,diff --git a/api/server/services/Files/Code/process.spec.js b/api/server/services/Files/Code/process.spec.jsindex e951c485e0..80c7d0aadc 100644--- a/api/server/services/Files/Code/process.spec.js+++ b/api/server/services/Files/Code/process.spec.js@@ -107,6 +107,8 @@ jest.mock('@librechat/api', () => {typeof configured === 'number' && Number.isFinite(configured) && configured > 0? Math.min(configured, 64 * 1024 * 1024): 64 * 1024 * 1024,+ CODE_OUTPUT_PREFLIGHT_MAX_BYTES: 64 * 1024 * 1024,+ CODE_OUTPUT_PREFLIGHT_MAX_COUNT: 10,/* `processCodeOutput` derives the `textFormat` trust flag for* `IMongoFile` from this helper — Codex P1 review on PR #12934.* The mock returns 'text' for non-null extractor output and null@@ -2806,6 +2808,307 @@ describe('Code Process', () => {mockParseSandboxImageChunk.mockImplementation((response) => response);});+ it('reuses the exact artifact preflight buffer without calling /exec', async () => {+ const req = {+ user: { id: 'artifact-user' },+ config: mockReq.config,+ };+ const source = Buffer.from('cached-image-bytes');+ mockAxios.mockResolvedValueOnce({ data: source });+ determineFileType.mockResolvedValueOnce({ mime: 'image/png' });++ await prepareCodeOutputForInspection({+ ...baseParams,+ req,+ id: 'artifact-file',+ name: 'charts/result.png',+ session_id: 'artifact-session',+ });+ expect(mockAxios).toHaveBeenCalledTimes(1);+ expect(mockAxios.mock.calls[0][0].method).toBe('get');+ mockAxios.mockClear();++ const result = await readSandboxImage({+ req,+ file_path: '/mnt/data/charts/result.png',+ session_id: 'runtime-session',+ files: [+ {+ id: 'artifact-file',+ name: 'charts/result.png',+ storage_session_id: 'artifact-session',+ },+ ],+ });++ expect(mockAxios).not.toHaveBeenCalled();+ expect(result).toEqual({ base64: source.toString('base64'), bytes: source.length });+ });++ it('does not reuse a same-path buffer for a different artifact ref', async () => {+ const req = {+ user: { id: 'artifact-user' },+ config: mockReq.config,+ };+ mockAxios.mockResolvedValueOnce({ data: Buffer.from('stale') });+ determineFileType.mockResolvedValueOnce({ mime: 'image/png' });+ await prepareCodeOutputForInspection({+ ...baseParams,+ req,+ id: 'stale-file',+ name: 'chart.png',+ session_id: 'artifact-session',+ });+ mockAxios.mockReset();+ mockAxios.mockResolvedValueOnce({ data: { stdout: '{}' } });++ await readSandboxImage({+ req,+ file_path: '/mnt/data/chart.png',+ files: [+ {+ id: 'current-file',+ name: 'chart.png',+ storage_session_id: 'artifact-session',+ },+ ],+ });++ expect(mockAxios).toHaveBeenCalledTimes(1);+ expect(mockAxios.mock.calls[0][0].method).toBe('post');+ });++ it('does not reuse an exact artifact ref across requests', async () => {+ const ownerReq = {+ user: { id: 'artifact-user' },+ config: mockReq.config,+ };+ const otherReq = {+ user: { id: 'other-user' },+ config: mockReq.config,+ };+ mockAxios.mockResolvedValueOnce({ data: Buffer.from('owner-bytes') });+ determineFileType.mockResolvedValueOnce({ mime: 'image/png' });+ await prepareCodeOutputForInspection({+ ...baseParams,+ req: ownerReq,+ id: 'artifact-file',+ name: 'chart.png',+ session_id: 'artifact-session',+ });+ mockAxios.mockReset();+ mockAxios.mockResolvedValueOnce({ data: { stdout: '{}' } });++ await readSandboxImage({+ req: otherReq,+ file_path: '/mnt/data/chart.png',+ files: [+ {+ id: 'artifact-file',+ name: 'chart.png',+ storage_session_id: 'artifact-session',+ },+ ],+ });++ expect(mockAxios).toHaveBeenCalledTimes(1);+ expect(mockAxios.mock.calls[0][0].method).toBe('post');+ });++ it('does not reuse an artifact ref from a different Code API deployment', async () => {+ const req = {+ user: { id: 'artifact-user' },+ config: mockReq.config,+ };+ mockAxios.mockResolvedValueOnce({ data: Buffer.from('deployment-a') });+ determineFileType.mockResolvedValueOnce({ mime: 'image/png' });+ await prepareCodeOutputForInspection({+ ...baseParams,+ req,+ id: 'artifact-file',+ name: 'chart.png',+ session_id: 'artifact-session',+ codeApiBaseUrl: 'https://code-a.example.com',+ executionProfile: 'stateful',+ executionRouteKey: 'stateful:deployment-a',+ });+ mockAxios.mockReset();+ mockAxios.mockResolvedValueOnce({ data: { stdout: '{}' } });++ await readSandboxImage({+ req,+ file_path: '/mnt/data/chart.png',+ codeApiBaseUrl: 'https://code-b.example.com',+ executionProfile: 'stateful',+ executionRouteKey: 'stateful:deployment-b',+ files: [+ {+ id: 'artifact-file',+ name: 'chart.png',+ storage_session_id: 'artifact-session',+ },+ ],+ });++ expect(mockAxios).toHaveBeenCalledTimes(1);+ expect(mockAxios.mock.calls[0][0]).toMatchObject({+ method: 'post',+ url: 'https://code-b.example.com/exec',+ });+ });++ it('does not reuse a cached artifact for a path containing parent traversal', async () => {+ const req = {+ user: { id: 'artifact-user' },+ config: mockReq.config,+ };+ mockAxios.mockResolvedValueOnce({ data: Buffer.from('cached-chart') });+ determineFileType.mockResolvedValueOnce({ mime: 'image/png' });+ await prepareCodeOutputForInspection({+ ...baseParams,+ req,+ id: 'artifact-file',+ name: 'chart.png',+ session_id: 'artifact-session',+ });+ mockAxios.mockReset();+ mockAxios.mockResolvedValueOnce({ data: { stdout: '{}' } });++ await readSandboxImage({+ req,+ file_path: '/mnt/data/link/../chart.png',+ files: [+ {+ id: 'artifact-file',+ name: 'chart.png',+ storage_session_id: 'artifact-session',+ },+ ],+ });++ expect(mockAxios).toHaveBeenCalledTimes(1);+ expect(mockAxios.mock.calls[0][0].method).toBe('post');+ });++ it('does not treat a literal backslash in a POSIX path as a separator', async () => {+ const req = {+ user: { id: 'artifact-user' },+ config: mockReq.config,+ };+ mockAxios.mockResolvedValueOnce({ data: Buffer.from('cached-chart') });+ determineFileType.mockResolvedValueOnce({ mime: 'image/png' });+ await prepareCodeOutputForInspection({+ ...baseParams,+ req,+ id: 'artifact-file',+ name: 'charts/result.png',+ session_id: 'artifact-session',+ });+ mockAxios.mockReset();+ mockAxios.mockResolvedValueOnce({ data: { stdout: '{}' } });++ await readSandboxImage({+ req,+ file_path: '/mnt/data/charts\\result.png',+ files: [+ {+ id: 'artifact-file',+ name: 'charts/result.png',+ storage_session_id: 'artifact-session',+ },+ ],+ });++ expect(mockAxios).toHaveBeenCalledTimes(1);+ expect(mockAxios.mock.calls[0][0].method).toBe('post');+ });++ it('evicts the oldest prepared buffers when the per-request cache reaches its limit', async () => {+ const req = {+ user: { id: 'artifact-user' },+ config: mockReq.config,+ };+ mockAxios.mockResolvedValue({ data: Buffer.from('cached') });++ for (let index = 0; index < 11; index++) {+ await prepareCodeOutputForInspection({+ ...baseParams,+ req,+ id: `artifact-${index}`,+ name: `chart-${index}.png`,+ session_id: 'artifact-session',+ inspectContent: false,+ });+ }+ mockAxios.mockReset();+ mockAxios.mockResolvedValueOnce({ data: { stdout: '{}' } });++ await readSandboxImage({+ req,+ file_path: '/mnt/data/chart-0.png',+ files: [+ {+ id: 'artifact-0',+ name: 'chart-0.png',+ storage_session_id: 'artifact-session',+ },+ ],+ });++ expect(mockAxios).toHaveBeenCalledTimes(1);+ expect(mockAxios.mock.calls[0][0].method).toBe('post');+ mockAxios.mockClear();++ const newest = await readSandboxImage({+ req,+ file_path: '/mnt/data/chart-10.png',+ files: [+ {+ id: 'artifact-10',+ name: 'chart-10.png',+ storage_session_id: 'artifact-session',+ },+ ],+ });++ expect(newest).toEqual({ base64: Buffer.from('cached').toString('base64'), bytes: 6 });+ expect(mockAxios).not.toHaveBeenCalled();+ });++ it('applies the inline byte limit before returning a prepared artifact buffer', async () => {+ const req = {+ user: { id: 'artifact-user' },+ config: mockReq.config,+ };+ const source = Buffer.alloc(128);+ mockAxios.mockResolvedValueOnce({ data: source });+ determineFileType.mockResolvedValueOnce({ mime: 'image/png' });+ await prepareCodeOutputForInspection({+ ...baseParams,+ req,+ id: 'large-file',+ name: 'large.png',+ session_id: 'artifact-session',+ });+ mockAxios.mockClear();++ const result = await readSandboxImage({+ req,+ file_path: '/mnt/data/large.png',+ maxBytes: 64,+ files: [+ {+ id: 'large-file',+ name: 'large.png',+ storage_session_id: 'artifact-session',+ },+ ],+ });++ expect(result).toEqual({ tooLarge: true, reason: 'size', bytes: source.length });+ expect(mockAxios).not.toHaveBeenCalled();+ });+it('forwards the sandbox session, runtime hint and profile header', async () => {mockAxios.mockResolvedValue({ data: { stdout: '{}' } });diff --git a/packages/api/src/agents/handlers.spec.ts b/packages/api/src/agents/handlers.spec.tsindex 2a8790dd7d..12de41039d 100644--- a/packages/api/src/agents/handlers.spec.ts+++ b/packages/api/src/agents/handlers.spec.ts@@ -4430,6 +4430,7 @@ describe('createToolExecuteHandler', () => {baseUrl: 'https://stateful-code.example.com',codeSessionKey: 'execute_code:stateful:v1:user',executionProfile: 'stateful',+ executionRouteKey: 'stateful:deployment-a',runtimeSessionHint: 'v1:user',statefulSessions: true,},@@ -4449,6 +4450,7 @@ describe('createToolExecuteHandler', () => {expect.objectContaining({codeApiBaseUrl: 'https://stateful-code.example.com',executionProfile: 'stateful',+ executionRouteKey: 'stateful:deployment-a',runtime_session_hint: 'v1:user',}),);diff --git a/packages/api/src/agents/handlers.ts b/packages/api/src/agents/handlers.tsindex 71099d8aa0..23ddeacd9e 100644--- a/packages/api/src/agents/handlers.ts+++ b/packages/api/src/agents/handlers.ts@@ -450,6 +450,7 @@ export interface ToolExecuteOptions {runtime_session_hint?: string;codeApiBaseUrl?: string;executionProfile?: CodeExecutionContext['executionProfile'];+ executionRouteKey?: string;req?: ServerRequest;}) => Promise<{ content: string } | null>;/**@@ -470,6 +471,7 @@ export interface ToolExecuteOptions {runtime_session_hint?: string;codeApiBaseUrl?: string;executionProfile?: CodeExecutionContext['executionProfile'];+ executionRouteKey?: string;/** In-sandbox size cap; files larger than this return `tooLarge` without transferring bytes. */maxBytes?: number;req?: ServerRequest;@@ -554,6 +556,7 @@ function getCodeExecutionContext(function codeExecutionRequestParams(context?: CodeExecutionContext): {codeApiBaseUrl?: string;executionProfile?: CodeExecutionContext['executionProfile'];+ executionRouteKey?: string;runtime_session_hint?: string;} {if (!context) {@@ -562,6 +565,7 @@ function codeExecutionRequestParams(context?: CodeExecutionContext): {return {codeApiBaseUrl: context.baseUrl,executionProfile: context.executionProfile,+ ...(context.executionRouteKey ? { executionRouteKey: context.executionRouteKey } : {}),...(context.runtimeSessionHint ? { runtime_session_hint: context.runtimeSessionHint } : {}),};}