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: Stop Code Outputs and Tool-Routed Spreadsheets From Locking Threads (#16058)
Danny Aviladb674eda60ed
diff --git a/api/app/clients/BaseClient.js b/api/app/clients/BaseClient.jsindex a685ee3091..a39c5ca3c8 100644--- a/api/app/clients/BaseClient.js+++ b/api/app/clients/BaseClient.js@@ -21,6 +21,7 @@ const {collectModelBoundHistoricalFileIdState,projectModelBoundSourceFiles,isModelBoundAttachmentFile,+ isToolOwnedAttachment,withBalanceReservations,findCheckpointSummaryPart,getSummaryPartText,@@ -1844,13 +1845,7 @@ class BaseClient {/* An explicit `provider` path is authoritative: lazy provisioning stamps* `embedded`/`codeEnvRef` on files that are still meant for the model, so the* legacy tool-provisioning exclusion only applies to records without one. */- if (- deliveryPath !== 'provider' &&- (file.embedded === true ||- file.metadata?.codeEnvRef != null ||- file.metadata?.codeEnvRefs != null ||- file.metadata?.fileIdentifier != null)- ) {+ if (deliveryPath !== 'provider' && isToolOwnedAttachment(file)) {allFiles.push(file);continue;}diff --git a/api/app/clients/specs/BaseClient.test.js b/api/app/clients/specs/BaseClient.test.jsindex 7277e63487..4a3fd4b7f6 100644--- a/api/app/clients/specs/BaseClient.test.js+++ b/api/app/clients/specs/BaseClient.test.js@@ -3584,13 +3584,13 @@ describe('BaseClient', () => {expect(TestClient.getTextContextAttachments([file])).toEqual([]);});- test('delivers the text when the tool that would read the file has yet to receive it', () => {- /* An upload that named no destination is filed under no tool, so the enabled tool alone- * cannot serve it and withholding the text left it readable by nothing. */+ test('delivers the text when File Search has yet to receive the file', () => {+ /* An upload that named no destination is filed under no tool, so an enabled search tool+ * alone cannot serve it and withholding the text left it readable by nothing. */routeCsvToTools();TestClient.options.agent = {provider: EModelEndpoint.openAI,- fileConsumers: { executeCode: true, fileSearch: true },+ fileConsumers: { executeCode: false, fileSearch: true },};TestClient.options.agent.deliveryRouting = resolveTurnDeliveryRouting({agent: TestClient.options.agent,@@ -3614,6 +3614,32 @@ describe('BaseClient', () => {]);});+ test('leaves a file Run Code can read with Run Code before the sandbox holds it', () => {+ /* Run Code uploads the file on its first call, so the text stays off the prompt, where it+ * would otherwise count toward the history limits until that call. */+ routeCsvToTools();+ TestClient.options.agent = {+ provider: EModelEndpoint.openAI,+ fileConsumers: { executeCode: true, fileSearch: true },+ };+ TestClient.options.agent.deliveryRouting = resolveTurnDeliveryRouting({+ agent: TestClient.options.agent,+ config: TestClient.options.req?.config,+ });+ const file = {+ file_id: 'unprovisioned-csv',+ filename: 'sales.csv',+ type: 'text/csv',+ text: 'region,total',+ llmDeliveryPath: 'none',+ metadata: { destinationChosen: false },+ };++ expect(TestClient.getAttachmentDeliveryPath(file)).toBe('none');+ expect(TestClient.getTextContextAttachments([file])).toEqual([]);+ expect(TestClient.resolveTurnAttachments([file])).toEqual([file]);+ });+test('does not fall back on an endpoint that has not enabled it', () => {routeCsvToTools({ textFallbackWithoutTools: false });TestClient.options.agent = {@@ -3931,6 +3957,29 @@ describe('BaseClient', () => {expect(message.image_urls).toEqual(['encoded-image']);});+ test('keeps a code output out of the prompt once its expired sandbox reference is cleared', async () => {+ /* Priming clears a dead sandbox reference on the turn's copy of the record so the file+ * is re-provisioned. The output still belongs to the sandbox that wrote it. */+ const message = {};+ const file = {+ user: 'user1',+ file_id: 'code-output-chart',+ filename: 'chart.png',+ filepath: '/uploads/chart.png',+ type: 'image/png',+ bytes: 100,+ source: 'local',+ context: 'execute_code',+ metadata: {},+ };++ const result = await TestClient.processAttachments(message, [file]);++ expect(result).toEqual([file]);+ expect(TestClient.addImageURLs).not.toHaveBeenCalled();+ expect(message.image_urls).toBeUndefined();+ });+test('keeps excluding embedded legacy files that have no delivery path', async () => {const message = {};const file = {diff --git a/packages/api/src/agents/attachments.test.ts b/packages/api/src/agents/attachments.test.tsindex 66745db153..92610dae91 100644--- a/packages/api/src/agents/attachments.test.ts+++ b/packages/api/src/agents/attachments.test.ts@@ -1,5 +1,5 @@import { logger } from '@librechat/data-schemas';-import { EModelEndpoint, FileSources } from 'librechat-data-provider';+import { EModelEndpoint, FileContext, FileSources } from 'librechat-data-provider';import type { IMongoFile } from '@librechat/data-schemas';import type { ServerRequest } from '~/types';@@ -18,7 +18,9 @@ import {getAgentContextAttachments,buildAgentContextAttachmentsByAgentId,isModelBoundAttachmentFile,+ isToolOwnedAttachment,} from './attachments';+import { applyTurnDelivery, resolveTurnDeliveryRouting } from './files/delivery';const makeTextFile = (file_id: string, filename: string, text: string): IMongoFile =>({@@ -670,3 +672,114 @@ describe('agent attachment helpers', () => {).resolves.toEqual(new Map());});});++describe('files that belong to a tool', () => {+ const XLSX = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';+ const sandboxRef = {+ kind: 'user',+ id: 'user-1',+ file_id: 'sandbox-file',+ storage_session_id: 's1',+ };++ it('keeps a code output tool-owned after priming clears its expired sandbox references', () => {+ const output = {+ file_id: 'rows-json',+ type: 'application/json',+ context: FileContext.execute_code,+ text: '{"rows":[]}',+ metadata: {},+ } as unknown as IMongoFile;++ expect(isToolOwnedAttachment(output)).toBe(true);+ expect(isModelBoundAttachmentFile(output)).toBe(false);+ });++ it('still treats a route-less user upload without tool references as prompt content', () => {+ const upload = {+ file_id: 'legacy-upload',+ type: 'application/pdf',+ context: FileContext.message_attachment,+ metadata: {},+ } as unknown as IMongoFile;++ expect(isToolOwnedAttachment(upload)).toBe(false);+ expect(isModelBoundAttachmentFile(upload)).toBe(true);+ });++ it('admits a Run Code thread shaped like the one the history limit locked', () => {+ /* Spreadsheets routed to tools with text stored for the fallback, one screenshot, and the+ * code outputs of an earlier run whose expired sandbox references priming cleared. Counted+ * as prompt attachments, the outputs and the spreadsheets' fallback text filled the per-turn+ * count past its default of ten, so every later turn was refused. */+ const config = {+ fileConfig: {+ textFallbackWithoutTools: true,+ endpoints: {+ default: { defaultLLMDeliveryPath: { overrides: { [XLSX]: 'none' as const } } },+ },+ },+ };+ const routing = resolveTurnDeliveryRouting({+ agent: { provider: EModelEndpoint.bedrock, endpoint: EModelEndpoint.bedrock },+ config,+ });+ const consumers = { executeCode: true, fileSearch: false };+ const sheet = (file_id: string, extra: object = {}) =>+ ({+ file_id,+ type: XLSX,+ bytes: 200_000,+ source: FileSources.local,+ context: FileContext.message_attachment,+ llmDeliveryPath: 'none',+ text: 'x'.repeat(110_000),+ metadata: { destinationChosen: false },+ ...extra,+ }) as unknown as IMongoFile;+ const olderSheets = ['q3-actuals', 'q3-budget', 'q3-map'].map((id) =>+ sheet(id, {+ llmDeliveryPath: 'text',+ metadata: { destinationChosen: false, codeEnvRef: sandboxRef },+ }),+ );+ const newSheets = ['s1', 's2', 's3', 's4', 's5', 's6'].map((id) => sheet(id));+ const screenshot = {+ file_id: 'screenshot',+ type: 'image/png',+ bytes: 380_971,+ source: FileSources.local,+ context: FileContext.message_attachment,+ llmDeliveryPath: 'provider',+ metadata: { destinationChosen: false },+ } as unknown as IMongoFile;+ const outputs = Array.from(+ { length: 8 },+ (_, index) =>+ ({+ file_id: `output-${index}`,+ type: 'application/json',+ bytes: 20_000,+ source: FileSources.local,+ context: FileContext.execute_code,+ text: 'y'.repeat(20_000),+ metadata: {},+ }) as unknown as IMongoFile,+ );++ const admitted = applyTurnDelivery([...olderSheets, screenshot, ...newSheets, ...outputs], {+ routing,+ consumers,+ }).filter(isModelBoundAttachmentFile);++ expect(admitted.map((file) => file.file_id)).toEqual(['screenshot']);+ expect(() =>+ assertAgentAttachmentLimits({+ attachments: admitted,+ fileConfig: config.fileConfig,+ endpoint: EModelEndpoint.bedrock,+ countRepeatedExtractedText: true,+ }),+ ).not.toThrow();+ });+});diff --git a/packages/api/src/agents/attachments.ts b/packages/api/src/agents/attachments.tsindex 2606905ff0..447af3c921 100644--- a/packages/api/src/agents/attachments.ts+++ b/packages/api/src/agents/attachments.ts@@ -1,9 +1,10 @@import { logger } from '@librechat/data-schemas';import {- EModelEndpoint,+ FileContext,FileSources,- getEndpointFileConfig,+ EModelEndpoint,mergeFileConfig,+ getEndpointFileConfig,} from 'librechat-data-provider';import type { IMongoFile } from '@librechat/data-schemas';import type { TokenCountFn } from '~/utils/text';@@ -22,10 +23,34 @@ type AttachmentTelemetryFile = FileWithId & {source?: string | null;type?: string | null;text?: string | null;+ context?: string | null;+ embedded?: boolean | null;llmDeliveryPath?: string | null;metadata?: (IMongoFile['metadata'] & { pageCount?: number | null }) | null;};+/**+ * Whether a record without a delivery route belongs to a tool rather than to the prompt.+ *+ * A code output lives in the sandbox that wrote it, and it stays the tool's while an expired+ * sandbox copy is re-provisioned: priming clears the dead references on the turn's copy of the+ * record, which must not turn the output into a prompt attachment that counts toward the turn's+ * limits. Any other record belongs to a tool once a tool has provisioned it.+ */+export function isToolOwnedAttachment(file: AttachmentTelemetryFile): boolean {+ const metadata = file.metadata as+ | (IMongoFile['metadata'] & { fileIdentifier?: unknown })+ | null+ | undefined;+ return (+ file.context === FileContext.execute_code ||+ file.embedded === true ||+ metadata?.codeEnvRef != null ||+ metadata?.codeEnvRefs != null ||+ metadata?.fileIdentifier != null+ );+}+/** Whether a hydrated file contributes content to the model prompt itself. */export function isModelBoundAttachmentFile(file: AttachmentTelemetryFile | null | undefined,@@ -46,16 +71,7 @@ export function isModelBoundAttachmentFile(if (file.llmDeliveryPath === 'provider') {return true;}- const metadata = file.metadata as- | (IMongoFile['metadata'] & { fileIdentifier?: unknown })- | null- | undefined;- return !(- (file as IMongoFile).embedded === true ||- metadata?.codeEnvRef != null ||- metadata?.codeEnvRefs != null ||- metadata?.fileIdentifier != null- );+ return !isToolOwnedAttachment(file);}type AgentAttachmentLimitRequest = {diff --git a/packages/api/src/agents/files/delivery.spec.ts b/packages/api/src/agents/files/delivery.spec.tsindex d36fa721d6..181501f375 100644--- a/packages/api/src/agents/files/delivery.spec.ts+++ b/packages/api/src/agents/files/delivery.spec.ts@@ -118,14 +118,23 @@ describe('applyTurnDelivery', () => {expect(applyTurnDelivery(files, { agent, config, consumers: runsCode })).toBe(files);});- it('delivers text for a file the tool that would read it has yet to receive', () => {- /* An upload that named no destination is filed under no tool, so the enabled tool alone is- * not what serves it: withholding the text on that basis left it readable by nothing. */- expect(applyTurnDelivery([csv], { agent, config, consumers: runsCode })).toEqual([+ it('delivers text for a file File Search has yet to receive', () => {+ /* An upload that named no destination is filed under no tool, so an enabled search tool+ * alone is not what serves it: withholding the text on that basis left it readable by+ * nothing. */+ const searchesFiles: TurnFileConsumers = { executeCode: false, fileSearch: true };+ expect(applyTurnDelivery([csv], { agent, config, consumers: searchesFiles })).toEqual([{ ...csv, llmDeliveryPath: 'text' },]);});+ it('leaves a file Run Code can read with Run Code before the sandbox holds it', () => {+ /* Run Code uploads the file on its first call. Delivering the text instead would count it+ * toward the turn's limits until that call, and a refused turn never makes it. */+ const files = [csv];+ expect(applyTurnDelivery(files, { agent, config, consumers: runsCode })).toBe(files);+ });+it('marks nothing where the endpoint has not enabled the fallback', () => {const files = [csv];const disabled = {diff --git a/packages/api/src/agents/files/encode.spec.ts b/packages/api/src/agents/files/encode.spec.tsindex d999273ead..10c29025be 100644--- a/packages/api/src/agents/files/encode.spec.ts+++ b/packages/api/src/agents/files/encode.spec.ts@@ -1,4 +1,4 @@-import { FileSources, ImageDetail } from 'librechat-data-provider';+import { FileContext, FileSources, ImageDetail } from 'librechat-data-provider';import type { TFile } from 'librechat-data-provider';import type { RunFileEncodingAgent, RunFileMessageEncoderDeps } from './encode';import type { ServerRequest } from '~/types';@@ -172,6 +172,7 @@ describe('createRunFileMessageEncoder', () => {agents: {noReader: { provider: 'openAI', fileConsumers: { executeCode: false, fileSearch: false } },runsCode: { provider: 'openAI', fileConsumers: { executeCode: true, fileSearch: false } },+ searches: { provider: 'openAI', fileConsumers: { executeCode: false, fileSearch: true } },unknown: { provider: 'openAI' },},fileConfig: {@@ -184,8 +185,9 @@ describe('createRunFileMessageEncoder', () => {},});- /* A tool serves a file only once it holds it, so the child that runs code keeps the file off- * its prompt for the copy the sandbox has, and receives the text for the one it does not. */+ /* Run Code uploads the file on its first call, so the child that runs code keeps it off the+ * prompt whether or not its sandbox holds a copy yet. File search serves only what its+ * store holds, so the searching child receives the text for a file never embedded. */const sandboxCsv: TFile = {...csv,metadata: {@@ -199,16 +201,18 @@ describe('createRunFileMessageEncoder', () => {},};- const [noReader, runsCode, unprovisioned, unknown] = await Promise.all([+ const [noReader, runsCode, unprovisioned, searches, unknown] = await Promise.all([harness.encode([csv], 'noReader'),harness.encode([sandboxCsv], 'runsCode'),harness.encode([csv], 'runsCode'),+ harness.encode([csv], 'searches'),harness.encode([csv], 'unknown'),]);expect(JSON.stringify(noReader[0].content)).toContain('region,total');expect(runsCode).toEqual([]);- expect(JSON.stringify(unprovisioned[0].content)).toContain('region,total');+ expect(unprovisioned).toEqual([]);+ expect(JSON.stringify(searches[0].content)).toContain('region,total');expect(unknown).toEqual([]);expect(harness.extractText).toHaveBeenCalledWith(expect.objectContaining({ attachments: [{ ...csv, llmDeliveryPath: 'text' }] }),@@ -363,6 +367,28 @@ describe('createRunFileMessageEncoder', () => {},);+ it('leaves code outputs with cleared sandbox references out of the child prompt and its count budget', async () => {+ /* Priming clears a dead reference on the turn's copy so the output is re-provisioned; the+ * output still belongs to the sandbox, so it neither reaches the prompt nor spends the+ * one-file budget. */+ const harness = setup({ fileConfig: { endpoints: { openAI: { fileLimit: 1 } } } });+ const output = (file_id: string): TFile => ({+ ...pdf,+ file_id,+ filename: `${file_id}.png`,+ type: 'image/png',+ text: undefined,+ llmDeliveryPath: undefined,+ context: FileContext.execute_code,+ metadata: {},+ });++ await expect(harness.encode([output('chart-a'), output('chart-b')], 'child')).resolves.toEqual(+ [],+ );+ expect(harness.encodeImages).not.toHaveBeenCalled();+ });+it('includes permanent child context in the count budget before encoding shared files', async () => {const harness = setup({agents: {diff --git a/packages/api/src/agents/files/encode.ts b/packages/api/src/agents/files/encode.tsindex a5312c5299..e04d6cbed8 100644--- a/packages/api/src/agents/files/encode.ts+++ b/packages/api/src/agents/files/encode.ts@@ -16,6 +16,7 @@ import type { BaseMessage } from '@librechat/agents/langchain';import type { ServerRequest, StrategyFunctions } from '~/types';import type { TokenCountFn } from '~/utils/text';import {+ isToolOwnedAttachment,isModelBoundAttachmentFile,assertAgentAttachmentLimits,AgentAttachmentPolicyError,@@ -160,13 +161,7 @@ export function createRunFileMessageEncoder(}/* Provisioning may add tool references to native files. Only legacy records use* those references to decide whether their bytes belong in the prompt. */- if (- deliveryPath !== 'provider' &&- (file.embedded === true ||- file.metadata?.codeEnvRef != null ||- file.metadata?.codeEnvRefs != null ||- file.metadata?.fileIdentifier != null)- ) {+ if (deliveryPath !== 'provider' && isToolOwnedAttachment(file)) {continue;}if (file.type.startsWith('image/')) {diff --git a/packages/data-provider/src/resolve-llm-delivery-path.spec.ts b/packages/data-provider/src/resolve-llm-delivery-path.spec.tsindex bc147bfd0f..ab3728cedd 100644--- a/packages/data-provider/src/resolve-llm-delivery-path.spec.ts+++ b/packages/data-provider/src/resolve-llm-delivery-path.spec.ts@@ -793,13 +793,22 @@ describe('hasTurnFileConsumer', () => {expect(hasTurnFileConsumer('video/mp4', { executeCode: false, fileSearch: true })).toBe(false);});- it('counts an enabled tool only where the record shows it holds the file', () => {+ it('counts File Search only where the record shows the vector store holds the file', () => {const consumers = { executeCode: false, fileSearch: true };expect(hasTurnFileConsumer('text/csv', consumers, { embedded: true })).toBe(true);expect(hasTurnFileConsumer('text/csv', consumers, { embedded: false })).toBe(false);expect(hasTurnFileConsumer('text/csv', consumers, {})).toBe(false);});+ it('counts an enabled Run Code as a reader before the sandbox holds a copy', () => {+ /* Its first call uploads the file, so no reference is needed in advance. The tool still+ * has to be able to read the type. */+ const consumers = { executeCode: true, fileSearch: false };+ expect(hasTurnFileConsumer('text/csv', consumers, {})).toBe(true);+ expect(hasTurnFileConsumer('text/csv', consumers, { metadata: {} })).toBe(true);+ expect(hasTurnFileConsumer(eml, consumers, {})).toBe(false);+ });+it('pairs the evidence with the tool that can read the type', () => {/* Only the sandbox holds this file, so the tool that can read an email export is the one* without a copy of it, while csv is served by the tool that has one. */@@ -955,16 +964,17 @@ describe('resolveTurnLLMDeliveryPath', () => {).toBe('text');});- it('delivers text when Run Code is on but no sandbox holds the file', () => {- /* A promoted destination is not uploaded to the sandbox at upload time, so the turn the- * file arrives on carries no reference either. */+ it('leaves a file Run Code can read with Run Code before the sandbox holds it', () => {+ /* Delivered text counts toward the turn's attachment limits. A turn those limits refuse+ * never runs code, so the file would never become held and every later turn would carry+ * the same text and be refused the same way. Run Code uploads the file on its first call. */expect(resolveTurnLLMDeliveryPath({file: routedCsv,consumers: { executeCode: true, fileSearch: false },endpointConfig,}),- ).toBe('text');+ ).toBe('none');});it('delivers text where the tool holding the file cannot read this type', () => {diff --git a/packages/data-provider/src/resolve-llm-delivery-path.ts b/packages/data-provider/src/resolve-llm-delivery-path.tsindex 1ea941bc55..6b41d378fc 100644--- a/packages/data-provider/src/resolve-llm-delivery-path.ts+++ b/packages/data-provider/src/resolve-llm-delivery-path.ts@@ -381,25 +381,25 @@ export function hasToolResourceProvisioning(file: TurnDeliveryFile, toolResource/*** Whether a tool this turn runs can read a file of this type.*- * Passing the record asks the stricter question a delivery decision needs: a tool serves a file- * only once it holds it. A file tool being enabled is not the same as the file having reached- * it, and an upload that named no destination is filed under no tool at all, so judging the- * tool set alone reads an empty vector store as a reader.+ * Passing the record asks the stricter question a delivery decision needs where a tool serves+ * only what it already holds. File search reads the vector store, and an upload that named no+ * destination is filed under no tool at all, so an enabled search tool is a reader only once+ * the record shows the store holds the file. Run Code needs no copy in advance: its first call+ * uploads every attachment it can read to the sandbox, so enabling it is enough. Requiring a+ * copy there would hand the file's text to the prompt on every turn before the first code run,+ * and a turn that refuses that text never runs code, so the file would never become held.*/export function hasTurnFileConsumer(mimeType: string,consumers: TurnFileConsumers,file?: TurnDeliveryFile,): boolean {- const holds = (toolResource: EToolResources): boolean =>- file == null || hasToolResourceProvisioning(file, toolResource);+ const searchHolds = file == null || hasToolResourceProvisioning(file, EToolResources.file_search);return (- (consumers.executeCode &&- canToolResourceConsume(EToolResources.execute_code, mimeType) &&- holds(EToolResources.execute_code)) ||+ (consumers.executeCode && canToolResourceConsume(EToolResources.execute_code, mimeType)) ||(consumers.fileSearch &&canToolResourceConsume(EToolResources.file_search, mimeType) &&- holds(EToolResources.file_search))+ searchHolds));}@@ -454,15 +454,15 @@ export function hasInferredLLMDeliveryPath(file: TurnDeliveryFile): boolean {* A record predating routing and a destination the user chose keep what they stored. An* inferred route re-resolves against the endpoint handling the turn. A `none` route leaves* the file for a tool; where the endpoint enables `textFallbackWithoutTools` and no tool this- * turn runs both reads the file and already holds it, the text extracted at upload is delivered- * rather than the file reaching nothing. Consumers left undefined are unknown and not judged, as- * in {@link resolveUploadDestination}.+ * turn runs can read the file, the text extracted at upload is delivered rather than the file+ * reaching nothing. Consumers left undefined are unknown and not judged, as in+ * {@link resolveUploadDestination}.*- * Holding the file is asked of the record rather than of the tool set, because the two disagree- * for the upload that needs the fallback most: one that named no destination is filed under no- * tool, so enabling file search would otherwise withhold the text for a vector store that never- * received the file, leaving the attachment readable by nothing. Deferred provisioning still- * fills that store on first use, which delivering the text does not prevent.+ * For file search, reading is asked of the record rather than of the tool set, because the two+ * disagree for the upload that needs the fallback most: one that named no destination is filed+ * under no tool, so enabling file search would otherwise withhold the text for a vector store+ * that never received the file. Run Code is judged by the tool set: see+ * {@link hasTurnFileConsumer}.*/export function resolveTurnLLMDeliveryPath(routing: Partial<TurnDeliveryRouting> | undefined,