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: Keep Attachment History From Locking Conversations (#16690)
lia-by-librechat[bot]de7755b4ca1c
diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.jsindex 6b8818d593..e7efd4ee99 100644--- a/api/server/controllers/agents/client.js+++ b/api/server/controllers/agents/client.js@@ -137,6 +137,9 @@ const {createAgentMemoryCallback,assertAgentAttachmentLimits,assertAgentAttachmentTopology,+ collectHistoricalAttachmentIds,+ admitSteerAttachmentHistory,+ rollbackSteerAttachmentHistory,isModelBoundAttachmentFile,isAgentAttachmentLimitError,isAttachmentObjectNotFoundError,@@ -411,6 +414,7 @@ class AgentClient extends BaseClient {);assertAgentAttachmentLimits({attachments: modelBoundAttachments,+ historicalFileIds: this.turnHistoricalAttachmentIds,req: this.options.req,endpoint: this.options.agent?.endpoint ?? this.options.endpoint,endpointType: this.options.endpointType,@@ -474,10 +478,15 @@ class AgentClient extends BaseClient {filters: this.options.req?.config?.filters,files: modelBoundFiles,});+ const historicalFileIds = collectHistoricalAttachmentIds(+ this.turnHistoricalAttachmentIds ?? [],+ modelBoundFiles,+ );const sharedAttachments = [...(this.turnSharedAttachmentFiles ?? []), ...modelBoundFiles];const scopedAttachmentsByAgentId = this.turnScopedAttachmentsByAgentId ?? new Map();assertAgentAttachmentTopology({sharedAttachments,+ historicalFileIds,scopedAttachmentsByAgentId,req: this.options.req,endpoint: this.options.agent?.endpoint ?? this.options.endpoint,@@ -488,6 +497,12 @@ class AgentClient extends BaseClient {[...sharedAttachments, ...(this.turnAggregateOnlyAttachmentFiles ?? [])],[...scopedAttachmentsByAgentId.values()].flat(),);+ this.turnSteerAttachmentHistory = admitSteerAttachmentHistory({+ state: this.turnSteerAttachmentHistory,+ historicalFileIds: this.turnHistoricalAttachmentIds,+ attachments: modelBoundFiles,+ });+ this.turnHistoricalAttachmentIds = this.turnSteerAttachmentHistory.historicalFileIds;this.turnSharedAttachmentFiles = sharedAttachments;this.attachmentMemoryContext?.attachments?.push(...modelBoundFiles);if (steerId && modelBoundFiles.length > 0) {@@ -501,6 +516,11 @@ class AgentClient extends BaseClient {this.getModelBoundAttachmentsForEndpoint(historicalAttachments);const compatibleCurrentAttachments =this.getModelBoundAttachmentsForEndpoint(currentAttachments);+ this.turnSteerAttachmentHistory = undefined;+ this.turnHistoricalAttachmentIds = collectHistoricalAttachmentIds(+ historicalAttachments,+ currentAttachments,+ );const sharedAttachments = [...compatibleHistoricalAttachments, ...compatibleCurrentAttachments];const sharedAttachmentIds = collectFileIds(sharedAttachments);const agents = collectReachableAgents([@@ -525,6 +545,7 @@ class AgentClient extends BaseClient {);assertAgentAttachmentTopology({sharedAttachments,+ historicalFileIds: this.turnHistoricalAttachmentIds,scopedAttachmentsByAgentId: scopedAttachmentMap,req: this.options.req,endpoint: this.options.agent?.endpoint ?? this.options.endpoint,@@ -741,6 +762,7 @@ class AgentClient extends BaseClient {this.steerOffsetState = { offset: 0 };this.appliedSteerParts = new Map();this.admittedSteerAttachments = new Map();+ this.turnSteerAttachmentHistory = undefined;/** @type {(messages: BaseMessage[], inspectionMessages?: BaseMessage[]) => Promise<void>} */this.processMemory;}@@ -924,6 +946,11 @@ class AgentClient extends BaseClient {};removeOccurrences(this.turnSharedAttachmentFiles);removeOccurrences(this.attachmentMemoryContext?.attachments);+ this.turnHistoricalAttachmentIds = rollbackSteerAttachmentHistory({+ state: this.turnSteerAttachmentHistory,+ historicalFileIds: this.turnHistoricalAttachmentIds,+ attachments: admitted,+ });}/**@@ -2460,12 +2487,18 @@ class AgentClient extends BaseClient {endpointType: this.options.endpointType,endpointsByAgentId,});+ this.turnSteerAttachmentHistory = undefined;+ this.turnHistoricalAttachmentIds = collectHistoricalAttachmentIds(+ this.authorizedHistoricalFiles?.values() ?? sharedAttachmentFiles,+ requestAttachments,+ );this.turnSharedAttachmentFiles = sharedAttachmentFiles;this.turnAggregateOnlyAttachmentFiles = retainedHistoricalFileContexts;this.turnScopedAttachmentsByAgentId = scopedAttachmentMap;this.turnAttachmentEndpointsByAgentId = endpointsByAgentId;assertAgentAttachmentTopology({sharedAttachments: sharedAttachmentFiles,+ historicalFileIds: this.turnHistoricalAttachmentIds,scopedAttachmentsByAgentId: scopedAttachmentMap,req: this.options.req,endpoint: this.options.agent?.endpoint ?? this.options.endpoint,@@ -2485,6 +2518,7 @@ class AgentClient extends BaseClient {attachmentsByAgentId: this.options.agentContextAttachmentsByAgentId,sharedRunAttachmentIds,sharedAttachments: sharedAttachmentFiles,+ historicalFileIds: this.turnHistoricalAttachmentIds,req: this.options.req,endpoint: this.options.agent?.endpoint ?? this.options.endpoint ?? EModelEndpoint.agents,endpointType: this.options.endpointType,@@ -3171,6 +3205,7 @@ class AgentClient extends BaseClient {attachmentsByAgentId: lateAttachmentsByAgentId,sharedRunAttachmentIds: liveSharedAttachmentIds,sharedAttachments: liveSharedAttachmentFiles,+ historicalFileIds: this.turnHistoricalAttachmentIds,req: this.options.req,endpoint: this.options.agent?.endpoint ?? this.options.endpoint,endpointType: this.options.endpointType,@@ -5493,6 +5528,11 @@ class AgentClient extends BaseClient {.call(this, requestFiles).filter((file) => !file?.file_id || !checkpointFileIds.has(file.file_id)),];+ this.turnSteerAttachmentHistory = undefined;+ this.turnHistoricalAttachmentIds = collectHistoricalAttachmentIds(+ resumeContentProjection.checkpointFiles,+ requestFiles,+ );const resumeSharedFileIds = collectFileIds(resumeSharedFiles);const resumeEndpointsByAgentId = new Map(agents@@ -5512,6 +5552,7 @@ class AgentClient extends BaseClient {attachmentsByAgentId: this.options.agentContextAttachmentsByAgentId,sharedRunAttachmentIds: resumeSharedFileIds,sharedAttachments: resumeSharedFiles,+ historicalFileIds: this.turnHistoricalAttachmentIds,req: this.options.req,endpoint: this.options.agent?.endpoint ?? this.options.endpoint ?? EModelEndpoint.agents,endpointType: this.options.endpointType,@@ -5637,6 +5678,7 @@ class AgentClient extends BaseClient {attachmentsByAgentId: lateAttachmentsByAgentId,sharedRunAttachmentIds: liveResumeSharedFileIds,sharedAttachments: liveResumeSharedFiles,+ historicalFileIds: this.turnHistoricalAttachmentIds,req: this.options.req,endpoint: this.options.agent?.endpoint ?? this.options.endpoint,endpointType: this.options.endpointType,diff --git a/api/server/controllers/agents/client.test.js b/api/server/controllers/agents/client.test.jsindex 7a62a1c31b..2c9ec60c04 100644--- a/api/server/controllers/agents/client.test.js+++ b/api/server/controllers/agents/client.test.js@@ -6237,6 +6237,159 @@ describe('AgentClient - titleConvo', () => {).resolves.toEqual(expect.objectContaining({ prompt: expect.any(Array) }));});+ it.each([3, 0])(+ 'continues with %i current files after cumulative history reaches the count limit',+ async (currentCount) => {+ client.options.resendFiles = true;+ const historical = Array.from({ length: currentCount ? 8 : 11 }, (_, index) =>+ makeTextFile(`history-${index}`, `history-${index}.txt`, 'history'),+ );+ const current = Array.from({ length: currentCount }, (_, index) =>+ makeTextFile(`current-${index}`, `current-${index}.txt`, 'current'),+ );+ client.options.attachments = Promise.resolve(current);+ require('~/models').getFiles.mockResolvedValue(historical);+ const messages = historical.map((file, index) => ({+ messageId: `history-message-${index}`,+ parentMessageId: index ? `history-message-${index - 1}` : null,+ isCreatedByUser: true,+ text: 'Inspect this file.',+ files: [{ file_id: file.file_id }],+ }));+ messages.push({+ messageId: 'current-message',+ parentMessageId: messages[messages.length - 1].messageId,+ isCreatedByUser: true,+ text: 'Continue.',+ });++ const replayedMessages = await client.addPreviousAttachments(messages);+ await expect(+ client.buildMessages(replayedMessages, 'current-message', {}),+ ).resolves.toEqual(expect.objectContaining({ prompt: expect.any(Array) }));+ expect(Object.values(client.message_file_map).flat()).toHaveLength(11);+ },+ );++ it('rejects an oversized current batch without blocking a later file-free turn', async () => {+ client.options.resendFiles = true;+ const files = Array.from({ length: 11 }, (_, index) =>+ makeTextFile(`rejected-${index}`, `rejected-${index}.txt`, 'context'),+ );+ client.options.attachments = files;+ await expect(+ client.buildMessages(+ [{ messageId: 'rejected-message', isCreatedByUser: true, text: 'Inspect files.' }],+ 'rejected-message',+ {},+ ),+ ).rejects.toMatchObject({ limitType: 'count', observed: 11, limit: 10 });++ client.options.attachments = [];+ client.message_file_map = {};+ require('~/models').getFiles.mockResolvedValue(files);+ const replayedMessages = await client.addPreviousAttachments([+ {+ messageId: 'rejected-message',+ isCreatedByUser: true,+ text: 'Inspect files.',+ files: files.map(({ file_id }) => ({ file_id })),+ },+ {+ messageId: 'recovery-message',+ parentMessageId: 'rejected-message',+ isCreatedByUser: true,+ text: 'Continue without new files.',+ },+ ]);+ await expect(client.buildMessages(replayedMessages, 'recovery-message', {})).resolves.toEqual(+ expect.objectContaining({ prompt: expect.any(Array) }),+ );+ });++ it('counts resubmitted historical files during steering without mutating rejected state', () => {+ const historical = Array.from({ length: 11 }, (_, index) =>+ makeTextFile(`history-${index}`, `history-${index}.txt`, 'context'),+ );+ client.turnSharedAttachmentFiles = historical;+ client.turnHistoricalAttachmentIds = new Set(historical.map(({ file_id }) => file_id));+ client.turnAttachmentEndpointsByAgentId = new Map([+ ['primary-agent', { endpoint: EModelEndpoint.openAI }],+ ]);++ expect(() => client.admitSteerAttachments(historical, 'rejected-steer')).toThrow(+ expect.objectContaining({ limitType: 'count', observed: 11, limit: 10 }),+ );+ expect(client.turnHistoricalAttachmentIds.size).toBe(11);+ expect(client.turnSharedAttachmentFiles).toBe(historical);+ expect(() => client.admitSteerAttachments([historical[0]], 'accepted-steer')).not.toThrow();+ expect(client.turnHistoricalAttachmentIds.has(historical[0].file_id)).toBe(false);+ });++ it('releases a failed historical resubmission before admitting later steer files', () => {+ mockReq.config.fileConfig = { endpoints: { openAI: { fileLimit: 1 } } };+ const historical = makeTextFile('history', 'history.txt', 'history');+ const current = makeTextFile('current', 'current.txt', 'current');+ client.turnSharedAttachmentFiles = [historical];+ client.turnHistoricalAttachmentIds = new Set([historical.file_id]);+ client.turnAttachmentEndpointsByAgentId = new Map([+ ['primary-agent', { endpoint: EModelEndpoint.openAI }],+ ]);+ client.attachmentMemoryContext = { attachments: [historical] };+ client.admitSteerAttachments([historical], 'failed-steer');++ client.rollbackSteerAttachmentAdmission('failed-steer');++ expect(client.turnHistoricalAttachmentIds).toEqual(new Set([historical.file_id]));+ expect(client.turnSharedAttachmentFiles).toEqual([historical]);+ expect(client.attachmentMemoryContext.attachments).toEqual([historical]);+ expect(() => client.admitSteerAttachments([current], 'later-steer')).not.toThrow();+ });++ it('keeps committed resubmissions counted when a later duplicate steer fails', () => {+ mockReq.config.fileConfig = { endpoints: { openAI: { fileLimit: 1 } } };+ const historical = makeTextFile('history', 'history.txt', 'history');+ const current = makeTextFile('current', 'current.txt', 'current');+ client.turnSharedAttachmentFiles = [historical];+ client.turnHistoricalAttachmentIds = new Set([historical.file_id]);+ client.turnAttachmentEndpointsByAgentId = new Map([+ ['primary-agent', { endpoint: EModelEndpoint.openAI }],+ ]);+ client.admitSteerAttachments([historical], 'accepted-steer');+ client.admittedSteerAttachments.delete('accepted-steer');+ client.admitSteerAttachments([historical], 'failed-steer');++ client.rollbackSteerAttachmentAdmission('failed-steer');++ expect(client.turnHistoricalAttachmentIds.has(historical.file_id)).toBe(false);+ expect(client.turnSharedAttachmentFiles).toEqual([historical, historical]);+ expect(() => client.admitSteerAttachments([current], 'later-steer')).toThrow(+ expect.objectContaining({ limitType: 'count', observed: 2, limit: 1 }),+ );+ });++ it.each([+ ['first', 'second'],+ ['second', 'first'],+ ])(+ 'restores an overlapping historical exclusion after rolling back %s then %s',+ (first, second) => {+ const historical = makeTextFile('history', 'history.txt', 'history');+ client.turnSharedAttachmentFiles = [historical];+ client.turnHistoricalAttachmentIds = new Set([historical.file_id]);+ client.admitSteerAttachments([historical], 'first');+ client.admitSteerAttachments([historical], 'second');++ client.rollbackSteerAttachmentAdmission(first);+ expect(client.turnHistoricalAttachmentIds.has(historical.file_id)).toBe(false);+ client.rollbackSteerAttachmentAdmission(second);+ expect(client.turnHistoricalAttachmentIds.has(historical.file_id)).toBe(true);+ expect(client.turnSharedAttachmentFiles).toEqual([historical]);+ client.rollbackSteerAttachmentAdmission(second);+ expect(client.turnHistoricalAttachmentIds.has(historical.file_id)).toBe(true);+ },+ );+it('rejects combined historical and current bytes before either batch is encoded', async () => {mockAgent.endpoint = 'Moonshot';client.options.endpointType = EModelEndpoint.custom;@@ -9764,7 +9917,7 @@ describe('AgentClient - resumeCompletion content protection', () => {).not.toThrow();});- it('reapplies aggregate attachment limits to persistent history on resume', async () => {+ it('does not reapply current attachment counts to persistent history on resume', async () => {const historicalFiles = Array.from({ length: 11 }, (_, index) => ({file_id: `resume-history-${index}`,filename: `history-${index}.txt`,@@ -9796,6 +9949,8 @@ describe('AgentClient - resumeCompletion content protection', () => {},}),});+ const resume = jest.fn().mockResolvedValue(undefined);+ mockCreateRun.mockResolvedValue({ resume, getCalibrationRatio: jest.fn(() => 0) });const context = makeContext(undefined);context.options.req.body.isTemporary = false;context.options.req.config.fileConfig = {@@ -9804,11 +9959,8 @@ describe('AgentClient - resumeCompletion content protection', () => {await expect(AgentClient.prototype.resumeCompletion.call(context, { resumeValue: {} }),- ).rejects.toMatchObject({- code: 'AGENT_ATTACHMENT_LIMIT_EXCEEDED',- limitType: 'count',- });- expect(mockCreateRun).not.toHaveBeenCalled();+ ).resolves.toBeUndefined();+ expect(resume).toHaveBeenCalledTimes(1);});it('counts a restored request file only once when it is already in the checkpoint', async () => {@@ -9878,7 +10030,7 @@ describe('AgentClient - resumeCompletion content protection', () => {]);});- it('counts checkpoint files retained in model state after endpoint policy tightens', async () => {+ it('preserves checkpoint files when the current file-count policy tightens', async () => {const checkpointFiles = [{file_id: 'retained-1',@@ -9910,6 +10062,8 @@ describe('AgentClient - resumeCompletion content protection', () => {}),});require('~/models').getFiles.mockResolvedValue(checkpointFiles);+ const resume = jest.fn().mockResolvedValue(undefined);+ mockCreateRun.mockResolvedValue({ resume, getCalibrationRatio: jest.fn(() => 0) });const context = makeContext(undefined);context.options.req.config.fileConfig = {endpoints: {@@ -9919,11 +10073,8 @@ describe('AgentClient - resumeCompletion content protection', () => {await expect(AgentClient.prototype.resumeCompletion.call(context, { resumeValue: {} }),- ).rejects.toMatchObject({- code: 'AGENT_ATTACHMENT_LIMIT_EXCEEDED',- limitType: 'count',- });- expect(mockCreateRun).not.toHaveBeenCalled();+ ).resolves.toBeUndefined();+ expect(resume).toHaveBeenCalledTimes(1);});it('reapplies each secondary agent endpoint limit on resume', async () => {diff --git a/client/src/components/Messages/Content/Error/ProviderError.tsx b/client/src/components/Messages/Content/Error/ProviderError.tsxindex cc42be9782..9c91205cd1 100644--- a/client/src/components/Messages/Content/Error/ProviderError.tsx+++ b/client/src/components/Messages/Content/Error/ProviderError.tsx@@ -115,6 +115,20 @@ export function UnclassifiedError({ json, text, message }: UnclassifiedErrorPropconst withoutPayload =jsonString !== '' ? text.replace(jsonString, () => payloadProse ?? '') : text;const prose = stripLangChainTroubleshootingUrl(withoutPayload).trim() || payloadProse;+ if (+ prose != null &&+ /^This turn exceeds the configured (attachment count|total attachment size|extracted document text) limit \(/.test(+ prose,+ )+ ) {+ return (+ <ErrorWithDetail+ headline={localize('com_error_attachment_limit')}+ detail={prose}+ label={localize('com_error_details_attachment')}+ />+ );+ }/** A payload that told us nothing usable is its own statement; otherwise name who failed. */const providerHeadline =provider != nulldiff --git a/client/src/components/Messages/Content/__tests__/Error.spec.tsx b/client/src/components/Messages/Content/__tests__/Error.spec.tsxindex de0c0772f4..ebdf167e7e 100644--- a/client/src/components/Messages/Content/__tests__/Error.spec.tsx+++ b/client/src/components/Messages/Content/__tests__/Error.spec.tsx@@ -153,6 +153,27 @@ beforeEach(() => {mockAccess = {};});+describe('LibreChat attachment limits', () => {+ it('recognizes fractional attachment-size limits', () => {+ const detail =+ 'This turn exceeds the configured total attachment size limit (128 > 104.8576). Remove some attachments or use smaller files and try again.';+ renderError(detail, providerMessage);+ expect(screen.getByText(catalog.com_error_attachment_limit)).toBeInTheDocument();+ expect(screen.getByText(detail)).toBeVisible();+ });++ it.each(['attachment count', 'total attachment size', 'extracted document text'])(+ 'does not blame the provider for the local %s limit',+ (label) => {+ const detail = `This turn exceeds the configured ${label} limit (11 > 10). Remove some attachments or use smaller files and try again.`;+ renderError(detail, providerMessage);+ expect(screen.getByText(catalog.com_error_attachment_limit)).toBeInTheDocument();+ expect(screen.queryByText('OpenAI could not complete this request.')).not.toBeInTheDocument();+ expect(screen.getByText(detail)).toBeVisible();+ },+ );+});+describe('Error — every client-facing error type', () => {/** The seeded gallery refuses to run while a member lacks a case; this is the renderer's half. */it.each([...Object.values(ErrorTypes), ...Object.values(ViolationTypes)])(diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex 5ab840ff30..d6d04718e3 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -622,6 +622,8 @@"com_error_no_user_key_admin": "No API key is configured for {{0}}. Ask an administrator to add one.","com_error_no_user_key_generic": "An API key is required to send messages.","com_error_non_browser": "This request was blocked because it did not come from a browser.",+ "com_error_attachment_limit": "LibreChat's attachment limit was exceeded. Remove some attachments or use smaller files and try again.",+ "com_error_details_attachment": "Attachment limit details","com_error_provider_failed": "{{0}} could not complete this request.","com_error_refusal": "{{0}} declined to answer this request. Rewrite your message and try again.","com_error_refusal_reason": "The model's explanation",diff --git a/packages/api/src/agents/attachments.test.ts b/packages/api/src/agents/attachments.test.tsindex 92610dae91..e4a7678143 100644--- a/packages/api/src/agents/attachments.test.ts+++ b/packages/api/src/agents/attachments.test.ts@@ -14,6 +14,9 @@ import {createAgentMemoryCallback,collectAgentAttachmentStats,collectFileIds,+ collectHistoricalAttachmentIds,+ admitSteerAttachmentHistory,+ rollbackSteerAttachmentHistory,buildAgentScopedContext,getAgentContextAttachments,buildAgentContextAttachmentsByAgentId,@@ -99,6 +102,86 @@ describe('agent attachment helpers', () => {]);});+ it('counts only new files while retaining historical context budgets', () => {+ const historical = Array.from({ length: 11 }, (_, index) => ({+ file_id: `history-${index}`,+ bytes: 10,+ text: 'context',+ }));+ const current = { file_id: 'current', bytes: 5, text: 'new' };+ const historicalFileIds = collectHistoricalAttachmentIds(historical, [current]);+ const stats = assertAgentAttachmentLimits({+ attachments: [...historical, current],+ historicalFileIds,+ fileConfig: { endpoints: { agents: { fileLimit: 1 } } },+ });++ expect(stats).toMatchObject({+ attachmentCount: 1,+ totalKnownBytes: 115,+ extractedTextChars: 80,+ });+ expect(() =>+ assertAgentAttachmentLimits({+ attachments: historical,+ historicalFileIds,+ fileConfig: { fileContextCharLimit: 10 },+ }),+ ).toThrow(expect.objectContaining({ limitType: 'extracted_text' }));+ expect(() =>+ assertAgentAttachmentLimits({+ attachments: historical,+ historicalFileIds,+ fileConfig: { fileContextSizeLimit: 0.00001 },+ }),+ ).toThrow(expect.objectContaining({ limitType: 'bytes' }));+ });++ it('counts resubmitted historical files and unidentified files as current', () => {+ const first = { file_id: 'first' };+ const second = { file_id: 'second' };+ const historicalFileIds = collectHistoricalAttachmentIds([first, second], [first]);+ expect(historicalFileIds).toEqual(new Set(['second']));+ expect(() =>+ assertAgentAttachmentLimits({+ attachments: [first, first, second, {}],+ historicalFileIds,+ fileConfig: { endpoints: { agents: { fileLimit: 1 } } },+ }),+ ).toThrow(expect.objectContaining({ limitType: 'count', observed: 2, limit: 1 }));+ });++ it('rolls back repeated historical occurrences without excluding a retained current file', () => {+ const historical = { file_id: 'history' };+ const current = { file_id: 'current' };+ const state = admitSteerAttachmentHistory({+ historicalFileIds: new Set([historical.file_id]),+ attachments: [historical, historical, current, {}],+ });+ expect(state.historicalFileIds).toEqual(new Set());+ rollbackSteerAttachmentHistory({ state, attachments: [historical] });+ expect(state.historicalFileIds).toEqual(new Set());+ const historicalFileIds = rollbackSteerAttachmentHistory({+ state,+ attachments: [historical, current, {}, { file_id: 'untracked' }],+ });+ expect(historicalFileIds).toEqual(new Set([historical.file_id]));+ expect(() =>+ assertAgentAttachmentLimits({+ attachments: [historical, current, { file_id: 'later' }],+ historicalFileIds,+ fileConfig: { endpoints: { agents: { fileLimit: 1 } } },+ }),+ ).toThrow(expect.objectContaining({ limitType: 'count', observed: 2 }));+ });++ it('preserves exclusions when a legacy admission has no history ledger', () => {+ const historicalFileIds = new Set(['history']);+ expect(+ rollbackSteerAttachmentHistory({ historicalFileIds, attachments: [{ file_id: 'history' }] }),+ ).toBe(historicalFileIds);+ });+it('counts bytes once per repeated model injection when requested', () => {const repeated = {file_id: 'replayed-pdf',@@ -555,6 +638,30 @@ describe('agent attachment helpers', () => {});});+ it('does not count historical shared or scoped files at context extraction', async () => {+ const historical = Array.from({ length: 11 }, (_, index) =>+ makeTextFile(`history-${index}`, `history-${index}.txt`, 'history'),+ );+ const current = makeTextFile('current', 'current.txt', 'current');+ const req = {+ body: { fileTokenLimit: 1000 },+ config: {},+ } as ServerRequest;+ req.config = {+ ...req.config!,+ fileConfig: { endpoints: { agents: { fileLimit: 1 } } },+ };+ await expect(+ buildAgentScopedContext({+ agentIds: ['agent-a'],+ sharedAttachments: [...historical.slice(0, 8), current],+ historicalFileIds: collectHistoricalAttachmentIds(historical, [current]),+ attachmentsByAgentId: new Map([['agent-a', historical.slice(8)]]),+ req,+ }),+ ).resolves.toEqual(new Map([['agent-a', expect.stringContaining('history')]]));+ });+it('rejects shared attachments incompatible with a receiving agent', async () => {const sharedAttachment = {...makeTextFile('shared-pdf', 'shared.pdf', ''),diff --git a/packages/api/src/agents/attachments.ts b/packages/api/src/agents/attachments.tsindex 447af3c921..04885b05c2 100644--- a/packages/api/src/agents/attachments.ts+++ b/packages/api/src/agents/attachments.ts@@ -238,7 +238,11 @@ export function isAgentAttachmentLimitError(export function collectAgentAttachmentStats(attachments?: Iterable<AttachmentTelemetryFile | null | undefined> | null,- options: { countRepeatedExtractedText?: boolean; countRepeatedBytes?: boolean } = {},+ options: {+ countRepeatedExtractedText?: boolean;+ countRepeatedBytes?: boolean;+ historicalFileIds?: ReadonlySet<string>;+ } = {},): AgentAttachmentStats {const stats: AgentAttachmentStats = {attachmentCount: 0,@@ -272,7 +276,9 @@ export function collectAgentAttachmentStats(Number.isFinite(file.metadata?.pageCount) && Number(file.metadata?.pageCount) >= 0? Number(file.metadata?.pageCount): undefined;- stats.attachmentCount += 1;+ if (!file.file_id || !options.historicalFileIds?.has(file.file_id)) {+ stats.attachmentCount += 1;+ }stats.totalKnownBytes += bytes;stats.extractedTextChars += extractedTextChars;stats.files.push({@@ -296,6 +302,7 @@ export function assertAgentAttachmentLimits({countRepeatedExtractedText = false,countRepeatedBytes = countRepeatedExtractedText,enforceAttachmentCount = true,+ historicalFileIds,useGlobalContextSizeLimit = false,}: {attachments?: Iterable<AttachmentTelemetryFile | null | undefined> | null;@@ -306,11 +313,14 @@ export function assertAgentAttachmentLimits({countRepeatedExtractedText?: boolean;countRepeatedBytes?: boolean;enforceAttachmentCount?: boolean;+ /** Replayed files consume context budgets, not the current submission's count allowance. */+ historicalFileIds?: ReadonlySet<string>;useGlobalContextSizeLimit?: boolean;}): AgentAttachmentStats {const stats = collectAgentAttachmentStats(attachments, {countRepeatedExtractedText,countRepeatedBytes,+ historicalFileIds,});const dynamicFileConfig = providedFileConfig ?? req?.config?.fileConfig;const fileConfig = mergeFileConfig(dynamicFileConfig);@@ -356,6 +366,7 @@ export function assertAgentAttachmentTopology({endpoint,endpointType,endpointsByAgentId,+ historicalFileIds,}: {sharedAttachments?: IMongoFile[];scopedAttachmentsByAgentId?: Map<string, IMongoFile[]>;@@ -363,6 +374,7 @@ export function assertAgentAttachmentTopology({endpoint?: string | null;endpointType?: string | null;endpointsByAgentId?: AgentAttachmentEndpointsByAgentId;+ historicalFileIds?: ReadonlySet<string>;}): void {const agentIds = new Set([...scopedAttachmentsByAgentId.keys(),@@ -394,6 +406,7 @@ export function assertAgentAttachmentTopology({endpoint: agentEndpoint?.endpoint,endpointType: agentEndpoint?.endpointType,countRepeatedExtractedText: true,+ historicalFileIds,});}assertAgentAttachmentLimits({@@ -523,6 +536,91 @@ export function collectFileIds<TFile extends FileWithId>(return fileIds;}+/** Excludes replayed files from count admission unless they are submitted again now. */+export function collectHistoricalAttachmentIds(+ historicalFiles: Iterable<FileWithId | string | null | undefined>,+ currentFiles: Iterable<FileWithId | null | undefined> = [],+): Set<string> {+ const fileIds = new Set<string>();+ for (const file of historicalFiles) {+ const fileId = typeof file === 'string' ? file : file?.file_id;+ if (fileId) {+ fileIds.add(fileId);+ }+ }+ for (const file of currentFiles) {+ if (file?.file_id) {+ fileIds.delete(file.file_id);+ }+ }+ return fileIds;+}++interface SteerAttachmentHistory {+ originalHistoricalFileIds: ReadonlySet<string>;+ historicalFileIds: Set<string>;+ currentFileCounts: Map<string, number>;+}++/** Tracks count admission separately from encoding so failed media can release its reservation. */+export function admitSteerAttachmentHistory({+ state,+ historicalFileIds,+ attachments,+}: {+ state?: SteerAttachmentHistory;+ historicalFileIds?: ReadonlySet<string>;+ attachments: Iterable<FileWithId | null | undefined>;+}): SteerAttachmentHistory {+ const admission = state ?? {+ originalHistoricalFileIds: new Set(historicalFileIds),+ historicalFileIds: new Set(historicalFileIds),+ currentFileCounts: new Map<string, number>(),+ };+ for (const file of attachments) {+ if (!file?.file_id || !admission.originalHistoricalFileIds.has(file.file_id)) {+ continue;+ }+ admission.currentFileCounts.set(+ file.file_id,+ (admission.currentFileCounts.get(file.file_id) ?? 0) + 1,+ );+ admission.historicalFileIds.delete(file.file_id);+ }+ return admission;+}++/** Restores historical exclusions only after every submission of that ID has rolled back. */+export function rollbackSteerAttachmentHistory({+ state,+ historicalFileIds,+ attachments,+}: {+ state?: SteerAttachmentHistory;+ historicalFileIds?: ReadonlySet<string>;+ attachments: Iterable<FileWithId | null | undefined>;+}): ReadonlySet<string> | undefined {+ if (!state) {+ return historicalFileIds;+ }+ for (const file of attachments) {+ const fileId = file?.file_id;+ const count = fileId ? state.currentFileCounts.get(fileId) : undefined;+ if (!fileId || !count) {+ continue;+ }+ if (count > 1) {+ state.currentFileCounts.set(fileId, count - 1);+ continue;+ }+ state.currentFileCounts.delete(fileId);+ if (state.originalHistoricalFileIds.has(fileId)) {+ state.historicalFileIds.add(fileId);+ }+ }+ return state.historicalFileIds;+}+export function buildAgentContextAttachmentsByAgentId<TFile extends FileWithId>(configs: Iterable<AgentContextAttachmentCarrier<TFile> | null | undefined>,): Map<string, TFile[]> {@@ -619,6 +717,7 @@ export async function buildAgentScopedContext({attachmentsByAgentId,sharedRunAttachmentIds,sharedAttachments = [],+ historicalFileIds,req,tokenCountFn = countTokens,endpoint,@@ -629,6 +728,7 @@ export async function buildAgentScopedContext({attachmentsByAgentId: AgentContextAttachmentsByAgentId<IMongoFile>;sharedRunAttachmentIds?: Set<string>;sharedAttachments?: IMongoFile[];+ historicalFileIds?: ReadonlySet<string>;req?: ServerRequest;tokenCountFn?: TokenCountFn;endpoint?: string | null;@@ -649,6 +749,7 @@ export async function buildAgentScopedContext({assertAgentAttachmentTopology({sharedAttachments,scopedAttachmentsByAgentId: new Map(attachmentEntries),+ historicalFileIds,req,endpoint,endpointType,