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
🎒 feat: Carry Project Context Across Conversations (#15684)
Marco Berettae1e1d1b19d24
diff --git a/api/server/controllers/agents/__tests__/callbacks.spec.js b/api/server/controllers/agents/__tests__/callbacks.spec.jsindex c3c3262cf9..9307edef94 100644--- a/api/server/controllers/agents/__tests__/callbacks.spec.js+++ b/api/server/controllers/agents/__tests__/callbacks.spec.js@@ -40,6 +40,7 @@ jest.mock('@librechat/api', () => ({jest.mock('@librechat/data-schemas', () => ({logger: {debug: jest.fn(),+ info: jest.fn(),error: jest.fn(),warn: jest.fn(),},diff --git a/api/server/controllers/agents/__tests__/modelEndHandler.spec.js b/api/server/controllers/agents/__tests__/modelEndHandler.spec.jsindex 0b4f1c8f06..e2d0880ae9 100644--- a/api/server/controllers/agents/__tests__/modelEndHandler.spec.js+++ b/api/server/controllers/agents/__tests__/modelEndHandler.spec.js@@ -1,5 +1,5 @@jest.mock('@librechat/data-schemas', () => ({- logger: { error: jest.fn(), debug: jest.fn() },+ logger: { error: jest.fn(), debug: jest.fn(), info: jest.fn() },}));jest.mock('@librechat/api', () => {const { getModelRefusalInfo } = jest.requireActual('@librechat/api');diff --git a/api/server/controllers/agents/__tests__/openai.spec.js b/api/server/controllers/agents/__tests__/openai.spec.jsindex 25ae7ab602..7ca66410c9 100644--- a/api/server/controllers/agents/__tests__/openai.spec.js+++ b/api/server/controllers/agents/__tests__/openai.spec.js@@ -158,6 +158,7 @@ jest.mock('nanoid', () => ({jest.mock('@librechat/data-schemas', () => ({logger: {debug: jest.fn(),+ info: jest.fn(),error: jest.fn(),warn: jest.fn(),},@@ -179,6 +180,9 @@ jest.mock('@librechat/api', () => ({/* Provisioning moved into this package; the controllers build the callback from it. */createProvisionFilesCallback: () => async () => {},createAgentExecutionContext: (context) => context,+ resolveApiConversationProject: jest.fn((...args) =>+ jest.requireActual('@librechat/api').resolveApiConversationProject(...args),+ ),/** Grants both by default; the capability set is what these specs vary. */resolveToolRoleGrants: jest.fn(async () => ({runCode: true,@@ -453,8 +457,8 @@ const mockBulkInsertTransactions = jest.fn().mockResolvedValue(undefined);jest.mock('~/models', () => ({getAgent: jest.fn().mockResolvedValue({ id: 'agent-123', name: 'Test Agent' }),+ getProjectFiles: jest.fn(),getFiles: jest.fn(),- getUserKey: jest.fn(),getMessages: jest.fn(),updateFilesUsage: jest.fn(),getUserKeyValues: jest.fn(),@@ -1553,7 +1557,7 @@ describe('OpenAIChatCompletionController', () => {it('should return 404 when conversation is not owned by user', async () => {const { validateRequest } = require('@librechat/api');- const { getConvo } = require('~/models');+ const { getConvo, getAgent } = require('~/models');validateRequest.mockReturnValueOnce({request: {model: 'agent-123',@@ -1563,11 +1567,100 @@ describe('OpenAIChatCompletionController', () => {},});getConvo.mockResolvedValueOnce(null);-+ getAgent.mockRejectedValueOnce(new Error('speculative agent lookup failed'));await OpenAIChatCompletionController(req, res);expect(getConvo).toHaveBeenCalledWith('user-123', 'convo-abc');expect(res.status).toHaveBeenCalledWith(404);});+ it('starts the agent read while owner-scoped conversation validation is in flight', async () => {+ const api = require('@librechat/api');+ const models = require('~/models');+ models.getConvo.mockResolvedValueOnce({ conversationId: 'convo-abc', user: 'user-123' });+ let resolveAgent;+ models.getAgent.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveAgent = resolve;+ }),+ );+ api.resolveApiConversationProject.mockImplementationOnce(async (...args) => {+ expect(models.getAgent).toHaveBeenCalledWith({ id: 'agent-123' });+ resolveAgent({ id: 'agent-123', name: 'Test Agent' });+ return jest.requireActual('@librechat/api').resolveApiConversationProject(...args);+ });+ api.validateRequest.mockReturnValueOnce({+ request: {+ model: 'agent-123',+ messages: [],+ stream: false,+ conversation_id: 'convo-abc',+ },+ });++ await OpenAIChatCompletionController(req, res);++ expect(models.getAgent.mock.invocationCallOrder[0]).toBeLessThan(+ models.getConvo.mock.invocationCallOrder[0],+ );+ expect(api.initializeAgent).toHaveBeenCalled();+ });++ it('keeps Project-unavailable errors as client not-found responses', async () => {+ const api = require('@librechat/api');+ const models = require('~/models');+ api.validateRequest.mockReturnValueOnce({+ request: {+ model: 'agent-123',+ messages: [],+ stream: false,+ conversation_id: 'convo-abc',+ },+ });+ models.getAgent.mockRejectedValueOnce(new Error('speculative agent lookup failed'));+ api.resolveApiConversationProject.mockResolvedValueOnce({+ ok: false,+ status: 404,+ reason: 'unavailable',+ message: 'Conversation context unavailable',+ });++ await OpenAIChatCompletionController(req, res);++ expect(res.status).toHaveBeenCalledWith(404);+ const errorCall = api.createErrorResponse.mock.calls.at(-1);+ expect(errorCall[1]).toBe('invalid_request_error');+ expect(errorCall[2]).toBeNull();+ expect(api.initializeAgent).not.toHaveBeenCalled();+ });++ it('rechecks conversation existence after enrollment before initializing a provider', async () => {+ const api = require('@librechat/api');+ const models = require('~/models');+ api.validateRequest.mockReturnValueOnce({+ request: {+ model: 'agent-123',+ messages: [{ role: 'user', content: 'Hello' }],+ stream: false,+ conversation_id: 'convo-abc',+ },+ });+ let deleted = false;+ models.getConvo.mockImplementation(async () =>+ deleted ? null : { conversationId: 'convo-abc', user: 'user-123' },+ );+ mockEnrollAgentExecution.mockImplementationOnce(async () => {+ deleted = true;+ return mockExecution;+ });++ await OpenAIChatCompletionController(req, res);++ expect(mockEnrollAgentExecution).toHaveBeenCalledTimes(1);+ expect(api.initializeAgent).not.toHaveBeenCalled();+ expect(api.createRun).not.toHaveBeenCalled();+ expect(mockProcessStream).not.toHaveBeenCalled();+ expect(res.status).toHaveBeenCalledWith(404);+ });it('should proceed when conversation is owned by user', async () => {const { validateRequest } = require('@librechat/api');@@ -1588,7 +1681,7 @@ describe('OpenAIChatCompletionController', () => {});it('should return 500 when getConvo throws a DB error', async () => {- const { validateRequest } = require('@librechat/api');+ const { validateRequest, createErrorResponse } = require('@librechat/api');const { getConvo } = require('~/models');validateRequest.mockReturnValueOnce({request: {@@ -1602,6 +1695,7 @@ describe('OpenAIChatCompletionController', () => {await OpenAIChatCompletionController(req, res);expect(res.status).toHaveBeenCalledWith(500);+ expect(createErrorResponse.mock.calls.at(-1)[1]).toBe('server_error');});});diff --git a/api/server/controllers/agents/__tests__/request.partialDisconnect.spec.js b/api/server/controllers/agents/__tests__/request.partialDisconnect.spec.jsindex 3c3e23f74d..b725dd45cf 100644--- a/api/server/controllers/agents/__tests__/request.partialDisconnect.spec.js+++ b/api/server/controllers/agents/__tests__/request.partialDisconnect.spec.js@@ -77,6 +77,10 @@ jest.mock('@librechat/api', () => ({jest.requireActual('@librechat/api').resolvePersistableCodeEnvironmentDecision(...args),getSafeErrorMetadata: jest.requireActual('@librechat/api').getSafeErrorMetadata,getSafeErrorText: jest.requireActual('@librechat/api').getSafeErrorText,+ startAgentProjectContextResolution:+ jest.requireActual('@librechat/api').startAgentProjectContextResolution,+ assertChatProjectInstructions: jest.requireActual('@librechat/api').assertChatProjectInstructions,+ getChatProjectTurnFailure: jest.requireActual('@librechat/api').getChatProjectTurnFailure,GenerationJobManager: mockGenerationJobManager,getReferencedQuotes: jest.fn(() => null),cleanupMCPRequestContext: jest.fn(),@@ -166,6 +170,12 @@ describe('ResumableAgentController tenant context', () => {user,jobRecord = { createdAt: 1000, contextMeta: partialContextMeta },) => {+ mockGetConvo.mockResolvedValue({+ conversationId: 'conversation-123',+ user: user.id,+ tenantId: user.tenantId,+ createdAt: '2026-07-31T00:00:00.000Z',+ });let allSubscribersLeftHandler;mockGenerationJobManager.getJobStore.mockReturnValue({getJob: jest.fn().mockResolvedValue(jobRecord),diff --git a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.jsindex da907e363e..0981b5fa62 100644--- a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js+++ b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js@@ -67,6 +67,8 @@ const mockFilterPersistableAbortContent = jest.fn((content) =>content.filter((part) => part?.type !== 'tool_call'),);const mockGetConvo = jest.fn();+const mockGetChatProject = jest.fn();+const mockGetFiles = jest.fn();const mockGetMessages = jest.fn();const mockStampConvoLastResponse = jest.fn().mockResolvedValue(undefined);const mockSaveMessage = jest.fn();@@ -302,6 +304,10 @@ jest.mock('@librechat/api', () => ({getSafeErrorText: jest.requireActual('@librechat/api').getSafeErrorText,resolveFailedTurnContent: jest.requireActual('@librechat/api').resolveFailedTurnContent,getFailedTurnTraceFields: (...args) => mockGetFailedTurnTraceFields(...args),+ startAgentProjectContextResolution:+ jest.requireActual('@librechat/api').startAgentProjectContextResolution,+ assertChatProjectInstructions: jest.requireActual('@librechat/api').assertChatProjectInstructions,+ getChatProjectTurnFailure: jest.requireActual('@librechat/api').getChatProjectTurnFailure,GenerationJobManager: mockGenerationJobManager,getReferencedQuotes: jest.fn((quotes) => {if (!Array.isArray(quotes)) {@@ -392,6 +398,8 @@ jest.mock('~/models', () => ({appendConvoMessageReference: (...args) => mockAppendConvoMessageReference(...args),getMessages: (...args) => mockGetMessages(...args),getConvo: (...args) => mockGetConvo(...args),+ getChatProject: (...args) => mockGetChatProject(...args),+ getProjectFiles: (...args) => mockGetFiles(...args),getAgentEventActorSnapshot: (...args) => mockGetAgentEventActorSnapshot(...args),commitAgentEventActorState: (...args) => mockCommitAgentEventActorState(...args),beginAgentEventActorLegacyTurn: (...args) => mockBeginAgentEventActorLegacyTurn(...args),@@ -463,7 +471,13 @@ describe('ResumableAgentController resume metadata', () => {mockMCPContexts = new WeakMap();mockCheckAndIncrementPendingRequest.mockResolvedValue({ allowed: true });mockDecrementPendingRequest.mockResolvedValue(undefined);- mockGetConvo.mockResolvedValue({ createdAt: '2026-06-07T00:00:00.000Z' });+ mockGetConvo.mockImplementation(async (user, conversationId) => ({+ user,+ conversationId,+ createdAt: '2026-06-07T00:00:00.000Z',+ }));+ mockGetChatProject.mockReset().mockResolvedValue(null);+ mockGetFiles.mockReset().mockResolvedValue([]);mockGetMessages.mockResolvedValue([]);mockIsAgentTriggerPrincipalActive.mockResolvedValue(true);mockIsSubagentOwnerAdmissible.mockResolvedValue(true);@@ -1207,6 +1221,11 @@ describe('ResumableAgentController resume metadata', () => {const req = {_isAgentTrigger: true,user: { id: 'user-123', tenantId: 'tenant-1' },+ resolvedConversation: {+ conversationId: 'conversation-123',+ user: 'user-123',+ tenantId: 'tenant-1',+ },body: {text: 'Run the queued turn.',messageId: 'queued-user-message',@@ -1239,6 +1258,11 @@ describe('ResumableAgentController resume metadata', () => {const req = {_isAgentTrigger: true,user: { id: 'user-123', tenantId: 'tenant-1' },+ resolvedConversation: {+ conversationId: 'conversation-123',+ user: 'user-123',+ tenantId: 'tenant-1',+ },body: {text: 'Run the queued turn.',messageId: 'queued-user-message',@@ -1321,66 +1345,6 @@ describe('ResumableAgentController resume metadata', () => {);});- it('prefetches conversation state before admission and joins it with job metadata', async () => {- let resolveConversation;- let signalMetadataStarted;- const conversationPromise = new Promise((resolve) => {- resolveConversation = resolve;- });- const metadataStarted = new Promise((resolve) => {- signalMetadataStarted = resolve;- });- mockGetConvo.mockReturnValue(conversationPromise);- mockGenerationJobManager.createJob.mockImplementation(() => {- signalMetadataStarted();- return Promise.resolve({- createdAt: 1000,- readyPromise: Promise.resolve(),- abortController: new AbortController(),- emitter: { on: jest.fn() },- });- });- const initializeClient = jest.fn().mockRejectedValue(new Error('stop after startup reads'));- const conversationId = 'conversation-123';- const req = {- user: { id: 'user-123' },- body: {- text: 'Run independent startup work together.',- messageId: 'user-message',- parentMessageId: 'parent-message',- conversationId,- endpointOption: {- endpoint: 'agents',- modelOptions: { model: 'gpt-4.1' },- },- },- config: {},- };- const res = createResumableResponse();-- const controllerPromise = AgentController(req, res, jest.fn(), initializeClient, null);- expect(mockGetConvo).toHaveBeenCalledWith('user-123', conversationId);- await metadataStarted;- await nextTick();-- expect(mockGetConvo.mock.invocationCallOrder[0]).toBeLessThan(- mockCheckAndIncrementPendingRequest.mock.invocationCallOrder[0],- );- expect(res.json).toHaveBeenCalledWith({- streamId: conversationId,- conversationId,- generationCreatedAt: 1000,- status: 'started',- generationProtocolVersion: 1,- });- expect(initializeClient).not.toHaveBeenCalled();-- resolveConversation({ createdAt: '2026-06-07T00:00:00.000Z' });- await controllerPromise;-- expect(initializeClient).toHaveBeenCalledTimes(1);- });-it('keeps request-scoped MCP connections until resumable initialization finishes', async () => {const conversationId = 'conversation-123';const disconnect = jest.fn().mockResolvedValue(undefined);@@ -3971,7 +3935,70 @@ describe('ResumableAgentController resume metadata', () => {expect(mockSaveConvo).not.toHaveBeenCalled();});- it('creates the conversation row for a failed first turn', async () => {+ it.each([false, true])(+ 'creates the conversation row for a failed first turn (authorized project: %s)',+ async (hasAuthorizedProject) => {+ const res = createResumableResponse();+ mockGenerationJobManager.claimGeneration.mockImplementation(+ async (_userId, _clientRequestId, streamId, claimedConversationId) =>+ wonGenerationClaim({ streamId, conversationId: claimedConversationId }),+ );+ const req = createFailedRequest({+ conversationId: undefined,+ clientRequestId: 'failed-new-conversation',+ agent_id: 'unverified-agent',+ parentMessageId: '00000000-0000-0000-0000-000000000000',+ endpointOption: {+ endpoint: 'azureOpenAI',+ agent_id: 'unverified-agent',+ modelOptions: { model: 'gpt-4o' },+ ...(hasAuthorizedProject && { chatProjectId: '507f1f77ebcf86cd799439011' }),+ },+ });+ if (hasAuthorizedProject) {+ req.chatProjectContext = {+ projectId: '507f1f77bcf86cd799439012',+ contextRevision: 0,+ instructions: '',+ file_ids: [],+ };+ }++ await AgentController(+ req,+ res,+ jest.fn(),+ jest.fn().mockRejectedValue(new Error('model unavailable')),+ null,+ );++ const mintedConversationId = res.json.mock.calls[0][0].conversationId;+ expect(mockSaveMessage).toHaveBeenCalledWith(+ expect.any(Object),+ expect.objectContaining({+ messageId: 'user-message_',+ conversationId: mintedConversationId,+ }),+ expect.any(Object),+ );+ expect(mockSaveConvo).toHaveBeenCalledWith(+ expect.objectContaining({ userId: 'user-123' }),+ expect.objectContaining({+ conversationId: mintedConversationId,+ endpoint: 'azureOpenAI',+ model: 'gpt-4o',+ }),+ expect.objectContaining({ initialAgentId: null }),+ );+ const savedConversation = mockSaveConvo.mock.calls[0][1];+ if (hasAuthorizedProject) {+ expect(savedConversation.chatProjectId).toBe('507f1f77bcf86cd799439012');+ } else {+ expect(savedConversation).not.toHaveProperty('chatProjectId');+ }+ },+ );+ it('persists the normalized code-environment decision on a failed first turn', async () => {const res = createResumableResponse();mockGenerationJobManager.claimGeneration.mockImplementation(async (_userId, _clientRequestId, streamId, claimedConversationId) =>@@ -3979,14 +4006,13 @@ describe('ResumableAgentController resume metadata', () => {);const req = createFailedRequest({conversationId: undefined,- clientRequestId: 'failed-new-conversation',+ clientRequestId: 'failed-code-environment',agent_id: 'unverified-agent',parentMessageId: '00000000-0000-0000-0000-000000000000',endpointOption: {endpoint: 'azureOpenAI',agent_id: 'unverified-agent',modelOptions: { model: 'gpt-4o' },- chatProjectId: '507f1f77bcf86cd799439011',},codeEnvironmentMode: 'attached',codeWorkspaces: [{ environmentId: 'personal-vm', workspaceId: 'project-a' }],@@ -4002,21 +4028,10 @@ describe('ResumableAgentController resume metadata', () => {await AgentController(req, res, jest.fn(), initializeClient, null);const mintedConversationId = res.json.mock.calls[0][0].conversationId;- expect(mockSaveMessage).toHaveBeenCalledWith(- expect.any(Object),- expect.objectContaining({- messageId: 'user-message_',- conversationId: mintedConversationId,- }),- expect.any(Object),- );expect(mockSaveConvo).toHaveBeenCalledWith(- expect.objectContaining({ userId: 'user-123' }),+ expect.any(Object),expect.objectContaining({conversationId: mintedConversationId,- endpoint: 'azureOpenAI',- model: 'gpt-4o',- chatProjectId: '507f1f77bcf86cd799439011',codeEnvironmentMode: 'attached',codeWorkspaces: [{ environmentId: 'personal-vm', workspaceId: 'project-a' }],}),@@ -4086,6 +4101,128 @@ describe('ResumableAgentController resume metadata', () => {);});});+ describe('agent project preflight', () => {+ beforeEach(() => {+ mockGenerationJobManager.claimGeneration.mockImplementation(+ async (_userId, _clientRequestId, streamId, conversationId) =>+ wonGenerationClaim({ streamId, conversationId }),+ );+ });++ const createProjectRequest = ({ conversationId, clientRequestId = 'project-preflight' }) => ({+ user: { id: 'user-123', tenantId: 'tenant-1' },+ body: {+ text: 'Use the selected project.',+ messageId: 'project-user-message',+ clientRequestId,+ ...(conversationId !== undefined && { conversationId }),+ endpointOption: {+ endpoint: 'agents',+ modelOptions: { model: 'gpt-4o' },+ chatProjectId: 'project-1',+ },+ },+ config: {},+ });++ it('rejects a new conversation whose requested project is missing before creating a job', async () => {+ mockGetConvo.mockResolvedValue({ user: 'user-123', tenantId: 'tenant-1' });+ mockGetChatProject.mockResolvedValue(null);+ const initializeClient = jest.fn();+ const res = createResumableResponse();++ await AgentController(createProjectRequest({}), res, jest.fn(), initializeClient, null);++ expect(res.status).toHaveBeenCalledWith(404);+ expect(res.json).toHaveBeenCalledWith(+ expect.objectContaining({ error: 'Conversation context unavailable' }),+ );+ expect(mockGenerationJobManager.createJob).not.toHaveBeenCalled();+ expect(initializeClient).not.toHaveBeenCalled();++ expect(mockSaveMessage).not.toHaveBeenCalled();+ expect(mockSaveConvo).not.toHaveBeenCalled();+ expect(mockGenerationJobManager.releaseGeneration).toHaveBeenCalled();+ expect(mockDecrementPendingRequest).toHaveBeenCalledWith('user-123');+ });++ it.each([+ ['missing', null],+ [+ 'foreign-tenant',+ { _id: 'project-1', tenantId: 'tenant-2', instructions: '', file_ids: [] },+ ],+ ])(+ 'continues an existing conversation without context when its stored project is %s',+ async (_label, storedProject) => {+ mockGetConvo.mockResolvedValue({+ conversationId: 'conversation-123',+ chatProjectId: 'project-1',+ user: 'user-123',+ tenantId: 'tenant-1',+ });+ mockGetChatProject.mockResolvedValue(storedProject);+ const req = createProjectRequest({+ conversationId: 'conversation-123',+ clientRequestId: `project-${_label}`,+ });+ const res = createResumableResponse();++ await AgentController(req, res, jest.fn(), jest.fn(), null);++ expect(res.status).not.toHaveBeenCalledWith(404);+ expect(req.chatProjectContext).toBeNull();+ expect(mockGenerationJobManager.createJob).toHaveBeenCalled();+ },+ );++ it('rejects project instructions by policy before admission reaches a provider', async () => {+ mockGetConvo.mockResolvedValue({+ conversationId: 'conversation-123',+ chatProjectId: 'project-1',+ user: 'user-123',+ tenantId: 'tenant-1',+ });+ mockGetChatProject.mockResolvedValue({+ _id: 'project-1',+ tenantId: 'tenant-1',+ instructions: 'Use sk_project_secret in every answer.',+ contextRevision: 1,+ file_ids: [],+ });+ mockGetFiles.mockResolvedValue([]);+ const req = createProjectRequest({ conversationId: 'conversation-123' });+ req.config.filters = {+ agentInstructions: {+ pii: {+ fields: ['instructions'],+ starterPatterns: [],+ customPatterns: [+ { id: 'project-secret', label: 'Project secret', regex: 'sk_project_secret' },+ ],+ },+ },+ };+ const initializeClient = jest.fn();+ const res = createResumableResponse();++ await AgentController(req, res, jest.fn(), initializeClient, null);++ expect(res.status).toHaveBeenCalledWith(400);+ expect(res.json).toHaveBeenCalledWith(+ expect.objectContaining({+ error: 'content_filter_block',+ source: 'agent_instruction',+ field: 'instructions',+ }),+ );+ expect(JSON.stringify(res.json.mock.calls)).not.toContain('sk_project_secret');+ expect(mockGenerationJobManager.createJob).not.toHaveBeenCalled();+ expect(initializeClient).not.toHaveBeenCalled();+ expect(mockSaveMessage).not.toHaveBeenCalled();+ expect(mockSaveConvo).not.toHaveBeenCalled();+ });+ });it.each([new (jest.requireActual('@librechat/api').OpenIDReauthRequiredError)(@@ -4702,16 +4839,29 @@ describe('ResumableAgentController resume metadata', () => {);});- it.each(['submitted', 'persisted', 'overridden'])(+ it.each(['submitted', 'persisted', 'overridden', 'loaded'])('preserves %s workspace selections in the runtime envelope',async (source) => {mockGenerationJobManager.claimGeneration.mockResolvedValue(wonGenerationClaim());const initializeClient = jest.fn().mockRejectedValue(new Error('stop before tool loading'));const codeWorkspaces = [{ environmentId: 'machine-a', workspaceId: 'project-b' }];+ const persistedConversation = {+ conversationId: 'conversation-123',+ user: 'user-123',+ codeWorkspaces,+ };+ let resolveStoredConversation;+ if (source === 'loaded') {+ mockGetConvo.mockReturnValueOnce(+ new Promise((resolve) => {+ resolveStoredConversation = resolve;+ }),+ );+ }const req = {user: { id: 'user-123' },- ...(source !== 'submitted'- ? { resolvedConversation: { conversationId: 'conversation-123', codeWorkspaces } }+ ...(source === 'persisted' || source === 'overridden'+ ? { resolvedConversation: persistedConversation }: {}),body: {...(source === 'submitted' ? { codeWorkspaces } : {}),@@ -4733,7 +4883,12 @@ describe('ResumableAgentController resume metadata', () => {set: jest.fn(),};- await AgentController(req, res, jest.fn(), initializeClient, null);+ const controllerPromise = AgentController(req, res, jest.fn(), initializeClient, null);+ if (source === 'loaded') {+ await nextTick();+ resolveStoredConversation(persistedConversation);+ }+ await controllerPromise;expect(initializeClient).toHaveBeenCalledWith(expect.objectContaining({@@ -5913,6 +6068,11 @@ describe('ResumableAgentController resume metadata', () => {mockAcquireEventChildGenerationLease.mockResolvedValue(null);const req = {user: { id: 'user-123', tenantId: 'tenant-1' },+ resolvedConversation: {+ conversationId: 'child-conversation',+ user: 'user-123',+ tenantId: 'tenant-1',+ },body: {text: 'This event arrived too late.',messageId: 'user-msg',diff --git a/api/server/controllers/agents/__tests__/responses.unit.spec.js b/api/server/controllers/agents/__tests__/responses.unit.spec.jsindex e8b1f2e7ab..15bcdfa0b6 100644--- a/api/server/controllers/agents/__tests__/responses.unit.spec.js+++ b/api/server/controllers/agents/__tests__/responses.unit.spec.js@@ -181,6 +181,7 @@ jest.mock('uuid', () => ({jest.mock('@librechat/data-schemas', () => ({logger: {debug: jest.fn(),+ info: jest.fn(),error: jest.fn(),warn: jest.fn(),},@@ -202,6 +203,9 @@ jest.mock('@librechat/api', () => ({/* Provisioning moved into this package; the controllers build the callback from it. */createProvisionFilesCallback: () => async () => {},createAgentExecutionContext: (context) => context,+ resolveApiConversationProject: jest.fn((...args) =>+ jest.requireActual('@librechat/api').resolveApiConversationProject(...args),+ ),/** Grants both by default; the capability set is what these specs vary. */resolveToolRoleGrants: jest.fn(async () => ({runCode: true,@@ -540,8 +544,8 @@ const mockBulkInsertTransactions = jest.fn().mockResolvedValue(undefined);jest.mock('~/models', () => ({getAgent: jest.fn().mockResolvedValue({ id: 'agent-123', name: 'Test Agent' }),+ getProjectFiles: jest.fn(),getFiles: jest.fn(),- getUserKey: jest.fn(),getMessages: jest.fn().mockResolvedValue([]),saveMessage: jest.fn().mockResolvedValue({}),updateFilesUsage: jest.fn(),@@ -2069,7 +2073,7 @@ describe('createResponse controller', () => {it('should return 404 when conversation is not owned by user', async () => {const { validateResponseRequest, sendResponsesErrorResponse } = require('@librechat/api');- const { getConvo } = require('~/models');+ const { getConvo, getAgent } = require('~/models');validateResponseRequest.mockReturnValueOnce({request: {model: 'agent-123',@@ -2079,6 +2083,7 @@ describe('createResponse controller', () => {},});getConvo.mockResolvedValueOnce(null);+ getAgent.mockRejectedValueOnce(new Error('speculative agent lookup failed'));await createResponse(req, res);expect(getConvo).toHaveBeenCalledWith('user-123', 'resp_abc');@@ -2089,6 +2094,95 @@ describe('createResponse controller', () => {'not_found',);});+ it('starts the agent read while owner-scoped conversation validation is in flight', async () => {+ const api = require('@librechat/api');+ const models = require('~/models');+ models.getConvo.mockResolvedValueOnce({ conversationId: 'resp_abc', user: 'user-123' });+ let resolveAgent;+ models.getAgent.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveAgent = resolve;+ }),+ );+ api.resolveApiConversationProject.mockImplementationOnce(async (...args) => {+ expect(models.getAgent).toHaveBeenCalledWith({ id: 'agent-123' });+ resolveAgent({ id: 'agent-123', name: 'Test Agent' });+ return jest.requireActual('@librechat/api').resolveApiConversationProject(...args);+ });+ api.validateResponseRequest.mockReturnValueOnce({+ request: {+ model: 'agent-123',+ input: 'Hello',+ stream: false,+ previous_response_id: 'resp_abc',+ },+ });++ await createResponse(req, res);++ expect(models.getAgent.mock.invocationCallOrder[0]).toBeLessThan(+ models.getConvo.mock.invocationCallOrder[0],+ );+ expect(api.initializeAgent).toHaveBeenCalled();+ });++ it('keeps Project-unavailable errors as Responses not-found responses', async () => {+ const api = require('@librechat/api');+ const models = require('~/models');+ api.validateResponseRequest.mockReturnValueOnce({+ request: {+ model: 'agent-123',+ input: 'Hello',+ stream: false,+ previous_response_id: 'resp_abc',+ },+ });+ models.getAgent.mockRejectedValueOnce(new Error('speculative agent lookup failed'));+ api.resolveApiConversationProject.mockResolvedValueOnce({+ ok: false,+ status: 404,+ reason: 'unavailable',+ message: 'Conversation context unavailable',+ });++ await createResponse(req, res);++ const errorCall = api.sendResponsesErrorResponse.mock.calls.at(-1);+ expect(errorCall[1]).toBe(404);+ expect(errorCall[3]).toBe('not_found');+ expect(api.initializeAgent).not.toHaveBeenCalled();+ });++ it('rechecks conversation existence after enrollment before provider or persistence work', async () => {+ const api = require('@librechat/api');+ const models = require('~/models');+ api.validateResponseRequest.mockReturnValueOnce({+ request: {+ model: 'agent-123',+ input: 'Hello',+ stream: false,+ store: true,+ previous_response_id: 'resp_abc',+ },+ });+ let deleted = false;+ models.getConvo.mockImplementation(async () =>+ deleted ? null : { conversationId: 'resp_abc', user: 'user-123' },+ );+ mockEnrollAgentExecution.mockImplementationOnce(async () => {+ deleted = true;+ return mockExecution;+ });++ await createResponse(req, res);++ expect(mockEnrollAgentExecution).toHaveBeenCalledTimes(1);+ expect(api.initializeAgent).not.toHaveBeenCalled();+ expect(api.createRun).not.toHaveBeenCalled();+ expect(models.saveConvo).not.toHaveBeenCalled();+ expect(models.saveMessage).not.toHaveBeenCalled();+ });it('should proceed when conversation is owned by user', async () => {const { validateResponseRequest, sendResponsesErrorResponse } = require('@librechat/api');@@ -2168,6 +2262,7 @@ describe('createResponse controller', () => {expect.any(String),expect.any(String),);+ expect(sendResponsesErrorResponse.mock.calls.at(-1)[3]).toBe('server_error');});});diff --git a/api/server/controllers/agents/__tests__/resume.spec.js b/api/server/controllers/agents/__tests__/resume.spec.jsindex a01d9802eb..cf0ebef3f1 100644--- a/api/server/controllers/agents/__tests__/resume.spec.js+++ b/api/server/controllers/agents/__tests__/resume.spec.js@@ -84,8 +84,10 @@ const mockCheckpointGetTuple = jest.fn();const mockSaveMessage = jest.fn();const mockGetConvo = jest.fn();+const mockGetChatProject = jest.fn();const mockGetMessages = jest.fn();const mockGetFiles = jest.fn();+const mockGetProjectFiles = jest.fn();const mockGetAgent = jest.fn();const mockGetActions = jest.fn();const mockGetUserMemories = jest.fn();@@ -151,8 +153,10 @@ jest.mock('@librechat/api', () => ({jest.mock('~/models', () => ({saveMessage: (...args) => mockSaveMessage(...args),getConvo: (...args) => mockGetConvo(...args),+ getChatProject: (...args) => mockGetChatProject(...args),getMessages: (...args) => mockGetMessages(...args),getFiles: (...args) => mockGetFiles(...args),+ getProjectFiles: (...args) => mockGetProjectFiles(...args),getAgent: (...args) => mockGetAgent(...args),getActions: (...args) => mockGetActions(...args),getUserMemories: (...args) => mockGetUserMemories(...args),@@ -329,8 +333,10 @@ describe('ResumeAgentController (POST /agents/chat/resume)', () => {mockCleanupMCPRequestContextForReq.mockResolvedValue(undefined);mockSaveMessage.mockResolvedValue({});mockGetConvo.mockResolvedValue(null);+ mockGetChatProject.mockResolvedValue(null);mockGetMessages.mockResolvedValue([]);mockGetFiles.mockResolvedValue([]);+ mockGetProjectFiles.mockResolvedValue([]);mockGetAgent.mockResolvedValue(null);mockGetActions.mockResolvedValue([]);mockGetUserMemories.mockResolvedValue([]);@@ -2232,6 +2238,200 @@ describe('ResumeAgentController (POST /agents/chat/resume)', () => {});});+ describe('project context resume fencing', () => {+ const projectConversation = {+ conversationId: CONVO_ID,+ chatProjectId: 'project-1',+ user: USER_ID,+ tenantId: TENANT_ID,+ };+ const projectResource = {+ _id: '507f1f77bcf86cd799439012',+ file_id: 'file-1',+ filename: 'reference.txt',+ filepath: '/uploads/reference.txt',+ object: 'file',+ type: 'text/plain',+ bytes: 10,+ usage: 0,+ embedded: true,+ context: 'message_attachment',+ user: USER_ID,+ tenantId: TENANT_ID,+ updatedAt: new Date('2020-01-01'),+ };++ const projectRecord = (contextRevision, instructions = 'Use the project context.') => ({+ _id: 'project-1',+ tenantId: TENANT_ID,+ contextRevision,+ instructions,+ file_ids: ['file-1'],+ });++ const withProject = (contextRevision, pendingRevision) => {+ const { getChatProjectContextKey, toCanonicalProjectResource } =+ jest.requireActual('@librechat/api');+ const pendingKey =+ pendingRevision === undefined+ ? undefined+ : getChatProjectContextKey({+ ...projectRecord(pendingRevision),+ projectId: 'project-1',+ resources: [toCanonicalProjectResource(projectResource)],+ });+ mockGetConvo.mockResolvedValue(projectConversation);+ mockGetChatProject.mockResolvedValue(projectRecord(contextRevision));+ mockGetProjectFiles.mockResolvedValue([projectResource]);+ mockGenerationJobManager.getJob.mockResolvedValue(+ makeToolApprovalJob({+ metadata: { pendingAction: { projectContextKey: pendingKey } },+ }),+ );+ };++ it('resumes when the authoritative project context key is unchanged', async () => {+ withProject(3, 3);+ const res = await post(approveBody());+ await settled;+ expect(res.status).toBe(200);+ expect(mockGenerationJobManager.approvals.resolve).toHaveBeenCalled();+ expect(mockInitializeClient).toHaveBeenCalled();+ });++ it.each([+ ['deleted', []],+ ['expired', [{ ...projectResource, expiredAt: new Date(0) }]],+ ['ineligible', [{ ...projectResource, embedded: false }]],+ ['replaced', [{ ...projectResource, _id: '507f1f77bcf86cd799439013' }]],+ ['changed content', [{ ...projectResource, updatedAt: new Date('2030-01-01') }]],+ ])('rejects a %s canonical file without a Project revision change', async (_change, files) => {+ withProject(3, 3);+ mockGetProjectFiles.mockResolvedValue(files);+ const res = await post(approveBody());+ expect(res.status).toBe(409);+ expect(res.body).toMatchObject({ code: 'PROJECT_CONTEXT_CHANGED' });+ expect(mockInitializeClient).not.toHaveBeenCalled();+ expect(mockDeleteAgentCheckpoint).toHaveBeenCalledWith(+ CONVO_ID,+ { type: 'mongo' },+ { threadId: CONVO_ID, checkpointIds: ['checkpoint-old'] },+ );+ });++ it('ignores usage and temporary-hold bookkeeping when resuming the same content', async () => {+ withProject(3, 3);+ mockGetProjectFiles.mockResolvedValue([+ {+ ...projectResource,+ usage: 9,+ temp_file_id: 'temporary-id',+ expiresAt: new Date('2030-01-01'),+ },+ ]);+ const res = await post(approveBody());+ await settled;+ expect(res.status).toBe(200);+ expect(mockInitializeClient).toHaveBeenCalled();+ });++ it('rejects a resume whose Project no longer exists', async () => {+ withProject(3, 3);+ mockGetChatProject.mockResolvedValue(null);+ const res = await post(approveBody());+ expect(res.status).toBe(409);+ expect(res.body).toMatchObject({ code: 'PROJECT_CONTEXT_CHANGED' });+ expect(mockInitializeClient).not.toHaveBeenCalled();+ });++ it('terminalizes and prunes the claimed epoch when project context changes', async () => {+ withProject(4, 3);+ const res = await post(approveBody());+ expect(res.status).toBe(409);+ expect(res.body).toMatchObject({ code: 'PROJECT_CONTEXT_CHANGED' });+ expect(mockGenerationJobManager.approvals.resolve).toHaveBeenCalled();+ expect(mockGenerationJobManager.completeJob).toHaveBeenCalledWith(+ CONVO_ID,+ expect.any(String),+ 1000,+ );+ expect(mockGenerationJobManager.approvals.resolve.mock.invocationCallOrder[0]).toBeLessThan(+ mockGenerationJobManager.completeJob.mock.invocationCallOrder[0],+ );+ expect(mockDeleteAgentCheckpoint).toHaveBeenCalledWith(+ CONVO_ID,+ { type: 'mongo' },+ { threadId: CONVO_ID, checkpointIds: ['checkpoint-old'] },+ );+ expect(mockInitializeClient).not.toHaveBeenCalled();+ });+ it('terminalizes a claimed resume when the fresh project lookup fails', async () => {+ withProject(3, 3);+ mockGetConvo.mockRejectedValueOnce(new Error('fresh project read failed'));++ const res = await post(approveBody());+ await settled;++ expect(res.status).toBe(500);+ expect(mockGenerationJobManager.approvals.resolve).toHaveBeenCalled();+ expect(mockGetConvo.mock.invocationCallOrder[0]).toBeGreaterThan(+ mockGenerationJobManager.approvals.resolve.mock.invocationCallOrder[0],+ );+ expect(mockGenerationJobManager.completeJob).toHaveBeenCalledWith(+ CONVO_ID,+ expect.any(String),+ 1000,+ );+ expect(mockDeleteAgentCheckpoint).toHaveBeenCalledWith(+ CONVO_ID,+ { type: 'mongo' },+ { threadId: CONVO_ID, checkpointIds: ['checkpoint-old'] },+ );+ expect(mockDecrementPendingRequest).toHaveBeenCalledWith(USER_ID);+ expect(mockInitializeClient).not.toHaveBeenCalled();+ expect(mockGenerationJobManager.beginProviderExecution).not.toHaveBeenCalled();+ });++ it('does not answer PROJECT_CONTEXT_CHANGED when terminalization itself fails', async () => {+ withProject(4, 3);+ mockGenerationJobManager.completeJob.mockRejectedValueOnce(new Error('redis unavailable'));++ const res = await post(approveBody());+ await settled;++ /* The approval CAS already moved this generation back to running, so a swallowed+ * storage failure would leave it running with no provider owner behind a+ * non-retryable 409. The failure has to reach the resume failure path instead. */+ expect(res.status).toBe(500);+ expect(res.body).not.toMatchObject({ code: 'PROJECT_CONTEXT_CHANGED' });+ expect(mockGenerationJobManager.completeJob).toHaveBeenCalledTimes(2);+ expect(mockInitializeClient).not.toHaveBeenCalled();+ expect(mockGenerationJobManager.beginProviderExecution).not.toHaveBeenCalled();+ });++ it('resumes a legacy pause without a recorded key under the current project context', async () => {+ withProject(3, undefined);+ const res = await post(approveBody());+ await settled;+ expect(res.status).toBe(200);+ expect(mockGenerationJobManager.completeJob).not.toHaveBeenCalledWith(+ CONVO_ID,+ 'Project context changed before approval could be resumed',+ expect.anything(),+ );+ expect(mockInitializeClient).toHaveBeenCalled();+ });++ it('does not terminalize or prune when the approval claim loses its CAS', async () => {+ withProject(4, 3);+ mockGenerationJobManager.approvals.resolve.mockResolvedValue(false);+ const res = await post(approveBody());+ expect(res.status).toBe(409);+ expect(mockGenerationJobManager.completeJob).not.toHaveBeenCalled();+ expect(mockDeleteAgentCheckpoint).not.toHaveBeenCalled();+ });+ });+describe('request guards (rejected before claiming the action)', () => {it('400 when conversationId is missing', async () => {const res = await post({ actionId: ACTION_ID });diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.jsindex 16fe1ee9b3..960e7269ab 100644--- a/api/server/controllers/agents/client.js+++ b/api/server/controllers/agents/client.js@@ -184,6 +184,7 @@ const {isAgentRunCancellation,markCompactionOutcome,resolvePersistableCodeEnvironmentDecision,+ getChatProjectContextKey,} = require('@librechat/api');const {Run,@@ -1955,7 +1956,7 @@ class AgentClient extends BaseClient {{spec: this.options.spec,iconURL: this.options.iconURL,- chatProjectId: this.options.chatProjectId,+ chatProjectId: this.options.req?.chatProjectContext?.projectId,endpoint: this.options.endpoint,agent_id: this.options.agent.id,modelLabel: this.options.modelLabel,@@ -2208,6 +2209,7 @@ class AgentClient extends BaseClient {memory,discoveredToolNames,checkpointerType: agentsConfig?.checkpointer?.type,+ projectContextKey: getChatProjectContextKey(this.options.req?.chatProjectContext),}),skillManifest,discoveredToolNames,@@ -3322,8 +3324,10 @@ class AgentClient extends BaseClient {},codeEnvAvailable: memoryCodeEnabled && memoryToolGrants?.runCode === true,statefulSessionsAvailable: memoryCapabilities.has(AgentCapabilities.stateful_code_sessions),+ useChatProjectContext: false,},{+ getProjectFiles: db.getProjectFiles,getFiles: db.getFiles,getUserKey: db.getUserKey,getConvoFiles: db.getConvoFiles,@@ -4339,6 +4343,9 @@ class AgentClient extends BaseClient {// fall back to it when the SDK doesn't echo threadId on the interrupt.threadId: interrupt.threadId ?? this.conversationId,ttlMs: getApprovalTtlMs(checkpointerCfg),+ // Bind the pause to the authoritative project identity/revision. The key is+ // server-only and is checked before provider/tool startup on resume.+ projectContextKey: getChatProjectContextKey(this.options.req?.chatProjectContext),expiresAt: this.options.req?._agentEventBindingRetention?.expiredAt,// Pin the graph-determining request fields so resume can't rebuild this paused// run on a different agent/tool set (esp. ephemeral agents, whose agent_id isdiff --git a/api/server/controllers/agents/openai.js b/api/server/controllers/agents/openai.jsindex 6cb1e80053..28f996d0d2 100644--- a/api/server/controllers/agents/openai.js+++ b/api/server/controllers/agents/openai.js@@ -72,6 +72,7 @@ const {executeAgentRun,waitForAgentExecutionWrites,resolveToolRoleGrants,+ resolveApiConversationProject,resolveAdmittedCodeEnvironmentDecision,createTerminalRunErrorObserver,} = require('@librechat/api');@@ -284,16 +285,9 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => {// Request-backed tool adapters still observe the validated envelope payload;// shared initialization receives the transport-free runtime below.req.body = request;- req.turnStartedAt = envelope.receivedAt;- const agentRuntime = createAgentExecutionContext({- user: req.user,- appConfig,- requestBody: request,- turnStartedAt: envelope.receivedAt,- conversationCreatedAt: req.conversationCreatedAt,- resolvedConversation: req.resolvedConversation,- hasResolvedConversation: Object.prototype.hasOwnProperty.call(req, 'resolvedConversation'),- });+ if (request.conversation_id != null && typeof request.conversation_id !== 'string') {+ return sendErrorResponse(res, 400, 'conversation_id must be a string', 'invalid_request_error');+ }const agentId = request.model;const manualSkills = extractManualSkills(req.body);@@ -369,18 +363,6 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => {);}- // Look up the agent- const agent = await db.getAgent({ id: agentId });- if (!agent) {- return sendErrorResponse(- res,- 404,- `Agent not found: ${agentId}`,- 'invalid_request_error',- 'model_not_found',- );- }-const responseId = `chatcmpl-${nanoid()}`;const terminalRunError = createTerminalRunErrorObserver({maxProviderErrorChars: appConfig?.endpoints?.agents?.maxProviderErrorChars,@@ -449,22 +431,49 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => {return handleExecutionError({ error, res, context, appConfig });},execute: async (execution) => {+ const agentPromise = db.getAgent({ id: agentId });+ // Validation may return before this promise is awaited; preserve the original+ // promise for the later await while avoiding an unhandled speculative rejection.+ agentPromise.catch(() => {});if (request.conversation_id != null) {- if (typeof request.conversation_id !== 'string') {+ const project = await resolveApiConversationProject(+ {+ userId: principal.userId,+ tenantId: principal.tenantId,+ conversationId: request.conversation_id,+ },+ {+ getConvo: db.getConvo,+ getChatProject: db.getChatProject,+ getProjectFiles: db.getProjectFiles,+ logger,+ logPrefix: '[OpenAI API]',+ },+ );+ if (!project.ok) {return sendErrorResponse(res,- 400,- 'conversation_id must be a string',- 'invalid_request_error',+ project.status,+ project.message,+ project.reason === 'server_error' ? 'server_error' : 'invalid_request_error',);}- const conversation = await db.getConvo(principal.userId, request.conversation_id);- if (!conversation) {- return sendErrorResponse(res, 404, 'Conversation not found', 'invalid_request_error');- }- req.resolvedConversation = conversation;+ req.resolvedConversation = project.conversation;+ req.chatProjectContext = project.context;+ }++ const agent = await agentPromise;+ if (!agent) {+ return sendErrorResponse(+ res,+ 404,+ `Agent not found: ${agentId}`,+ 'invalid_request_error',+ 'model_not_found',+ );}+ req.turnStartedAt = envelope.receivedAt;const { decision: codeEnvironmentDecision, conversation: admittedConversation } =await resolveAdmittedCodeEnvironmentDecision({appConfig,@@ -475,6 +484,17 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => {readDecision: (id) => db.readAdmittedConvoCodeEnvironmentDecision(principal.userId, id),});req.resolvedConversation = admittedConversation;+ const agentRuntime = createAgentExecutionContext({+ user: req.user,+ appConfig,+ requestBody: request,+ turnStartedAt: envelope.receivedAt,+ conversationCreatedAt: req.conversationCreatedAt,+ resolvedConversation: req.resolvedConversation,+ hasResolvedConversation: Object.prototype.hasOwnProperty.call(req, 'resolvedConversation'),+ chatProjectContext: req.chatProjectContext,+ });+const parentMessageId = request.parent_message_id ?? null;let mcpParentMessageId;if (@@ -511,6 +531,7 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => {const skillDbMethods = getSkillDbMethods();const dbMethods = {+ getProjectFiles: db.getProjectFiles,getConvoFiles: db.getConvoFiles,getFiles: db.getFiles,filterFilesByAgentAccess: filterFilesByRemoteAgentAccess,@@ -620,6 +641,7 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => {endpointOption,allowedProviders,isInitialAgent: true,+ useChatProjectContext: true,accessibleSkillIds: primaryScopedSkillIds,skillAuthoringAvailable: canAuthorSkillFiles({agent,@@ -688,6 +710,7 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => {conversationId,parentMessageId,requestBody: mcpRequestBody,+ useChatProjectContext: true,resourceType: ResourceType.REMOTE_AGENT,computeAccessibleSkillIds: (handoffAgent) =>resolveAgentScopedSkillIds({@@ -1102,11 +1125,11 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => {appConfig,signal: execution.signal,customHandlers: handlers,+ modelCallbacks: [terminalRunError.modelCallback],requestBody: mcpRequestBody,user: { ...createSafeUser(req.user), id: userId },traceContext: { endpoint: EModelEndpoint.agents },tenantId: principal.tenantId,- modelCallbacks: [terminalRunError.modelCallback],/** Bills subagent child-run model calls (reported outside the* streamEvents loop) into the same collectedUsage array. */subagentUsageSink: createSubagentUsageSink(collectedUsage),diff --git a/api/server/controllers/agents/request.js b/api/server/controllers/agents/request.jsindex eca096527c..fa656d53ae 100644--- a/api/server/controllers/agents/request.js+++ b/api/server/controllers/agents/request.js@@ -24,6 +24,9 @@ const {exemptFromConcurrencyLimiter,isScheduleFireRequest,isUnpersistedPreliminaryParent,+ startAgentProjectContextResolution,+ assertChatProjectInstructions,+ getChatProjectTurnFailure,resolveConversationAnchor,getAgentStartupTelemetry,acceptAgentStartupTelemetry,@@ -68,6 +71,8 @@ const {saveConvo,getMessages,getConvo,+ getChatProject,+ getProjectFiles,getAgentEventActorSnapshot,commitAgentEventActorState,storeAgentEventActorSuspension,@@ -119,6 +124,11 @@ function getInitializationFailure(error) {};}+ const projectFailure = getChatProjectTurnFailure(error);+ if (projectFailure) {+ return projectFailure;+ }+const metadata = getAgentErrorMetadata(error);if (!metadata?.status) {return null;@@ -521,7 +531,7 @@ async function saveErrorTurn(}const agentId = endpointOption?.agent_id ?? req.body?.agent_id;- const chatProjectId = endpointOption?.chatProjectId ?? req.body?.chatProjectId;+ const chatProjectId = req.chatProjectContext?.projectId;const seedConvo = isNewConvo || req.resolvedConversation === null;/** A stored turn seals the decision it ran under, on a saved chat as much as on a new one: the* error turn below enters the conversation, so leaving its validated decision out would let a@@ -919,6 +929,19 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit? req.resolvedConversation: undefined,});+ // Resolve the authoritative project context while idempotency and admission+ // gates proceed below. The promise is awaited before createJob, so rejected+ // project policy never receives an HTTP generation ACK.+ const chatProjectContextPromise = startAgentProjectContextResolution({+ req,+ endpointOption,+ conversationId,+ isNewConvo,+ conversationAnchorPromise,+ getConvo,+ getChatProject,+ getProjectFiles,+ });/** A newly bound actor conversation has no child messages yet, so its first* event legitimately uses the root parent id. The authenticated write guard@@ -1539,18 +1562,6 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit) {preallocatedResponseMessageId = crypto.randomUUID();}- const mcpRequestBody = createMCPRuntimeRequestBody({- messageId: preallocatedResponseMessageId,- conversationId: effectiveConversationId,- codeEnvironmentMode: req.body.codeEnvironmentMode,- codeWorkspaces: resolveRunCodeWorkspaces({- conversationId: effectiveConversationId,- requestedSelections: req.body.codeWorkspaces,- conversation: req.resolvedConversation,- }),- parentMessageId:- editedContent != null ? preallocatedResponseMessageId : preallocatedUserMessageId,- });let client = null;let verifiedInitialAgentId = null;@@ -1607,6 +1618,22 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTitreq._agentEventTriggerProjection = getAgentEventTriggerProjection(agentEventDelivery);try {+ assertChatProjectInstructions({+ context: await chatProjectContextPromise,+ filters: req.config?.filters,+ });+ const mcpRequestBody = createMCPRuntimeRequestBody({+ messageId: preallocatedResponseMessageId,+ conversationId: effectiveConversationId,+ codeEnvironmentMode: req.body.codeEnvironmentMode,+ codeWorkspaces: resolveRunCodeWorkspaces({+ conversationId: effectiveConversationId,+ requestedSelections: req.body.codeWorkspaces,+ conversation: req.resolvedConversation,+ }),+ parentMessageId:+ editedContent != null ? preallocatedResponseMessageId : preallocatedUserMessageId,+ });logger.debug(`[ResumableAgentController] Creating job`, {streamId,conversationId,diff --git a/api/server/controllers/agents/responses.js b/api/server/controllers/agents/responses.jsindex 016ee1d10a..13917a58a1 100644--- a/api/server/controllers/agents/responses.js+++ b/api/server/controllers/agents/responses.js@@ -85,6 +85,7 @@ const {executeAgentRun,waitForAgentExecutionWrites,resolveToolRoleGrants,+ resolveApiConversationProject,resolveAdmittedCodeEnvironmentDecision,resolvePersistableCodeEnvironmentDecision,createTerminalRunErrorObserver,@@ -524,16 +525,14 @@ const executeResponse = async (envelope, { req, res }) => {// Request-backed tool adapters still observe the validated envelope payload;// shared initialization receives the transport-free runtime below.req.body = request;- req.turnStartedAt = envelope.receivedAt;- const agentRuntime = createAgentExecutionContext({- user: req.user,- appConfig,- requestBody: request,- turnStartedAt: envelope.receivedAt,- conversationCreatedAt: req.conversationCreatedAt,- resolvedConversation: req.resolvedConversation,- hasResolvedConversation: Object.prototype.hasOwnProperty.call(req, 'resolvedConversation'),- });+ if (request.previous_response_id != null && typeof request.previous_response_id !== 'string') {+ return sendResponsesErrorResponse(+ res,+ 400,+ 'previous_response_id must be a string',+ 'invalid_request',+ );+ }const agentId = request.model;const manualSkills = extractManualSkills(req.body);const isStreaming = request.stream === true;@@ -615,18 +614,6 @@ const executeResponse = async (envelope, { req, res }) => {);}- // Look up the agent- const agent = await db.getAgent({ id: agentId });- if (!agent) {- return sendResponsesErrorResponse(- res,- 404,- `Agent not found: ${agentId}`,- 'not_found',- 'model_not_found',- );- }-// Generate IDsconst responseId = generateResponseId();const terminalRunError = createTerminalRunErrorObserver({@@ -689,24 +676,27 @@ const executeResponse = async (envelope, { req, res }) => {return handleExecutionError({ error, res, appConfig });},execute: async (execution) => {+ const agentPromise = db.getAgent({ id: agentId });+ // Validation may return before this promise is awaited; preserve the original+ // promise for the later await while avoiding an unhandled speculative rejection.+ agentPromise.catch(() => {});if (request.previous_response_id != null) {- if (typeof request.previous_response_id !== 'string') {- return sendResponsesErrorResponse(- res,- 400,- 'previous_response_id must be a string',- 'invalid_request',- );- }- const previousConversation = await db.getConvo(- principal.userId,- request.previous_response_id,+ const project = await resolveApiConversationProject(+ {+ userId: principal.userId,+ tenantId: principal.tenantId,+ conversationId: request.previous_response_id,+ rejectSubagentThread: true,+ },+ {+ getConvo: db.getConvo,+ getChatProject: db.getChatProject,+ getProjectFiles: db.getProjectFiles,+ logger,+ logPrefix: '[Responses API]',+ },);- if (!previousConversation) {- return sendResponsesErrorResponse(res, 404, 'Conversation not found', 'not_found');- }- req.resolvedConversation = previousConversation;- if (previousConversation.subagentThread != null) {+ if (!project.ok && project.reason === 'read_only') {return sendResponsesErrorResponse(res,409,@@ -715,8 +705,30 @@ const executeResponse = async (envelope, { req, res }) => {'conversation_read_only',);}+ if (!project.ok) {+ return sendResponsesErrorResponse(+ res,+ project.status,+ project.message,+ project.reason === 'server_error' ? 'server_error' : 'not_found',+ );+ }+ req.resolvedConversation = project.conversation;+ req.chatProjectContext = project.context;+ }++ const agent = await agentPromise;+ if (!agent) {+ return sendResponsesErrorResponse(+ res,+ 404,+ `Agent not found: ${agentId}`,+ 'not_found',+ 'model_not_found',+ );}+ req.turnStartedAt = envelope.receivedAt;const { decision: codeEnvironmentDecision, conversation: admittedConversation } =await resolveAdmittedCodeEnvironmentDecision({appConfig,@@ -727,6 +739,17 @@ const executeResponse = async (envelope, { req, res }) => {readDecision: (id) => db.readAdmittedConvoCodeEnvironmentDecision(principal.userId, id),});req.resolvedConversation = admittedConversation;+ const agentRuntime = createAgentExecutionContext({+ user: req.user,+ appConfig,+ requestBody: request,+ turnStartedAt: envelope.receivedAt,+ conversationCreatedAt: req.conversationCreatedAt,+ resolvedConversation: req.resolvedConversation,+ hasResolvedConversation: Object.prototype.hasOwnProperty.call(req, 'resolvedConversation'),+ chatProjectContext: req.chatProjectContext,+ });+const parentMessageId = null;const mcpRequestBody = createMCPRuntimeRequestBody({messageId: responseId,@@ -765,6 +788,7 @@ const executeResponse = async (envelope, { req, res }) => {};const dbMethods = {+ getProjectFiles: db.getProjectFiles,getConvoFiles: db.getConvoFiles,getFiles: db.getFiles,filterFilesByAgentAccess: filterFilesByRemoteAgentAccess,@@ -874,6 +898,7 @@ const executeResponse = async (envelope, { req, res }) => {endpointOption,allowedProviders,isInitialAgent: true,+ useChatProjectContext: true,accessibleSkillIds: primaryScopedSkillIds,skillAuthoringAvailable: canAuthorSkillFiles({agent,@@ -941,6 +966,7 @@ const executeResponse = async (envelope, { req, res }) => {requestFiles: [],conversationId,parentMessageId,+ useChatProjectContext: true,requestBody: mcpRequestBody,resourceType: ResourceType.REMOTE_AGENT,computeAccessibleSkillIds: (handoffAgent) =>diff --git a/api/server/controllers/agents/resume.js b/api/server/controllers/agents/resume.jsindex 3fe3d6f372..3cffe9b151 100644--- a/api/server/controllers/agents/resume.js+++ b/api/server/controllers/agents/resume.js@@ -47,6 +47,9 @@ const {findAgentEventAppliedAction,assertCodeExecutionApprovalBinding,collectReachableAgents,+ rejectChangedResumeProjectContext,+ PROJECT_CONTEXT_CHANGED_REASON,+ PROJECT_CONTEXT_CHANGED_RESPONSE,restoreScheduledTokenContext,recoverTurnMessageReference,announceReply,@@ -61,7 +64,9 @@ const {const {saveMessage,getConvo,+ getChatProject,getMessages,+ getProjectFiles,getFiles,getAgent,getActions,@@ -199,7 +204,6 @@ async function deleteFailedResumeCheckpoint(args, context) {}const GENERIC_RESUME_ERROR = 'Resume failed';-const resumeContentProtectionDependencies = {onTraversalFailure: reportLocatorTraversalFailure,getAgentCheckpointer,@@ -1303,6 +1307,18 @@ const ResumeAgentController = async (req, res, next, initializeClient, addTitle)let eventActorActionRecorder;let appliedEventActor;const providerExecutionId = randomUUID();+ let resumeAcknowledged = false;+ let resumeSlotReleased = false;+ const rejectPendingEventActorResume = async (error) => {+ if (+ eventActorResumePromise != null &&+ eventActorStartGate != null &&+ !eventActorContinuationStarted+ ) {+ eventActorStartGate.reject(error);+ await eventActorResumePromise.catch(() => {});+ }+ };try {if (req._agentEventBindingParentConversationId != null) {req._agentEventTaskId = job.metadata.idempotencyClientRequestId;@@ -1686,509 +1702,549 @@ const ResumeAgentController = async (req, res, next, initializeClient, addTitle)generationProtocolVersion,);}-- // Linearize the consumed approval against the schedule's live config. The schedule- // document fence was acquired only after all async policy reads, and this atomic- // consume checks its token/revision/enabled state immediately after the approval CAS.- // An edit/disable that won first makes this fail; one that lands afterward is ordered- // after the continuation has started. Never begin provider execution on a stale claim.- if (scheduleId) {- let scheduleClaimCurrent = false;- try {- scheduleClaimCurrent = await finalizeScheduleResumeClaim(- scheduleId,- scheduleResumeClaimToken,- scheduleResumeLeaseBy,- scheduleResumeOptions,- );- } catch (error) {- logger.error('[ResumeAgentController] Failed to finalize scheduled resume fence', error);- await releaseScheduleFence();- }- if (!scheduleClaimCurrent) {- await decrementPendingRequest(userId);- let stopped = false;+ let client = null;+ /** Re-pause progress failures use the action/epoch-scoped terminal CAS. The+ * generic resume catch must not subsequently call completeJob, because the+ * failed pause may have lost ownership to a newer action or generation. */+ let pausePersistenceFailed = false;+ let pausePersistenceFailureFinalized = false;+ try {+ // Linearize the consumed approval against the schedule's live config. The schedule+ // document fence was acquired only after all async policy reads, and this atomic+ // consume checks its token/revision/enabled state immediately after the approval CAS.+ // An edit/disable that won first makes this fail; one that lands afterward is ordered+ // after the continuation has started. Never begin provider execution on a stale claim.+ if (scheduleId) {+ let scheduleClaimCurrent = false;try {- const abortResult = await GenerationJobManager.abortJob(streamId, {- expectedCreatedAt: job.createdAt,- awaitProviderDrain: true,- });- // Same authoritative gate as the inactive-schedule path above: only a landed- // abort (or an already-terminal, drained generation) may settle this occurrence.- stopped = isStopConfirmed(abortResult);+ scheduleClaimCurrent = await finalizeScheduleResumeClaim(+ scheduleId,+ scheduleResumeClaimToken,+ scheduleResumeLeaseBy,+ scheduleResumeOptions,+ );} catch (error) {- logger.warn('[ResumeAgentController] Failed to stop stale scheduled resume', error);+ logger.error('[ResumeAgentController] Failed to finalize scheduled resume fence', error);+ await releaseScheduleFence();}- if (!stopped) {- res.set('Retry-After', '1');+ if (!scheduleClaimCurrent) {+ resumeSlotReleased = true;+ await decrementPendingRequest(userId);+ let stopped = false;+ try {+ const abortResult = await GenerationJobManager.abortJob(streamId, {+ expectedCreatedAt: job.createdAt,+ awaitProviderDrain: true,+ });+ // Same authoritative gate as the inactive-schedule path above: only a landed+ // abort (or an already-terminal, drained generation) may settle this occurrence.+ stopped = isStopConfirmed(abortResult);+ } catch (error) {+ logger.warn('[ResumeAgentController] Failed to stop stale scheduled resume', error);+ }+ if (!stopped) {+ res.set('Retry-After', '1');+ return sendGenerationJson(+ res,+ 503,+ {+ code: 'SCHEDULE_STOP_UNCONFIRMED',+ error: 'The stale scheduled resume could not be confirmed stopped.',+ },+ generationProtocolVersion,+ );+ }+ await recordScheduleOutcome({+ scheduleId,+ scheduledFor,+ streamId,+ jobCreatedAt: job.createdAt,+ status: 'interrupted',+ conversationId,+ error: 'Schedule was disabled, changed, or deleted before approval',+ });+ if (checkpointNamespace !== '') {+ await deleteAgentCheckpoint(conversationId, checkpointerCfg, undefined, {+ checkpointNamespace,+ }).catch((error) => {+ logger.warn(+ '[ResumeAgentController] Failed to prune stale schedule checkpoint',+ error,+ );+ });+ }return sendGenerationJson(res,- 503,- {- code: 'SCHEDULE_STOP_UNCONFIRMED',- error: 'The stale scheduled resume could not be confirmed stopped.',- },+ 409,+ { code: 'SCHEDULE_NO_LONGER_ACTIVE', error: 'This schedule can no longer be resumed' },generationProtocolVersion,);}- await recordScheduleOutcome({- scheduleId,- scheduledFor,- streamId,- jobCreatedAt: job.createdAt,- status: 'interrupted',- conversationId,- error: 'Schedule was disabled, changed, or deleted before approval',- });- if (checkpointNamespace !== '') {- await deleteAgentCheckpoint(conversationId, checkpointerCfg, undefined, {- checkpointNamespace,+ }+ // Re-read the authoritative conversation/project only after approvals.resolve+ // wins its CAS. The approval CAS/epoch is the owner fence: a mismatch+ // terminalizes only this claimed job before initializeClient can start provider+ // or tool work.+ const claimedProjectContextConflict = await rejectChangedResumeProjectContext(+ { req, conversationId, expectedKey: pendingAction?.projectContextKey },+ {+ getConvo,+ getChatProject,+ getProjectFiles,+ logger,+ finalizeJob: async (reason) =>+ (await GenerationJobManager.completeJob(streamId, reason, job.createdAt)) === true,+ deleteCheckpoint: () =>+ deleteResumedGenerationCheckpoint({+ conversationId,+ checkpointerCfg,+ job,+ checkpointGeneration,+ }),+ },+ );+ if (claimedProjectContextConflict) {+ sendGenerationJson(res, 409, PROJECT_CONTEXT_CHANGED_RESPONSE, generationProtocolVersion);+ await rejectPendingEventActorResume(new Error(PROJECT_CONTEXT_CHANGED_REASON));+ resumeSlotReleased = true;+ await decrementPendingRequest(userId);+ await releaseScheduleFence();+ if (scheduleId) {+ await recordScheduleOutcome({+ scheduleId,+ scheduledFor,+ streamId,+ jobCreatedAt: job.createdAt,+ status: 'interrupted',+ conversationId,+ error: PROJECT_CONTEXT_CHANGED_REASON,}).catch((error) => {- logger.warn('[ResumeAgentController] Failed to prune stale schedule checkpoint', error);+ logger.warn(+ '[ResumeAgentController] Failed to record stale project-context schedule outcome',+ getSafeErrorMetadata(error),+ );});}- return sendGenerationJson(- res,- 409,- { code: 'SCHEDULE_NO_LONGER_ACTIVE', error: 'This schedule can no longer be resumed' },- generationProtocolVersion,- );+ return;}- }-- eventLeaseTransferredToRun = true;- } finally {- if (!eventLeaseTransferredToRun) {- await releaseEventChildLease?.();- releaseEventChildLease = undefined;- }- }-- /**- * An interrupt steer enqueued just before the pause survives durably with- * its `preempt` flag, but the ARM lived only in the previous owner's- * runtime. Rebuild it from the queue so the resumed segment honours an- * interrupt the user already had acknowledged.- */- const preemptRearm = GenerationJobManager.rearmQueuedPreempts(streamId, job.createdAt).catch(- (error) => {- logger.error(- '[ResumeAgentController] Failed to re-arm queued preempts',- getSafeErrorMetadata(error),+ eventLeaseTransferredToRun = true;++ /**+ * An interrupt steer enqueued just before the pause survives durably with+ * its `preempt` flag, but the ARM lived only in the previous owner's+ * runtime. Rebuild it from the queue so the resumed segment honours an+ * interrupt the user already had acknowledged.+ */+ const preemptRearm = GenerationJobManager.rearmQueuedPreempts(streamId, job.createdAt).catch(+ (error) => {+ logger.error(+ '[ResumeAgentController] Failed to re-arm queued preempts',+ getSafeErrorMetadata(error),+ );+ },);- },- );-- /**- * BOUNDED, and the bound is the point. `.catch` only fires on rejection,- * but ioredis queues commands while a connection is down instead of- * rejecting, so either of these can simply never settle. That would block- * here — after `approvals.resolve` has already consumed the action and- * flipped the job to `running`, and before both `res.json` and the resume- * lifecycle's own try/finally. The client times out, its retry gets a 409- * because the action is spent, and neither the continuation nor the- * failed-resume cleanup ever runs.- *- * Re-arming is steering bookkeeping that the next tool boundary would- * honour anyway, so it finishes in the background rather than holding a- * resume the user is waiting on. Capability is not in this best-effort path:- * it was committed atomically by the resume claim above.- */- let steeringSetupTimer;- await Promise.race([- preemptRearm,- new Promise((resolve) => {- steeringSetupTimer = setTimeout(() => {- logger.warn(- `[ResumeAgentController] Steering setup for ${streamId} still pending after ` +- `${STEER_RESUME_SETUP_TIMEOUT_MS}ms; continuing the resume without it`,- );- resolve();- }, STEER_RESUME_SETUP_TIMEOUT_MS);- }),- ]);- clearTimeout(steeringSetupTimer);- // Seed the run-scoped MCP request-context store BEFORE the ACK: once `res.json`- // finishes the response, a later `getMCPRequestContext(req, res)` (from tool loading)- // sees `res` as ended and returns undefined, leaving the resumed run without its MCP- // connection store — approved MCP / OAuth-overlay tools would then run without their- // request-scoped connections. Pre-seeding with a null `res` + `cleanupOnResponse:false`- // mirrors the normal stream path (request.js); torn down in the `finally` below.- req._resumableStreamId = streamId;- getMCPRequestContext(req, undefined, { cleanupOnResponse: false });-- // ACK immediately; the continuation streams over the client's existing SSE.- sendGenerationJson(- res,- 200,- { streamId, conversationId, status: 'resuming' },- generationProtocolVersion,- );+ /**+ * BOUNDED, and the bound is the point. `.catch` only fires on rejection,+ * but ioredis queues commands while a connection is down instead of+ * rejecting, so either of these can simply never settle. Keep steering setup+ * bounded so it cannot hold the resume before the ACK or its lifecycle cleanup.+ *+ * Re-arming is steering bookkeeping that the next tool boundary would+ * honour anyway, so it finishes in the background rather than holding the+ * resume the user is waiting on. Capability is not in this best-effort path:+ * it was committed atomically by the resume claim above.+ */+ let steeringSetupTimer;+ await Promise.race([+ preemptRearm,+ new Promise((resolve) => {+ steeringSetupTimer = setTimeout(() => {+ logger.warn(+ `[ResumeAgentController] Steering setup for ${streamId} still pending after ` ++ `${STEER_RESUME_SETUP_TIMEOUT_MS}ms; continuing the resume without it`,+ );+ resolve();+ }, STEER_RESUME_SETUP_TIMEOUT_MS);+ }),+ ]);+ clearTimeout(steeringSetupTimer);++ // Seed the run-scoped MCP request-context store BEFORE the ACK: once `res.json`+ // finishes the response, a later `getMCPRequestContext(req, res)` (from tool loading)+ // sees `res` as ended and returns undefined, leaving the resumed run without its MCP+ // connection store; approved MCP / OAuth-overlay tools would then run without their+ // request-scoped connections. Pre-seeding with a null `res` + `cleanupOnResponse:false`+ // mirrors the normal stream path (request.js); torn down in the `finally` below.+ req._resumableStreamId = streamId;+ getMCPRequestContext(req, undefined, { cleanupOnResponse: false });++ sendGenerationJson(+ res,+ 200,+ { streamId, conversationId, status: 'resuming' },+ generationProtocolVersion,+ );+ resumeAcknowledged = true;- req.turnStartedAt = job.createdAt;+ req.turnStartedAt = job.createdAt;- let client = null;- /** Re-pause progress failures use the action/epoch-scoped terminal CAS. The- * generic resume catch must not subsequently call completeJob, because the- * failed pause may have lost ownership to a newer action or generation. */- let pausePersistenceFailed = false;- let pausePersistenceFailureFinalized = false;- try {- if (userSubmittedPaths.length > 0) {- job.metadata.userSubmittedPaths = userSubmittedPaths;- }- if (userSubmittedMessageFieldPaths.length > 0) {- job.metadata.userSubmittedMessageFieldPaths = userSubmittedMessageFieldPaths;- }- if (userSubmittedPaths.length > 0 || userSubmittedMessageFieldPaths.length > 0) {- await GenerationJobManager.getJobStore().updateJob(- streamId,- {- ...(userSubmittedPaths.length > 0 && { userSubmittedPaths }),- ...(userSubmittedMessageFieldPaths.length > 0 && {- userSubmittedMessageFieldPaths,- }),- },- job.createdAt,- );- }+ if (userSubmittedPaths.length > 0) {+ job.metadata.userSubmittedPaths = userSubmittedPaths;+ }+ if (userSubmittedMessageFieldPaths.length > 0) {+ job.metadata.userSubmittedMessageFieldPaths = userSubmittedMessageFieldPaths;+ }+ if (userSubmittedPaths.length > 0 || userSubmittedMessageFieldPaths.length > 0) {+ await GenerationJobManager.getJobStore().updateJob(+ streamId,+ {+ ...(userSubmittedPaths.length > 0 && { userSubmittedPaths }),+ ...(userSubmittedMessageFieldPaths.length > 0 && {+ userSubmittedMessageFieldPaths,+ }),+ },+ job.createdAt,+ );+ }- const mcpRequestBody =- job.metadata.mcpRequestBody ??- createMCPRuntimeRequestBody({- messageId: job.metadata.responseMessageId,- conversationId: streamId,- codeEnvironmentMode:- req.body.codeEnvironmentMode ?? req.resolvedConversation?.codeEnvironmentMode,- codeWorkspaces: req.body.codeWorkspaces ?? req.resolvedConversation?.codeWorkspaces,- parentMessageId: job.metadata.userMessage?.messageId ?? Constants.NO_PARENT,+ const mcpRequestBody =+ job.metadata.mcpRequestBody ??+ createMCPRuntimeRequestBody({+ messageId: job.metadata.responseMessageId,+ conversationId: streamId,+ codeEnvironmentMode:+ req.body.codeEnvironmentMode ?? req.resolvedConversation?.codeEnvironmentMode,+ codeWorkspaces: req.body.codeWorkspaces ?? req.resolvedConversation?.codeWorkspaces,+ parentMessageId: job.metadata.userMessage?.messageId ?? Constants.NO_PARENT,+ });+ const result = await initializeClient({+ scheduledTokenContext: restoreScheduledTokenContext(req, job.metadata),+ req,+ res,+ endpointOption: req.body.endpointOption,+ signal: job.abortController.signal,+ jobCreatedAt: job.createdAt,+ checkpointNamespace,+ foregroundRunId: mcpRequestBody.messageId,+ requestBody: mcpRequestBody,});- const result = await initializeClient({- scheduledTokenContext: restoreScheduledTokenContext(req, job.metadata),- req,- res,- endpointOption: req.body.endpointOption,- signal: job.abortController.signal,- jobCreatedAt: job.createdAt,- checkpointNamespace,- foregroundRunId: mcpRequestBody.messageId,- requestBody: mcpRequestBody,- toolTimingReplayEvents: resumeState?.replayEvents,- });- client = result.client;+ client = result.client;- // The user approved the code action against the route/session selected at- // pause time. Re-resolve it on this replica and fail before provider/tool- // execution if the environment, worker, or workspace scope moved.- assertCodeExecutionApprovalBinding(- pendingAction.codeExecutionBinding,- collectReachableAgents([client.options?.agent, ...(client.agentConfigs?.values() ?? [])]),- );+ // Re-resolve the approved code target before provider/tool execution on this replica.+ assertCodeExecutionApprovalBinding(+ pendingAction.codeExecutionBinding,+ collectReachableAgents([client.options?.agent, ...(client.agentConfigs?.values() ?? [])]),+ );- // Bind the rebuilt client to the in-flight turn's identity (no new user message).- client.conversationId = streamId;- // The resume operates on the SAME job (it moved it running again), so its identity is- // the paused job's createdAt — used by the re-pause CAS pre-check + checkpoint prune to- // avoid acting on a job a newer request has since replaced.- client.jobCreatedAt = job.createdAt;- client.checkpointNamespace = checkpointNamespace;- client.responseMessageId = job.metadata.responseMessageId;- client.parentMessageId = job.metadata.userMessage?.messageId ?? Constants.NO_PARENT;- // Seed the rebuilt pruner from the tier and calibration captured at the pause, so the- // resumed segment keeps historical tool results byte-identical to the paused one.- client.seedContextMeta?.(job.metadata?.contextMeta);- if (client.contentParts) {- GenerationJobManager.setContentParts(streamId, client.contentParts, job.createdAt);- }+ // Bind the rebuilt client to the in-flight turn's identity (no new user message).+ client.conversationId = streamId;+ // The resume operates on the SAME job (it moved it running again), so its identity is+ // the paused job's createdAt, used by the re-pause CAS pre-check + checkpoint prune to+ // avoid acting on a job a newer request has since replaced.+ client.jobCreatedAt = job.createdAt;+ client.checkpointNamespace = checkpointNamespace;+ client.responseMessageId = job.metadata.responseMessageId;+ client.parentMessageId = job.metadata.userMessage?.messageId ?? Constants.NO_PARENT;+ // Seed the rebuilt pruner from the tier and calibration captured at the pause, so the+ // resumed segment keeps historical tool results byte-identical to the paused one.+ client.seedContextMeta?.(job.metadata?.contextMeta);+ if (client.contentParts) {+ GenerationJobManager.setContentParts(streamId, client.contentParts, job.createdAt);+ }- const resumeClient = () =>- client.resumeCompletion({- resumeValue: mapped.resumeValue,- seedContent,- runSteps: resumeState?.runSteps ?? [],- storedMessages,- abortController: job.abortController,- // Carry the user's MCP auth so approved MCP tools run with their credentials.- userMCPAuthMap: result.userMCPAuthMap,- // Replay deferred tools discovered before the pause (captured at pause). The rebuilt- // graph passes `messages: []`, so without these the model would lose their schemas.- discoveredToolNames: job.metadata?.discoveredTools,- activityPhaseSnapshot: job.metadata?.activityPhaseSnapshot,- compactionSemanticIndex: job.metadata?.compactionSemanticIndex,- });- if (- !(await GenerationJobManager.beginProviderExecution(- streamId,- job.createdAt,- providerExecutionId,- ))- ) {- throw Object.assign(new Error('Generation stopped before provider resume'), {- code: 'RUN_REPLACED',- });- }- if (eventActorResumePromise == null) {- await resumeClient();- } else {- eventActorContinuationStarted = true;- eventActorStartGate.resolve(async (actorContext) => {- client.checkpointNamespace = actorContext.checkpointNamespace;- client.eventActorCheckpointId = actorContext.checkpointId;- client.eventActorInvocationId = actorContext.invocationId;- client.eventActorContinuation = actorContext.continuation;- return resumeClient();- });- const actorResult = await eventActorResumePromise;- if (actorResult.execution.status === 'suspended') {- const suspensionKind = req._agentEventDetachedActionLifecycle?.readSuspension()?.kind;- if (suspensionKind === 'internal_completion') {- await GenerationJobManager.updateMetadata(- streamId,- {- agentEventSuspension: {- version: actorResult.execution.suspension.version,- suspensionId: actorResult.execution.suspension.suspensionId,- attempt: actorResult.execution.suspension.attempt,+ const resumeClient = () =>+ client.resumeCompletion({+ resumeValue: mapped.resumeValue,+ seedContent,+ runSteps: resumeState?.runSteps ?? [],+ storedMessages,+ abortController: job.abortController,+ // Carry the user's MCP auth so approved MCP tools run with their credentials.+ userMCPAuthMap: result.userMCPAuthMap,+ // Replay deferred tools discovered before the pause (captured at pause). The rebuilt+ // graph passes `messages: []`, so without these the model would lose their schemas.+ discoveredToolNames: job.metadata?.discoveredTools,+ activityPhaseSnapshot: job.metadata?.activityPhaseSnapshot,+ compactionSemanticIndex: job.metadata?.compactionSemanticIndex,+ });+ if (+ !(await GenerationJobManager.beginProviderExecution(+ streamId,+ job.createdAt,+ providerExecutionId,+ ))+ ) {+ throw Object.assign(new Error('Generation stopped before provider resume'), {+ code: 'RUN_REPLACED',+ });+ }+ if (eventActorResumePromise == null) {+ await resumeClient();+ } else {+ eventActorContinuationStarted = true;+ eventActorStartGate.resolve(async (actorContext) => {+ client.checkpointNamespace = actorContext.checkpointNamespace;+ client.eventActorCheckpointId = actorContext.checkpointId;+ client.eventActorInvocationId = actorContext.invocationId;+ client.eventActorContinuation = actorContext.continuation;+ return resumeClient();+ });+ const actorResult = await eventActorResumePromise;+ if (actorResult.execution.status === 'suspended') {+ const suspensionKind = req._agentEventDetachedActionLifecycle?.readSuspension()?.kind;+ if (suspensionKind === 'internal_completion') {+ await GenerationJobManager.updateMetadata(+ streamId,+ {+ agentEventSuspension: {+ version: actorResult.execution.suspension.version,+ suspensionId: actorResult.execution.suspension.suspensionId,+ attempt: actorResult.execution.suspension.attempt,+ },},- },- job.createdAt,- );- } else if (!(await client.publishStagedApproval(actorResult.execution.suspension))) {- throw new Error('Re-paused event actor suspension could not be projected to its job');+ job.createdAt,+ );+ } else if (!(await client.publishStagedApproval(actorResult.execution.suspension))) {+ throw new Error('Re-paused event actor suspension could not be projected to its job');+ }+ } else if (actorResult.execution.status === 'applied') {+ appliedEventActor = {+ invocationId: durableEventActorSuspension.invocation.invocationId,+ checkpoint: actorResult.execution.head.checkpoint,+ action: actorResult.execution.result.action,+ };}- } else if (actorResult.execution.status === 'applied') {- appliedEventActor = {- invocationId: durableEventActorSuspension.invocation.invocationId,- checkpoint: actorResult.execution.head.checkpoint,- action: actorResult.execution.result.action,- };}- }- // The model may pause AGAIN (another tool, or a follow-up question). The pending- // action is durably projected; persist progress before exposing it to clients.- if (client.pendingApproval) {- logger.debug(`[ResumeAgentController] Re-paused for approval: ${streamId}`);- const pauseActionId = client.pendingApproval.actionId;- const pauseCreatedAt = client.jobCreatedAt ?? job.createdAt;- const ownsPausePersistence = await GenerationJobManager.approvals.ownsPausePersistence(- streamId,- pauseActionId,- pauseCreatedAt,- );- if (ownsPausePersistence) {- try {- // Persist this segment's content + artifacts before the fresh client (next- // resume) drops them, so an expiring re-pause doesn't lose them; finalize later- // overwrites content and merges attachments onto the saved message. A failed- // required write must reject into the error-finalization path rather than expose- // the next action while its preceding segment is absent from durable history.- await persistRePauseProgress({ req, client, job, streamId, conversationId });- } catch (pausePersistenceError) {- pausePersistenceFailed = true;+ // The model may pause AGAIN (another tool, or a follow-up question). The pending+ // action is durably projected; persist progress before exposing it to clients.+ if (client.pendingApproval) {+ logger.debug(`[ResumeAgentController] Re-paused for approval: ${streamId}`);+ const pauseActionId = client.pendingApproval.actionId;+ const pauseCreatedAt = client.jobCreatedAt ?? job.createdAt;+ const ownsPausePersistence = await GenerationJobManager.approvals.ownsPausePersistence(+ streamId,+ pauseActionId,+ pauseCreatedAt,+ );+ if (ownsPausePersistence) {try {- pausePersistenceFailureFinalized =- (await GenerationJobManager.failPausePersistence(- streamId,- pauseActionId,- getUserFacingResumeError(pausePersistenceError, req.config),- pauseCreatedAt,- )) === true;- if (!pausePersistenceFailureFinalized) {- logger.warn(- `[ResumeAgentController] Skipping stale re-pause persistence failure — ${streamId} no longer owns its barrier`,+ // Persist this segment's content + artifacts before the fresh client (next+ // resume) drops them, so an expiring re-pause doesn't lose them; finalize later+ // overwrites content and merges attachments onto the saved message. A failed+ // required write must reject into the error-finalization path rather than expose+ // the next action while its preceding segment is absent from durable history.+ await persistRePauseProgress({ req, client, job, streamId, conversationId });+ } catch (pausePersistenceError) {+ pausePersistenceFailed = true;+ try {+ pausePersistenceFailureFinalized =+ (await GenerationJobManager.failPausePersistence(+ streamId,+ pauseActionId,+ getUserFacingResumeError(pausePersistenceError, req.config),+ pauseCreatedAt,+ )) === true;+ if (!pausePersistenceFailureFinalized) {+ logger.warn(+ `[ResumeAgentController] Skipping stale re-pause persistence failure: ${streamId} no longer owns its barrier`,+ );+ }+ } catch (failError) {+ logger.error(+ `[ResumeAgentController] Failed to terminalize re-pause persistence error for ${streamId}`,+ getSafeErrorMetadata(failError),);}- } catch (failError) {- logger.error(- `[ResumeAgentController] Failed to terminalize re-pause persistence error for ${streamId}`,- getSafeErrorMetadata(failError),+ throw pausePersistenceError;+ }+ await client.exposePendingApproval?.();+ const released = await GenerationJobManager.approvals.finishPausePersistence(+ streamId,+ pauseActionId,+ pauseCreatedAt,+ );+ if (!released) {+ logger.warn(+ `[ResumeAgentController] Re-pause persistence barrier changed before release: ${streamId}`,);}- throw pausePersistenceError;- }- await client.exposePendingApproval?.();- const released = await GenerationJobManager.approvals.finishPausePersistence(- streamId,- pauseActionId,- pauseCreatedAt,- );- if (!released) {- logger.warn(- `[ResumeAgentController] Re-pause persistence barrier changed before release: ${streamId}`,+ if (scheduleId) {+ await recordScheduleOutcome({+ scheduleId,+ scheduledFor,+ streamId,+ jobCreatedAt: job.createdAt,+ status: 'requires_action',+ conversationId,+ checkpointNamespace: client.checkpointNamespace,+ });+ }+ } else {+ logger.debug(+ `[ResumeAgentController] Skipping stale re-pause persistence: ${streamId} no longer owns its barrier`,);}+ return;+ }++ // If the user aborted mid-resume, the abort route already emitted the terminal+ // event and finalized the job; don't double-save / double-finalize here. This+ // continuation is nevertheless the scheduled-run owner, so it must settle the+ // run row after observing its own abort; the generic Stop route deliberately+ // delegates a running generation's settlement to that generation owner.+ if (job.abortController.signal.aborted) {+ logger.debug(+ `[ResumeAgentController] Aborted during resume; abort route finalizes: ${streamId}`,+ );if (scheduleId) {await recordScheduleOutcome({scheduleId,scheduledFor,streamId,jobCreatedAt: job.createdAt,- status: 'requires_action',+ status: 'interrupted',conversationId,- checkpointNamespace: client.checkpointNamespace,+ error: 'Scheduled run was stopped',});}- } else {- logger.debug(- `[ResumeAgentController] Skipping stale re-pause persistence — ${streamId} no longer owns its barrier`,- );+ return;}- return;- }- // If the user aborted mid-resume, the abort route already emitted the terminal- // event and finalized the job — don't double-save / double-finalize here. This- // continuation is nevertheless the scheduled-run owner, so it must settle the- // run row after observing its own abort; the generic Stop route deliberately- // delegates a running generation's settlement to that generation owner.- if (job.abortController.signal.aborted) {- logger.debug(- `[ResumeAgentController] Aborted during resume; abort route finalizes: ${streamId}`,- );- if (scheduleId) {- await recordScheduleOutcome({- scheduleId,- scheduledFor,- streamId,- jobCreatedAt: job.createdAt,- status: 'interrupted',- conversationId,- error: 'Scheduled run was stopped',- });- }- return;- }-- await finalizeResumedTurn({- req,- client,- job,- streamId,- conversationId,- addTitle,- checkpointGeneration,- appliedEventActor,- });- } catch (err) {- if (- eventActorResumePromise != null &&- eventActorStartGate != null &&- !eventActorContinuationStarted- ) {- eventActorStartGate.reject(err);- await eventActorResumePromise.catch(() => {});- }- logger.error('[ResumeAgentController] Resume failed', getSafeErrorMetadata(err));- if (pausePersistenceFailed) {- // failPausePersistence already performed the exact requires_action ->- // error transition. Only its CAS winner owns this generation's checkpoint- // cleanup; a stale/mismatched failure must leave the live scope intact.- if (pausePersistenceFailureFinalized) {- await deleteFailedResumeCheckpoint(- {+ await finalizeResumedTurn({+ req,+ client,+ job,+ streamId,+ conversationId,+ addTitle,+ checkpointGeneration,+ appliedEventActor,+ });+ } catch (err) {+ await rejectPendingEventActorResume(err);+ logger.error('[ResumeAgentController] Resume failed', getSafeErrorMetadata(err));+ await releaseScheduleFence();+ if (pausePersistenceFailed) {+ // failPausePersistence already performed the exact requires_action ->+ // error transition. Only its CAS winner owns this generation's checkpoint+ // cleanup; a stale/mismatched failure must leave the live scope intact.+ if (pausePersistenceFailureFinalized) {+ await deleteFailedResumeCheckpoint(+ {+ conversationId,+ checkpointerCfg,+ job,+ checkpointGeneration,+ },+ 're-pause persistence failure',+ );+ }+ if (scheduleId && pausePersistenceFailureFinalized) {+ await recordScheduleOutcome({+ scheduleId,+ scheduledFor,+ streamId,+ jobCreatedAt: job.createdAt,+ status: 'error',conversationId,- checkpointerCfg,- job,- checkpointGeneration,- },- 're-pause persistence failure',- );- }- if (scheduleId && pausePersistenceFailureFinalized) {- await recordScheduleOutcome({- scheduleId,- scheduledFor,- streamId,- jobCreatedAt: job.createdAt,- status: 'error',- conversationId,- error: err?.message ?? 'Re-pause persistence failed',- });+ error: err?.message ?? 'Re-pause persistence failed',+ });+ }+ return;}- return;- }- const errorMessage = getUserFacingResumeError(err, req.config);- // Job-replacement guard (mirrors finalizeResumedTurn's success-path guard): if a- // newer request reused this conversationId while the resume was failing, do NOT emit- // the error to / complete / prune the NEWER turn's job. The finally still releases- // the slot + disposes. Proceed with finalization if the replacement check itself fails.- let stillLive = true;- try {- const liveJob = await GenerationJobManager.getJobStore().getJob(streamId);- stillLive = !!liveJob && liveJob.createdAt === job.createdAt;- } catch (readErr) {- logger.warn(- '[ResumeAgentController] Replacement check failed; finalizing anyway',- getSafeErrorMetadata(readErr),- );- }- if (!stillLive) {- logger.warn(- `[ResumeAgentController] Skipping failed-resume finalization — job ${streamId} was replaced`,- );- } else {- // completeJob atomically claims running -> error and parks steers before- // publishing. If abort or a re-pause won, it returns false; only the- // terminal-CAS winner may delete this generation's checkpoint scope.- let errorFinalized = false;+ const errorMessage = getUserFacingResumeError(err, req.config);+ // Job-replacement guard (mirrors finalizeResumedTurn's success-path guard): if a+ // newer request reused this conversationId while the resume was failing, do NOT emit+ // the error to / complete / prune the NEWER turn's job. The finally still releases+ // the slot + disposes. Proceed with finalization if the replacement check itself fails.+ let stillLive = true;try {- errorFinalized =- (await GenerationJobManager.completeJob(streamId, errorMessage, job.createdAt)) === true;- } catch (completeErr) {- logger.error(- '[ResumeAgentController] Failed to finalize failed resume',- getSafeErrorMetadata(completeErr),+ const liveJob = await GenerationJobManager.getJobStore().getJob(streamId);+ stillLive = !!liveJob && liveJob.createdAt === job.createdAt;+ } catch (readErr) {+ logger.warn(+ '[ResumeAgentController] Replacement check failed; finalizing anyway',+ getSafeErrorMetadata(readErr),);}- if (errorFinalized) {- await deleteFailedResumeCheckpoint(- {- conversationId,- checkpointerCfg,- job,- checkpointGeneration,- },- 'failed resume finalization',+ if (!stillLive) {+ logger.warn(+ `[ResumeAgentController] Skipping failed-resume finalization: job ${streamId} was replaced`,);+ } else {+ // completeJob atomically claims running -> error and parks steers before+ // publishing. If abort or a re-pause won, it returns false; only the+ // terminal-CAS winner may delete this generation's checkpoint scope.+ let errorFinalized = false;+ try {+ errorFinalized =+ (await GenerationJobManager.completeJob(streamId, errorMessage, job.createdAt)) ===+ true;+ } catch (completeErr) {+ logger.error(+ '[ResumeAgentController] Failed to finalize failed resume',+ getSafeErrorMetadata(completeErr),+ );+ }+ if (errorFinalized) {+ await deleteFailedResumeCheckpoint(+ {+ conversationId,+ checkpointerCfg,+ job,+ checkpointGeneration,+ },+ 'failed resume finalization',+ );+ }+ if (scheduleId && errorFinalized) {+ const balanceRefusal = err?.message?.includes(ViolationTypes.TOKEN_BALANCE);+ await recordScheduleOutcome({+ scheduleId,+ scheduledFor,+ streamId,+ jobCreatedAt: job.createdAt,+ status: balanceRefusal ? 'skipped_balance' : 'error',+ conversationId,+ ...(!balanceRefusal && { error: err?.message ?? 'Resume failed' }),+ });+ }+ }+ if (!resumeAcknowledged && !res.headersSent) {+ sendGenerationJson(res, 500, { error: GENERIC_RESUME_ERROR }, generationProtocolVersion);}- if (scheduleId && errorFinalized) {- const balanceRefusal = err?.message?.includes(ViolationTypes.TOKEN_BALANCE);- await recordScheduleOutcome({- scheduleId,- scheduledFor,+ } finally {+ try {+ // Tear down the MCP request-context store seeded before the ACK (parity with+ // request.js's finishResumableRequest). No-op if it was never seeded.+ await cleanupMCPRequestContextForReq(req);+ // Release the concurrency slot taken above, UNLESS handleRunInterrupt already+ // released it on a re-pause (so a fast /resume isn't 429'd). On a normal finish or+ // error it didn't, so release here. A re-pause re-acquires its own slot next resume.+ if (!resumeSlotReleased && !client?.pendingRequestReleased) {+ await decrementPendingRequest(userId);+ }+ if (client) {+ disposeClient(client);+ }+ } finally {+ await GenerationJobManager.markProviderExecutionDrained?.(streamId,- jobCreatedAt: job.createdAt,- status: balanceRefusal ? 'skipped_balance' : 'error',- conversationId,- ...(!balanceRefusal && { error: err?.message ?? 'Resume failed' }),+ job.createdAt,+ providerExecutionId,+ ).catch((drainError) => {+ logger.warn('[ResumeAgentController] Failed to record provider drain', drainError);});+ await releaseEventChildLease?.();+ releaseEventChildLease = undefined;}}} finally {- try {- // Tear down the MCP request-context store seeded before the ACK (parity with- // request.js's finishResumableRequest). No-op if it was never seeded.- await cleanupMCPRequestContextForReq(req);- // Release the concurrency slot taken above — UNLESS handleRunInterrupt already- // released it on a re-pause (so a fast /resume isn't 429'd). On a normal finish or- // error it didn't, so release here. A re-pause re-acquires its own slot next resume.- if (!client?.pendingRequestReleased) {- await decrementPendingRequest(userId);- }- if (client) {- disposeClient(client);- }- } finally {- await GenerationJobManager.markProviderExecutionDrained?.(- streamId,- job.createdAt,- providerExecutionId,- ).catch((drainError) => {- logger.warn('[ResumeAgentController] Failed to record provider drain', drainError);- });+ if (!eventLeaseTransferredToRun) {await releaseEventChildLease?.();+ releaseEventChildLease = undefined;}}};diff --git a/api/server/controllers/assistants/chat.contentFilter.spec.js b/api/server/controllers/assistants/chat.contentFilter.spec.jsindex fe3fb8cf91..2b74083732 100644--- a/api/server/controllers/assistants/chat.contentFilter.spec.js+++ b/api/server/controllers/assistants/chat.contentFilter.spec.js@@ -6,12 +6,18 @@ const mockStreamRunManager = jest.fn();const mockSendEvent = jest.fn();const mockSaveUserMessage = jest.fn();const mockSaveAssistantMessage = jest.fn();-const mockCreateRunBody = jest.fn();+const mockCountTokens = jest.fn();+const mockCheckBalance = jest.fn();+const mockGetBalanceConfig = jest.fn();+const mockGetModelMaxTokens = jest.fn();+const mockGetTransactions = jest.fn();const mockSendResponse = jest.fn();+const mockCreateRunBody = jest.fn();const mockHandleError = jest.fn();const mockRetrieveAssistant = jest.fn();const mockListThreadMessages = jest.fn();const mockGetConvo = jest.fn();+const mockGetChatProject = jest.fn();const mockGetFiles = jest.fn();const mockEncodeAndFormat = jest.fn();const mockGetOpenAIClient = jest.fn().mockResolvedValue({@@ -43,20 +49,20 @@ jest.mock('@librechat/data-schemas', () => ({...jest.requireActual('@librechat/data-schemas'),logger: {debug: jest.fn(),+ info: jest.fn(),error: jest.fn(),warn: jest.fn(),},}));-jest.mock('@librechat/api', () => {const actual = jest.requireActual('../../../../packages/api/dist/index.cjs');return {...actual,sendEvent: (...args) => mockSendEvent(...args),- countTokens: jest.fn(),- checkBalance: jest.fn(),- getBalanceConfig: jest.fn(),- getModelMaxTokens: jest.fn(),+ countTokens: (...args) => mockCountTokens(...args),+ checkBalance: (...args) => mockCheckBalance(...args),+ getBalanceConfig: (...args) => mockGetBalanceConfig(...args),+ getModelMaxTokens: (...args) => mockGetModelMaxTokens(...args),};});@@ -117,9 +123,11 @@ jest.mock('~/models', () => ({releaseBalanceReservation: jest.fn(),renewBalanceReservation: jest.fn(),reserveBalance: jest.fn(),- getTransactions: jest.fn(),+ getTransactions: (...args) => mockGetTransactions(...args),getMultiplier: jest.fn(),getConvo: (...args) => mockGetConvo(...args),+ getChatProject: (...args) => mockGetChatProject(...args),+ getProjectFiles: (...args) => mockGetFiles(...args),getFiles: (...args) => mockGetFiles(...args),}));@@ -139,7 +147,6 @@ jest.mock('./helpers', () => ({const chatV1 = require('./chatV1');const chatV2 = require('./chatV2');const { logger } = require('@librechat/data-schemas');-const { checkBalance, getBalanceConfig } = require('@librechat/api');const { ImageVisionTool } = require('librechat-data-provider');describe.each([@@ -152,6 +159,12 @@ describe.each([beforeEach(() => {jest.clearAllMocks();+ mockCountTokens.mockReset().mockResolvedValue(0);+ mockCheckBalance.mockReset().mockResolvedValue(undefined);+ mockGetBalanceConfig.mockReset().mockReturnValue({ enabled: false });+ mockGetModelMaxTokens.mockReset().mockReturnValue(100000);+ mockGetTransactions.mockReset().mockResolvedValue([]);+ mockCreateRunBody.mockReset().mockReturnValue({});mockRetrieveAssistant.mockReset().mockResolvedValue({id: 'asst-1',instructions: 'Safe assistant',@@ -164,10 +177,10 @@ describe.each([mockGetFiles.mockReset().mockResolvedValue([]);mockGetConvo.mockReset().mockResolvedValue(null);mockEncodeAndFormat.mockReset().mockResolvedValue({ files: [], image_urls: [] });+ mockGetChatProject.mockReset().mockResolvedValue(null);mockInitThread.mockReset();mockCreateRun.mockReset();mockRunAssistant.mockReset();- mockCreateRunBody.mockReset();/* Every run that reaches FINAL has persisted its assistant row: the controller publishesthe conversation snapshot the client acknowledges, so a test that does not care aboutthe write still needs one. Tests asserting on the stamp override this. */@@ -230,6 +243,16 @@ describe.each([};});+ const useProject = (projectId, instructions) => {+ req.body.endpointOption = { ...req.body.endpointOption, chatProjectId: projectId };+ mockGetChatProject.mockResolvedValue({+ _id: projectId,+ instructions,+ contextRevision: 1,+ file_ids: [],+ });+ };+async function expectRawFreeRejection(rawContent, expectedSource, expectedField) {await chatController(req, res);@@ -322,8 +345,8 @@ describe.each([it('releases a balance reservation that settles after thread initialization fails', async () => {req.config.filters = {};const release = jest.fn().mockResolvedValue(undefined);- getBalanceConfig.mockReturnValue({ enabled: true });- checkBalance.mockImplementation(+ mockGetBalanceConfig.mockReturnValue({ enabled: true });+ mockCheckBalance.mockImplementation(() => new Promise((resolve) => setTimeout(() => resolve({ release }), 50)),);mockInitThread.mockRejectedValueOnce(new Error('stop after initThread'));@@ -331,7 +354,7 @@ describe.each([await chatController(req, res);expect(mockInitThread).toHaveBeenCalledTimes(1);- expect(checkBalance).toHaveBeenCalledTimes(1);+ expect(mockCheckBalance).toHaveBeenCalledTimes(1);expect(release).toHaveBeenCalledTimes(1);});@@ -362,6 +385,81 @@ describe.each([expect(mockRetrieveAssistant).toHaveBeenCalledWith('asst-1');expect(mockListThreadMessages).not.toHaveBeenCalled();});+ it('blocks project guidance before provider, thread, message, run, or stream side effects', async () => {+ req.config.filters = {+ agentInstructions: {+ pii: {+ fields: ['instructions'],+ starterPatterns: [],+ customPatterns: [+ {+ id: 'private',+ label: 'private value',+ regex: 'PRIVATE-[A-Z]+',+ },+ ],+ },+ },+ };+ useProject('507f1f77bcf86cd799439012', 'Project guidance PRIVATE-INSTRUCTION');++ await expectRawFreeRejection('PRIVATE-INSTRUCTION', 'agent_instruction', 'instructions');++ expect(mockGetChatProject).toHaveBeenCalledTimes(1);+ expect(mockGetOpenAIClient).not.toHaveBeenCalled();+ expect(mockValidateAuthor).not.toHaveBeenCalled();+ });+ it('returns not found for an unavailable Project without provider or close-handler effects', async () => {+ req.body.endpointOption = { chatProjectId: 'missing-project' };+ await chatController(req, res);++ expect(res.status).toHaveBeenCalledWith(404);+ expect(mockGetOpenAIClient).not.toHaveBeenCalled();+ expect(mockInitThread).not.toHaveBeenCalled();+ expect(mockSaveUserMessage).not.toHaveBeenCalled();+ expect(mockCreateRun).not.toHaveBeenCalled();+ expect(mockRunAssistant).not.toHaveBeenCalled();+ expect(mockStreamRunManager).not.toHaveBeenCalled();+ await closeHandler();+ expect(mockHandleError).not.toHaveBeenCalled();+ expect(mockSendResponse).not.toHaveBeenCalled();+ });++ it('passes authorized project guidance to the provider without loading project resources', async () => {+ const project = {+ _id: 'project-a',+ instructions: 'Project instructions for the provider',+ contextRevision: 4,+ file_ids: ['unused-project-file'],+ };+ req.body.endpoint = 'azureAssistants';+ req.body.endpointOption = { chatProjectId: 'project-a' };+ mockGetChatProject.mockResolvedValueOnce(project);+ mockGetFiles.mockRejectedValueOnce(new Error('unused project file lookup must not run'));+ mockInitThread.mockResolvedValueOnce({ thread_id: 'thread-existing' });+ mockGetOpenAIClient.mockResolvedValueOnce({+ openai: {+ _options: { model: 'gpt-4' },+ responseMessage: { messageId: 'response-message' },+ beta: {+ assistants: { retrieve: mockRetrieveAssistant },+ threads: { messages: { list: mockListThreadMessages }, runs: {} },+ },+ },+ });+ mockCreateRun.mockRejectedValueOnce(new Error('stop after provider request'));++ await chatController(req, res);++ expect(mockGetFiles).not.toHaveBeenCalled();+ expect(mockCreateRun).toHaveBeenCalledWith(+ expect.objectContaining({+ body: expect.objectContaining({+ additional_instructions: expect.stringContaining(project.instructions),+ }),+ }),+ );+ });it('blocks paged historical user text before thread, message, run, or stream side effects', async () => {req.config.filters = {@@ -672,8 +770,8 @@ describe.each([it('keeps the balance reservation until a run that continued in the background settles', async () => {req.config.filters = {};const release = jest.fn().mockResolvedValue(undefined);- getBalanceConfig.mockReturnValue({ enabled: true });- checkBalance.mockResolvedValue({ release });+ mockGetBalanceConfig.mockReturnValue({ enabled: true });+ mockCheckBalance.mockResolvedValue({ release });mockInitThread.mockResolvedValueOnce({ thread_id: 'thread-existing' });let finishBackgroundRun = () => undefined;const usage = { prompt_tokens: 1, completion_tokens: 1 };@@ -795,4 +893,128 @@ describe.each([});});}+ it('rejects a new hosted run before provider execution when project guidance exceeds balance', async () => {+ const projectContext = {+ projectId: '507f1f77bcf86cd799439012',+ contextRevision: 1,+ instructions: 'Large project guidance '.repeat(100),+ file_ids: [],+ };+ const projectInstructions = `Project guidance (user-provided context; subordinate to system, platform, agent, and tool policies):+${projectContext.instructions}`;+ req.body.thread_id = undefined;+ req.body.conversationId = undefined;+ useProject(projectContext.projectId, projectContext.instructions);+ mockGetBalanceConfig.mockReturnValueOnce({ enabled: true });+ mockGetTransactions.mockResolvedValueOnce([]);+ mockGetModelMaxTokens.mockReturnValueOnce(100000);+ mockCountTokens.mockImplementationOnce(async (value) => value.length);+ mockCheckBalance.mockRejectedValueOnce(new Error('Insufficient balance'));+ mockInitThread.mockResolvedValueOnce({ thread_id: 'thread-new' });++ await chatController(req, res);++ const promptText = `${req.body.text}\n\n${projectInstructions}`;+ expect(mockCountTokens).toHaveBeenCalledWith(promptText);+ expect(mockCheckBalance).toHaveBeenCalledWith(+ expect.objectContaining({+ txData: expect.objectContaining({+ amount: promptText.length + 5 + 200,+ }),+ }),+ expect.any(Object),+ );+ expect(mockCreateRun).not.toHaveBeenCalled();+ expect(mockRunAssistant).not.toHaveBeenCalled();+ expect(mockStreamRunManager).not.toHaveBeenCalled();+ });+ it('includes new authorized project membership in the final conversation payload', async () => {+ const projectContext = {+ projectId: '507f1f77bcf86cd799439012',+ contextRevision: 1,+ instructions: '',+ file_ids: [],+ };+ req.body.endpoint = 'azureAssistants';+ req.body.thread_id = undefined;+ useProject(projectContext.projectId, projectContext.instructions);+ mockInitThread.mockResolvedValueOnce({ thread_id: 'thread-new' });+ mockCreateRun.mockResolvedValueOnce({ id: 'run-new', status: 'completed' });+ mockRunAssistant.mockResolvedValueOnce({+ run: {+ id: 'run-new',+ status: 'completed',+ usage: { prompt_tokens: 1, completion_tokens: 1 },+ },+ responseMessage: { messageId: 'assistant-message' },+ text: 'Done',+ steps: [],+ messages: [],+ });+ mockGetOpenAIClient.mockResolvedValueOnce({+ openai: {+ _options: { model: 'gpt-4' },+ responseMessage: { messageId: 'response-message' },+ beta: {+ assistants: { retrieve: mockRetrieveAssistant },+ threads: { messages: { list: mockListThreadMessages }, runs: {} },+ },+ },+ });++ await chatController(req, res);++ const finalEvent = mockSendEvent.mock.calls.find(([, event]) => event.final)?.[1];+ expect(finalEvent?.conversation).toEqual(+ expect.objectContaining({ chatProjectId: projectContext.projectId }),+ );+ });++ it('uses persisted membership for an existing conversation in the final payload', async () => {+ const existingConversation = {+ conversationId: 'conversation-existing',+ chatProjectId: '507f1f77bcf86cd799439013',+ };+ req.body.endpoint = 'azureAssistants';+ req.body.conversationId = existingConversation.conversationId;+ req.body.thread_id = 'thread-existing';+ mockGetConvo.mockResolvedValueOnce(existingConversation);+ mockGetChatProject.mockResolvedValueOnce({+ _id: '507f1f77bcf86cd799439014',+ contextRevision: 2,+ instructions: '',+ file_ids: [],+ });+ mockInitThread.mockResolvedValueOnce({ thread_id: 'thread-existing' });+ mockCreateRun.mockResolvedValueOnce({ id: 'run-existing', status: 'completed' });+ mockRunAssistant.mockResolvedValueOnce({+ run: {+ id: 'run-existing',+ status: 'completed',+ usage: { prompt_tokens: 1, completion_tokens: 1 },+ },+ responseMessage: { messageId: 'assistant-message' },+ text: 'Done',+ steps: [],+ messages: [],+ });+ mockGetOpenAIClient.mockResolvedValueOnce({+ openai: {+ _options: { model: 'gpt-4' },+ responseMessage: { messageId: 'response-message' },+ beta: {+ assistants: { retrieve: mockRetrieveAssistant },+ threads: { messages: { list: mockListThreadMessages }, runs: {} },+ },+ },+ });++ await chatController(req, res);++ const finalEvent = mockSendEvent.mock.calls.find(([, event]) => event.final)?.[1];+ expect(finalEvent?.conversation).toEqual(+ expect.objectContaining({ chatProjectId: existingConversation.chatProjectId }),+ );+ expect(finalEvent?.conversation?.chatProjectId).not.toBe('507f1f77bcf86cd799439014');+ });});diff --git a/api/server/controllers/assistants/chatV1.js b/api/server/controllers/assistants/chatV1.jsindex 0f66c07154..95f0d66e2c 100644--- a/api/server/controllers/assistants/chatV1.js+++ b/api/server/controllers/assistants/chatV1.js@@ -17,6 +17,8 @@ const {reportLocatorTraversalFailure,preflightAssistantUserMessageContent,settleAssistantFinal,+ resolveAssistantProjectTurn,+ joinChatProjectInstructions,} = require('@librechat/api');const {Time,@@ -55,7 +57,9 @@ const {reserveBalance,getMultiplier,getConvo,+ getProjectFiles,getFiles,+ getChatProject,} = require('~/models');const { logViolation, getLogStores } = require('~/cache');const { getOpenAIClient } = require('./helpers');@@ -272,6 +276,25 @@ const chatV1 = async (req, res) => {await handleError(new Error('Request closed'));}});+ const projectTurn = await resolveAssistantProjectTurn(+ {+ userId: req.user.id,+ tenantId: req.user.tenantId,+ conversationId: convoId,+ requestedProjectId: endpointOption?.chatProjectId ?? req.body?.chatProjectId,+ resolvedConversation: req.resolvedConversation,+ filters: req.config?.filters,+ },+ { getConvo, getChatProject, getProjectFiles },+ );+ if (projectTurn.rejection) {+ contentRejected = true;+ return res.status(projectTurn.rejection.status).json(projectTurn.rejection.body);+ }+ const existingConversation = projectTurn.conversation;+ const projectInstructions = projectTurn.instructions;+ req.resolvedConversation = existingConversation;+ req.chatProjectContext = projectTurn.context;if (convoId && !_thread_id) {completedRun = true;@@ -299,11 +322,14 @@ const chatV1 = async (req, res) => {transactions.reduce((acc, curr) => acc + curr.rawAmount, 0),);- // TODO: make promptBuffer a config option; buffer for titles, needs buffer for system instructions+ // TODO: make promptBuffer a config option; buffer for title generation.const promptBuffer = parentMessageId === Constants.NO_PARENT && !_thread_id ? 200 : 0;// 5 is added for labels- let promptTokens = (await countTokens(text + (promptPrefix ?? ''))) + 5;- promptTokens += totalPreviousTokens + promptBuffer;+ const promptText = joinChatProjectInstructions(+ `${text ?? ''}${promptPrefix ?? ''}`,+ projectInstructions,+ );+ let promptTokens = totalPreviousTokens + (await countTokens(promptText)) + 5 + promptBuffer;// Count tokens up to the current context windowpromptTokens = Math.min(promptTokens, getModelMaxTokens(model));@@ -385,7 +411,7 @@ const chatV1 = async (req, res) => {const getRequestFileIds = async () => {let thread_file_ids = [];if (convoId) {- const convo = await getConvo(req.user.id, convoId);+ const convo = existingConversation;if (convo && convo.file_ids) {thread_file_ids = convo.file_ids;}@@ -404,6 +430,12 @@ const chatV1 = async (req, res) => {}}};+ if (projectInstructions) {+ body.additional_instructions = joinChatProjectInstructions(+ body.additional_instructions,+ projectInstructions,+ );+ }const addVisionPrompt = async () => {if (!endpointOption.attachments) {@@ -534,6 +566,7 @@ const chatV1 = async (req, res) => {/* asynchronous */userMessagePromise = saveUserMessage(req, { ...requestMessage, model });+ const conversationProjectId = projectTurn.membershipProjectId;conversation = {conversationId,endpoint,@@ -541,6 +574,7 @@ const chatV1 = async (req, res) => {instructions: instructions,assistant_id,// model,+ ...(conversationProjectId !== undefined ? { chatProjectId: conversationProjectId } : {}),};if (file_ids.length) {diff --git a/api/server/controllers/assistants/chatV2.js b/api/server/controllers/assistants/chatV2.jsindex d573b50b32..992dbfdfa9 100644--- a/api/server/controllers/assistants/chatV2.js+++ b/api/server/controllers/assistants/chatV2.js@@ -16,6 +16,8 @@ const {reportLocatorTraversalFailure,preflightAssistantUserMessageContent,settleAssistantFinal,+ resolveAssistantProjectTurn,+ joinChatProjectInstructions,} = require('@librechat/api');const {Time,@@ -49,6 +51,8 @@ const {reserveBalance,renewBalanceReservation,releaseBalanceReservation,+ getChatProject,+ getProjectFiles,getFiles,} = require('~/models');const { logViolation, getLogStores } = require('~/cache');@@ -143,6 +147,25 @@ const chatV2 = async (req, res) => {await handleError(new Error('Request closed'));}});+ const projectTurn = await resolveAssistantProjectTurn(+ {+ userId: req.user.id,+ tenantId: req.user.tenantId,+ conversationId: convoId,+ requestedProjectId: endpointOption?.chatProjectId ?? req.body?.chatProjectId,+ resolvedConversation: req.resolvedConversation,+ filters: req.config?.filters,+ },+ { getConvo, getChatProject, getProjectFiles },+ );+ if (projectTurn.rejection) {+ contentRejected = true;+ return res.status(projectTurn.rejection.status).json(projectTurn.rejection.body);+ }+ const existingConversation = projectTurn.conversation;+ const projectInstructions = projectTurn.instructions;+ req.resolvedConversation = existingConversation;+ req.chatProjectContext = projectTurn.context;if (convoId && !_thread_id) {completedRun = true;@@ -170,11 +193,14 @@ const chatV2 = async (req, res) => {transactions.reduce((acc, curr) => acc + curr.rawAmount, 0),);- // TODO: make promptBuffer a config option; buffer for titles, needs buffer for system instructions+ // TODO: make promptBuffer a config option; buffer for title generation.const promptBuffer = parentMessageId === Constants.NO_PARENT && !_thread_id ? 200 : 0;// 5 is added for labels- let promptTokens = (await countTokens(text + (promptPrefix ?? ''))) + 5;- promptTokens += totalPreviousTokens + promptBuffer;+ const promptText = joinChatProjectInstructions(+ `${text ?? ''}${promptPrefix ?? ''}`,+ projectInstructions,+ );+ let promptTokens = totalPreviousTokens + (await countTokens(promptText)) + 5 + promptBuffer;// Count tokens up to the current context windowpromptTokens = Math.min(promptTokens, getModelMaxTokens(model));@@ -256,20 +282,17 @@ const chatV2 = async (req, res) => {endpointOption,clientTimestamp,});-- let existingConversationPromise;- const getExistingConversation = () => {- if (!convoId) {- return Promise.resolve(null);- }- existingConversationPromise ??= getConvo(req.user.id, convoId);- return existingConversationPromise;- };+ if (projectInstructions) {+ body.additional_instructions = joinChatProjectInstructions(+ body.additional_instructions,+ projectInstructions,+ );+ }const getRequestFileIds = async () => {let thread_file_ids = [];if (convoId) {- const convo = await getExistingConversation();+ const convo = existingConversation;if (convo && convo.file_ids) {thread_file_ids = convo.file_ids;}@@ -364,6 +387,7 @@ const chatV2 = async (req, res) => {/* asynchronous */userMessagePromise = saveUserMessage(req, { ...requestMessage, model });+ const conversationProjectId = projectTurn.membershipProjectId;conversation = {conversationId,endpoint,@@ -371,6 +395,7 @@ const chatV2 = async (req, res) => {instructions: instructions,assistant_id,// model,+ ...(conversationProjectId !== undefined ? { chatProjectId: conversationProjectId } : {}),};if (file_ids.length) {diff --git a/api/server/routes/__tests__/config.spec.js b/api/server/routes/__tests__/config.spec.jsindex 338d434de7..557cdecce9 100644--- a/api/server/routes/__tests__/config.spec.js+++ b/api/server/routes/__tests__/config.spec.js@@ -104,6 +104,7 @@ afterEach(() => {delete process.env.SAML_SESSION_SECRET;delete process.env.ALLOW_ACCOUNT_DELETION;delete process.env.ALLOW_EMAIL_CHANGE;+ delete process.env.RAG_API_URL;delete process.env.ADMIN_PANEL_URL;delete process.env.ENABLE_INSIGHTS;delete process.env.ANALYTICS_GTM_ID;@@ -357,6 +358,26 @@ describe('GET /api/config', () => {});describe('authenticated (req.user exists)', () => {+ it('exposes retrieval availability only after login without exposing the service URL', async () => {+ mockGetAppConfig.mockResolvedValue(baseAppConfig);+ const app = createApp(mockUser);+ delete process.env.RAG_API_URL;++ const disabled = await request(app).get('/api/config');+ expect(disabled.statusCode).toBe(200);+ expect(disabled.body.ragEnabled).toBe(false);++ process.env.RAG_API_URL = 'http://rag.internal:8000';+ const enabled = await request(app).get('/api/config');+ expect(enabled.statusCode).toBe(200);+ expect(enabled.body.ragEnabled).toBe(true);+ expect(JSON.stringify(enabled.body)).not.toContain(process.env.RAG_API_URL);++ const anonymous = await request(createApp()).get('/api/config');+ expect(anonymous.statusCode).toBe(200);+ expect(anonymous.body).not.toHaveProperty('ragEnabled');+ });+it('should call getAppConfig with role, userId, and tenantId', async () => {mockGetAppConfig.mockResolvedValue(baseAppConfig);mockGetTenantId.mockReturnValue('fallback-tenant');diff --git a/api/server/routes/__tests__/projects.spec.js b/api/server/routes/__tests__/projects.spec.jsnew file mode 100644index 0000000000..9137ba190e--- /dev/null+++ b/api/server/routes/__tests__/projects.spec.js@@ -0,0 +1,151 @@+const express = require('express');+const request = require('supertest');++const resolvedConfig = {+ projects: {+ maxFiles: 3,+ maxInstructionsLength: 120,+ maxDescriptionLength: 80,+ },+};+const mockHandler = jest.fn((req, res) => {+ res.status(200).json({ config: req.config });+});+const mockCreateProjectHandlers = jest.fn(() => ({+ listProjects: mockHandler,+ createProject: mockHandler,+ assignConversationToProject: mockHandler,+ getProject: mockHandler,+ updateProject: mockHandler,+ deleteProject: mockHandler,+ listProjectFiles: mockHandler,+ listAvailableProjectFiles: mockHandler,+ addProjectFile: mockHandler,+ removeProjectFile: mockHandler,+}));+const mockRequireJwtAuth = jest.fn((req, _res, next) => {+ req.user = { id: 'project-user', tenantId: 'tenant-a' };+ next();+});+const mockConfigMiddleware = jest.fn((req, _res, next) => {+ req.config = resolvedConfig;+ next();+});++jest.mock('@librechat/api', () => ({ createProjectHandlers: mockCreateProjectHandlers }));+jest.mock('~/models', () => ({+ listChatProjects: jest.fn(),+ createChatProject: jest.fn(),+ getChatProject: jest.fn(),+ updateChatProject: jest.fn(),+ deleteChatProject: jest.fn(),+ assignConversationToProject: jest.fn(),+ addChatProjectFile: jest.fn(),+ removeChatProjectFile: jest.fn(),+ getProjectFiles: jest.fn(),+ getAvailableProjectFiles: jest.fn(),+}));+jest.mock('~/server/middleware', () => ({+ requireJwtAuth: mockRequireJwtAuth,+ configMiddleware: mockConfigMiddleware,+}));++const projectsRouter = require('../projects');++const app = express();+app.use(express.json());+app.use('/api/projects', projectsRouter);++const routeCases = [+ { name: 'list projects', method: 'get', path: '/api/projects', resolvesConfig: false },+ { name: 'create projects', method: 'post', path: '/api/projects', resolvesConfig: true },+ {+ name: 'assign conversations',+ method: 'put',+ path: '/api/projects/conversations/conversation-id',+ resolvesConfig: false,+ },+ {+ name: 'list available project files',+ method: 'get',+ path: '/api/projects/project-id/files/available',+ resolvesConfig: false,+ },+ {+ name: 'list project files',+ method: 'get',+ path: '/api/projects/project-id/files',+ resolvesConfig: false,+ },+ {+ name: 'add project files',+ method: 'post',+ path: '/api/projects/project-id/files',+ resolvesConfig: true,+ },+ {+ name: 'remove project files',+ method: 'delete',+ path: '/api/projects/project-id/files/file-id',+ resolvesConfig: false,+ },+ {+ name: 'get projects',+ method: 'get',+ path: '/api/projects/project-id',+ resolvesConfig: false,+ },+ {+ name: 'update projects',+ method: 'patch',+ path: '/api/projects/project-id',+ resolvesConfig: true,+ },+ {+ name: 'delete projects',+ method: 'delete',+ path: '/api/projects/project-id',+ resolvesConfig: false,+ },+];++describe('Projects route middleware', () => {+ beforeEach(() => {+ mockRequireJwtAuth.mockClear();+ mockConfigMiddleware.mockClear();+ mockHandler.mockClear();+ });++ it.each(routeCases)(+ '$name resolves config only when required',+ async ({ method, path, resolvesConfig }) => {+ const response = await request(app)[method](path);++ expect(response.status).toBe(200);+ expect(mockRequireJwtAuth).toHaveBeenCalledTimes(1);+ expect(mockHandler).toHaveBeenCalledTimes(1);+ expect(mockHandler.mock.calls[0][0].config).toEqual(+ resolvesConfig ? resolvedConfig : undefined,+ );++ if (resolvesConfig) {+ expect(mockConfigMiddleware).toHaveBeenCalledTimes(1);+ expect(mockConfigMiddleware.mock.calls[0][0].user).toEqual({+ id: 'project-user',+ tenantId: 'tenant-a',+ });+ expect(mockRequireJwtAuth.mock.invocationCallOrder[0]).toBeLessThan(+ mockConfigMiddleware.mock.invocationCallOrder[0],+ );+ expect(mockConfigMiddleware.mock.invocationCallOrder[0]).toBeLessThan(+ mockHandler.mock.invocationCallOrder[0],+ );+ } else {+ expect(mockConfigMiddleware).not.toHaveBeenCalled();+ expect(mockRequireJwtAuth.mock.invocationCallOrder[0]).toBeLessThan(+ mockHandler.mock.invocationCallOrder[0],+ );+ }+ },+ );+});diff --git a/api/server/routes/config.js b/api/server/routes/config.jsindex 977781c861..38bfd4ee7f 100644--- a/api/server/routes/config.js+++ b/api/server/routes/config.js@@ -156,6 +156,7 @@ function buildPostLoginPayload(appConfig) {sharedLinksEnabled,publicSharedLinksEnabled,openidReuseTokens,+ ragEnabled: Boolean(process.env.RAG_API_URL?.trim()),/** Read inline (not module-level) for per-request evaluation and test isolation */allowAccountDeletion:process.env.ALLOW_ACCOUNT_DELETION === undefined ||@@ -303,6 +304,7 @@ router.get('/', async function (req, res) {conversationListLimits,sharedLinksSnapshotFilesEnabled: sharedLinksEnabled && isFileSnapshotEnabled(appConfig),socialLogins: appConfig?.registration?.socialLogins ?? defaultSocialLogins,+ projects: appConfig?.projects,interface: appConfig?.interfaceConfig,titleGenerationTiming: resolveTitleTiming({appConfig,diff --git a/api/server/routes/projects.js b/api/server/routes/projects.jsindex fd782a1ba5..8c0414fe62 100644--- a/api/server/routes/projects.js+++ b/api/server/routes/projects.js@@ -1,6 +1,6 @@const express = require('express');const { createProjectHandlers } = require('@librechat/api');-const requireJwtAuth = require('~/server/middleware/requireJwtAuth');+const { configMiddleware, requireJwtAuth } = require('~/server/middleware');const db = require('~/models');const router = express.Router();@@ -11,15 +11,21 @@ const handlers = createProjectHandlers({updateChatProject: db.updateChatProject,deleteChatProject: db.deleteChatProject,assignConversationToProject: db.assignConversationToProject,+ addChatProjectFile: db.addChatProjectFile,+ removeChatProjectFile: db.removeChatProjectFile,+ getProjectFiles: db.getProjectFiles,+ getAvailableProjectFiles: db.getAvailableProjectFiles,});-router.use(requireJwtAuth);-router.get('/', handlers.listProjects);-router.post('/', handlers.createProject);+router.post('/', configMiddleware, handlers.createProject);router.put('/conversations/:conversationId', handlers.assignConversationToProject);+router.get('/:projectId/files/available', handlers.listAvailableProjectFiles);+router.get('/:projectId/files', handlers.listProjectFiles);+router.post('/:projectId/files', configMiddleware, handlers.addProjectFile);+router.delete('/:projectId/files/:fileId', handlers.removeProjectFile);router.get('/:projectId', handlers.getProject);-router.patch('/:projectId', handlers.updateProject);+router.patch('/:projectId', configMiddleware, handlers.updateProject);router.delete('/:projectId', handlers.deleteProject);module.exports = router;diff --git a/api/server/services/Endpoints/agents/addedConvo.js b/api/server/services/Endpoints/agents/addedConvo.jsindex 4fed579568..b22c3b5b0b 100644--- a/api/server/services/Endpoints/agents/addedConvo.js+++ b/api/server/services/Endpoints/agents/addedConvo.js@@ -205,6 +205,7 @@ const processAddedConvo = async ({signal,},{+ getProjectFiles: db.getProjectFiles,getFiles: db.getFiles,getUserKey: db.getUserKey,getMessages: db.getMessages,diff --git a/api/server/services/Endpoints/agents/initialize.js b/api/server/services/Endpoints/agents/initialize.jsindex 68de908eb1..83420383ba 100644--- a/api/server/services/Endpoints/agents/initialize.js+++ b/api/server/services/Endpoints/agents/initialize.js@@ -6,6 +6,7 @@ const {resolveAdmittedCodeEnvironmentDecision,createConcurrencyLimiter,loadSkillStates,+ resolveInitializationProjectContext,initializeAgent,primeInvokedSkillsForProfiles,validateAgentModel,@@ -23,9 +24,9 @@ const {collectCodeExecutionProfileRoutes,getLazySubagentConfigId,resolveCodeExecutionContext,- resolveCodeExecutionWorkspaceContext,optsOutOfAttachedCodeEnvironment,isImplicitStatefulCodeRouteAvailable,+ resolveCodeExecutionWorkspaceContext,createStatefulCodeEnvironmentPolicyError,buildSubagentThreadTaskConfig,backgroundCompletionWakeupsEnabled,@@ -587,6 +588,15 @@ const initializeClientWithProvider = async ({/** @type {Array<import('librechat-data-provider').TTokenUsageEvent>} */const usageEmitSink = [];+ const chatProjectContextPromise = resolveInitializationProjectContext(+ { req, endpointOption, conversationId, conversationPromise: requestConversationPromise },+ {+ getConvo: db.getConvo,+ getChatProject: db.getChatProject,+ getProjectFiles: db.getProjectFiles,+ },+ );+const [memoryAvailable,accessibleSkillIds,@@ -595,6 +605,7 @@ const initializeClientWithProvider = async ({{ skillStates, defaultActiveOnShare },{ primaryAgent, modelsConfig },requestConversation,+ chatProjectContext,toolRoleGrants,] = await Promise.all([memoryAvailablePromise,@@ -604,10 +615,13 @@ const initializeClientWithProvider = async ({skillStatesPromise,validatedPrimaryAgentPromise,requestConversationPromise,+ chatProjectContextPromise,toolRoleGrantsPromise,]);/** Preserve the owner-scoped fallback for loaders that share this request. */req.resolvedConversation = requestConversation;+ req.chatProjectContext = chatProjectContext;+ req.chatProjectContextEnabled = true;const { decision: codeEnvironmentDecision, conversation: admittedConversation } =await resolveAdmittedCodeEnvironmentDecision({appConfig,@@ -700,7 +714,6 @@ const initializeClientWithProvider = async ({primaryAgent.skills = resolvedSkillIds.map((id) => id.toString());}}-const primaryScopedSkillIds = resolveAgentScopedSkillIds({agent: primaryAgent,accessibleSkillIds,@@ -720,9 +733,9 @@ const initializeClientWithProvider = async ({skillsCapabilityEnabled,ephemeralSkillsToggle,});-const primaryConfig = await initializeAgent({+ useChatProjectContext: true,req,res,loadTools,@@ -749,6 +762,7 @@ const initializeClientWithProvider = async ({signal,},{+ getProjectFiles: db.getProjectFiles,getFiles: db.getFiles,getUserKey: db.getUserKey,getMessages: db.getMessages,@@ -841,6 +855,7 @@ const initializeClientWithProvider = async ({checkPermission,logViolation,db: {+ getProjectFiles: db.getProjectFiles,getFiles: db.getFiles,getUserKey: db.getUserKey,getMessages: db.getMessages,@@ -1326,6 +1341,7 @@ const initializeClientWithProvider = async ({signal: context.signal,},{+ getProjectFiles: db.getProjectFiles,getFiles: db.getFiles,getUserKey: db.getUserKey,getMessages: db.getMessages,diff --git a/api/server/services/Endpoints/agents/initialize.spec.js b/api/server/services/Endpoints/agents/initialize.spec.jsindex b68966d1b8..43a94d6914 100644--- a/api/server/services/Endpoints/agents/initialize.spec.js+++ b/api/server/services/Endpoints/agents/initialize.spec.js@@ -771,6 +771,48 @@ describe('initializeClient — processAgent ACL gate', () => {canCreateSkillSpy.mockRestore();}});+ it('starts Project lookup as soon as the conversation snapshot resolves', async () => {+ const models = deferred();+ const conversation = deferred();+ const project = deferred();+ const req = makeReq();+ delete req.resolvedConversation;+ const getConvoSpy = jest.spyOn(db, 'getConvo').mockReturnValue(conversation.promise);+ const getChatProjectSpy = jest.spyOn(db, 'getChatProject').mockReturnValue(project.promise);+ getModelsConfig.mockReturnValueOnce(models.promise);+ mockInitializeAgent.mockResolvedValue(makePrimaryConfig([]));++ try {+ const initialization = initializeClient({+ req,+ res: {},+ signal: new AbortController().signal,+ endpointOption: makeEndpointOption(),+ });++ conversation.resolve({+ conversationId: 'conv_1',+ chatProjectId: 'project-1',+ user: req.user.id,+ tenantId: null,+ });+ await new Promise((resolve) => setImmediate(resolve));+ expect(getChatProjectSpy).toHaveBeenCalledWith(req.user.id, 'project-1');++ models.resolve({});+ project.resolve({+ _id: 'project-1',+ instructions: '',+ contextRevision: 0,+ file_ids: [],+ tenantId: null,+ });+ await initialization;+ } finally {+ getConvoSpy.mockRestore();+ getChatProjectSpy.mockRestore();+ }+ });it('resolves model-spec skill names through deployment-aware skill methods', async () => {const deploymentSkillId = new mongoose.Types.ObjectId();diff --git a/api/server/services/Threads/manage.js b/api/server/services/Threads/manage.jsindex c6dd17b065..2400c72663 100644--- a/api/server/services/Threads/manage.js+++ b/api/server/services/Threads/manage.js@@ -82,6 +82,9 @@ async function saveUserMessage(req, params) {tokenCount,};+ // Only confirmed new conversations seed membership; saveConvo applies it on insert.+ const chatProjectId =+ req?.resolvedConversation === null ? req.chatProjectContext?.projectId : undefined;const convo = {endpoint: params.endpoint,conversationId: params.conversationId,@@ -89,8 +92,8 @@ async function saveUserMessage(req, params) {instructions: params.instructions,assistant_id: params.assistant_id,model: params.model,+ ...(typeof chatProjectId === 'string' && chatProjectId ? { chatProjectId } : {}),};-if (params.files?.length) {userMessage.files = params.files.map(({ file_id }) => ({ file_id }));convo.file_ids = params.file_ids;diff --git a/api/server/services/Threads/manage.retention.spec.js b/api/server/services/Threads/manage.retention.spec.jsindex 60e0ee09cf..c3469ecb4b 100644--- a/api/server/services/Threads/manage.retention.spec.js+++ b/api/server/services/Threads/manage.retention.spec.js@@ -9,7 +9,8 @@ jest.mock('@librechat/api', () => ({jest.mock('~/server/services/Files/process', () => ({ retrieveAndProcessFile: jest.fn() }));-const { Message, Conversation } = require('~/db/models');+const { Message, Conversation, ChatProject } = require('~/db/models');+const { createChatProject, assignConversationToProject } = require('~/models');const { saveUserMessage, saveAssistantMessage, checkMessageGaps } = require('./manage');describe('Assistants message retention', () => {@@ -25,6 +26,43 @@ describe('Assistants message retention', () => {await mongoServer.stop();});+ it('seeds Project membership once and preserves a concurrent move without revalidation', async () => {+ const user = new mongoose.Types.ObjectId().toString();+ const conversationId = v4();+ const firstProject = await createChatProject(user, { name: 'Original project' });+ const nextProject = await createChatProject(user, { name: 'Moved project' });+ const firstProjectId = firstProject._id.toString();+ const nextProjectId = nextProject._id.toString();+ const req = {+ user: { id: user },+ body: { conversationId },+ resolvedConversation: null,+ chatProjectContext: { projectId: firstProjectId },+ config: {},+ };+ const params = {+ user,+ conversationId,+ endpoint: 'assistants',+ assistant_id: 'asst_project',+ thread_id: 'thread_project',+ text: 'Continue with the authorized context.',+ };+ await saveUserMessage(req, { ...params, messageId: v4() });+ expect(req.resolvedConversation.chatProjectId).toBe(firstProjectId);++ await assignConversationToProject(user, conversationId, nextProjectId);+ const projectLookup = jest.spyOn(ChatProject, 'exists');+ try {+ await saveUserMessage(req, { ...params, messageId: v4() });+ const saved = await Conversation.findOne({ user, conversationId }).lean();+ expect(saved.chatProjectId).toBe(nextProjectId);+ expect(projectLookup).not.toHaveBeenCalled();+ } finally {+ projectLookup.mockRestore();+ }+ });+it.each([false, true])('retains the full turn and gap sync with isTemporary=%s',async (isTemporary) => {diff --git a/api/server/services/__tests__/toolCapabilityGates.spec.js b/api/server/services/__tests__/toolCapabilityGates.spec.jsindex 56820fec4b..1b8693ddc2 100644--- a/api/server/services/__tests__/toolCapabilityGates.spec.js+++ b/api/server/services/__tests__/toolCapabilityGates.spec.js@@ -47,12 +47,15 @@ const CLASSIFIED = {* comment. */'packages/api/src/agents/openai/service.ts': 3,+ /** Two gates for the project file corpus (`addProjectFilesToFileSearch` and+ * `canUseProjectFileSearch`), each paired with the `fileSearchAvailable`+ * grant resolved by the caller, plus two `recordCapabilityToolNames`+ * bookkeeping reads that describe what was built. */+ 'packages/api/src/agents/initialize.ts': 4,+// -- Not gates ---------------------------------------------------------------/** The upload-resource map entry, and one mention in a doc comment. */'packages/api/src/tools/rolePermissions.ts': 2,- /** `recordCapabilityToolNames` bookkeeping — describes what was built, does- * not decide whether to build it. */- 'packages/api/src/agents/initialize.ts': 2,/** Default capability list shipped in config. */'packages/data-provider/src/config.ts': 2,/** Config normalization only: strips stale `tool_options` when the capabilitydiff --git a/client/src/components/Chat/ChatView.tsx b/client/src/components/Chat/ChatView.tsxindex fbf26cf3e9..feaccb0b01 100644--- a/client/src/components/Chat/ChatView.tsx+++ b/client/src/components/Chat/ChatView.tsx@@ -27,6 +27,7 @@ import {import ApprovalProvider from './Messages/Content/ApprovalContext';import ConversationStarters from './Input/ConversationStarters';import { pendingApprovalActionFamily } from './approval/state';+import ProjectBadge from '~/components/Projects/ProjectBadge';import { composerLiftFamily } from './Input/Composer/state';import { showComposerTipsAtom } from '~/store/composerTips';import { useGetMessagesByConvoId } from '~/data-provider';@@ -112,6 +113,7 @@ function ChatView({ index = 0, project }: { index?: number; project?: TChatProje? chatHelpers.conversation: undefined;const activeSubagentThread = activeConversation?.subagentThread;+ const chatProjectId = activeConversation?.chatProjectId || undefined;useAdaptiveSSE(rootSubmission, chatHelpers, false, index);@@ -182,24 +184,27 @@ function ChatView({ index = 0, project }: { index?: number; project?: TChatProje<h1 className="sr-only">{pageHeading}</h1>{/* Marks the header's controls as this pane's, so a pane-scopedshortcut pressed from them acts here, not on the first pane. */}- <div data-chat-pane-portal={index} className="contents">- <Header- parentConversationId={parentConversationId}- readOnly={isSubagentThreadReadOnly}- />- </div>- <>- <div- data-chat-pane={index}- style={- isLandingPage && composerLift > 0- ? { transform: `translateY(-${composerLift}px)` }- : undefined- }- className={cn(- 'flex flex-col',- isLandingPage- ? /* The gutter is reserved once per state, wherever the+ <div data-chat-pane-portal={index} className="contents">+ <Header+ parentConversationId={parentConversationId}+ readOnly={isSubagentThreadReadOnly}+ />+ </div>+ {!isLandingPage && chatProjectId && (+ <ProjectBadge projectId={chatProjectId} />+ )}+ <>+ <div+ data-chat-pane={index}+ style={+ isLandingPage && composerLift > 0+ ? { transform: `translateY(-${composerLift}px)` }+ : undefined+ }+ className={cn(+ 'flex flex-col',+ isLandingPage+ ? /* The gutter is reserved once per state, wherever thecentring happens. A conversation centres the composerinside the band below, against a message column thatholds the scrollbar band back; the landing page centres@@ -207,12 +212,13 @@ function ChatView({ index = 0, project }: { index?: number; project?: TChatProjetogether, so it holds the same band back here. Withoutit the composer lands 4px right of where a conversationputs it and slides sideways on the way in. */- 'scrollbar-gutter-spacer flex-1 items-center justify-end sm:justify-center'- : 'h-full overflow-y-auto',- )}- >- {content}- {/* Named + opaque so a view transition (the ask_user_question+ 'scrollbar-gutter-spacer flex-1 items-center justify-end sm:justify-center'+ : 'h-full overflow-y-auto',+ !isLandingPage && chatProjectId && 'pt-9',+ )}+ >+ {content}+ {/* Named + opaque so a view transition (the ask_user_questionpopover ⇄ chat-card morph) paints the whole composer bandover the travelling card instead of letting it showthrough below the composer. The background matches thediff --git a/client/src/components/Chat/__tests__/ChatView.spec.tsx b/client/src/components/Chat/__tests__/ChatView.spec.tsxindex 1be3ca02a8..e8d4d94b8a 100644--- a/client/src/components/Chat/__tests__/ChatView.spec.tsx+++ b/client/src/components/Chat/__tests__/ChatView.spec.tsx@@ -20,6 +20,7 @@ jest.mock('~/hooks/AuthContext', () => ({jest.mock('~/data-provider', () => ({useGetMessagesByConvoId: () => ({ data: null, isLoading: false, isFetching: false }),+ useProjectQuery: () => ({ data: undefined }),}));/**@@ -72,12 +73,6 @@ describe('ChatView page heading', () => {expect(headings).toHaveLength(1);});- test('keeps the heading visually hidden', () => {- render(<ChatView />);-- expect(screen.getByRole('heading', { level: 1 })).toHaveClass('sr-only');- });-test('announces a localized new chat heading on the landing page', () => {render(<ChatView />);diff --git a/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx b/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsxindex f8527fa1d2..93d1073599 100644--- a/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx+++ b/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx@@ -55,6 +55,7 @@ jest.mock('~/Providers', () => {});jest.mock('~/data-provider', () => ({+ useProjectQuery: () => ({ data: undefined }),useGetMessagesByConvoId: () => ({data: [{ messageId: 'message-1' }],isLoading: false,@@ -114,20 +115,4 @@ describe('ChatView child-thread execution identity', () => {expect(screen.getByRole('note')).toHaveTextContent('com_ui_subagent_thread_read_only');expect(screen.getByTestId('header')).toHaveAttribute('data-read-only', 'true');});-- it('keeps a saved-agent child view-only after it settles', () => {- mockConversation = {- conversationId: 'child-thread',- title: 'Saved agent child',- subagentThread: {- parentConversationId: 'parent-thread',- },- };-- render(<ChatView />);-- expect(screen.queryByTestId('chat-form')).not.toBeInTheDocument();- expect(screen.getByRole('note')).toHaveTextContent('com_ui_subagent_thread_read_only');- expect(screen.getByTestId('header')).toHaveAttribute('data-read-only', 'true');- });});diff --git a/client/src/components/Conversations/ProjectsSection.tsx b/client/src/components/Conversations/ProjectsSection.tsxindex 108bde61fd..8c7618dfd2 100644--- a/client/src/components/Conversations/ProjectsSection.tsx+++ b/client/src/components/Conversations/ProjectsSection.tsx@@ -41,7 +41,6 @@ import {} from '~/data-provider';import ProjectCreateDialog from '~/components/Projects/ProjectCreateDialog';import ProjectDeleteDialog from '~/components/Projects/ProjectDeleteDialog';-import ProjectEditDialog from '~/components/Projects/ProjectEditDialog';import { useLocalize, useLocalStorage, useNewConvo } from '~/hooks';import { clearMessagesCache, cn, rowActionClasses } from '~/utils';import { Collapse } from '~/components/ui';@@ -188,8 +187,8 @@ const ProjectItem = memo(const menuId = useId();const [expanded, setExpanded] = useState(defaultExpanded);const [isMenuOpen, setIsMenuOpen] = useState(false);- const [isRenameOpen, setIsRenameOpen] = useState(false);const [isDeleteOpen, setIsDeleteOpen] = useState(false);+ const deleteMenuRef = useRef<HTMLButtonElement>(null);const projectChatPath = `/c/${Constants.NEW_CONVO}?projectId=${encodeURIComponent(project._id)}`;/* The whole item, header plus its expanded chats, is the drop target for@@ -272,23 +271,29 @@ const ProjectItem = memo(id: `${menuId}-rename`,label: localize('com_ui_edit_project'),icon: <Pencil className="text-text-secondary size-4" aria-hidden="true" />,- onClick: () => setIsRenameOpen(true),+ onClick: () => {+ navigate(`/projects/${encodeURIComponent(project._id)}?edit=1`);+ toggleNav();+ },},{id: `${menuId}-delete`,label: localize('com_ui_delete'),icon: <Trash2 className="text-text-secondary size-4" aria-hidden="true" />,onClick: () => setIsDeleteOpen(true),+ hideOnClick: false,+ ref: deleteMenuRef,+ render: (props) => <button {...props} />,},],- [localize, menuId, openProject],+ [localize, menuId, navigate, openProject, project._id, toggleNav],);return (- <li className="list-none" ref={projectRowRef}>+ <li className="max-w-full min-w-0 list-none" ref={projectRowRef}><divclassName={cn(- 'group text-text-primary hover:bg-surface-active-alt relative flex h-9 items-center rounded-lg text-sm',+ 'group/project-row text-text-primary hover:bg-surface-active-alt relative flex h-9 max-w-full min-w-0 items-center rounded-lg text-sm',isActive && 'bg-surface-active-alt hover:bg-surface-active-alt',!isActive && isMenuOpen && 'bg-surface-active-alt',isDropOver && canDrop && 'bg-surface-active-alt ring-border-medium ring-1 ring-inset',@@ -300,7 +305,7 @@ const ProjectItem = memo(onClick={() => setExpanded((prev) => !prev)}aria-expanded={expanded}aria-label={project.name}- className="focus-visible:ring-text-primary flex min-w-0 flex-1 items-center gap-2 rounded-lg py-1.5 pr-16 pl-1.5 text-left outline-hidden focus-visible:ring-2 focus-visible:ring-inset"+ className="focus-visible:ring-text-primary flex w-full max-w-full min-w-0 flex-1 items-center gap-2 rounded-lg py-1.5 pr-16 pl-1.5 text-left outline-hidden focus-visible:ring-2 focus-visible:ring-inset"><ChevronRightclassName={cn(@@ -310,7 +315,7 @@ const ProjectItem = memo(aria-hidden="true"/><Folder className="text-text-secondary h-4 w-4 shrink-0" aria-hidden="true" />- <span className="min-w-0 truncate">{project.name}</span>+ <span className="max-w-full min-w-0 truncate wrap-anywhere">{project.name}</span></button><div/* The 4px between the two controls, and from the row's trailing edge,@@ -360,8 +365,12 @@ const ProjectItem = memo(onShowAll={openProject}/></Collapse>- <ProjectEditDialog open={isRenameOpen} onOpenChange={setIsRenameOpen} project={project} />- <ProjectDeleteDialog open={isDeleteOpen} onOpenChange={setIsDeleteOpen} project={project} />+ <ProjectDeleteDialog+ open={isDeleteOpen}+ onOpenChange={setIsDeleteOpen}+ project={project}+ triggerRef={deleteMenuRef}+ /></li>);},diff --git a/client/src/components/Projects/ProjectBadge.tsx b/client/src/components/Projects/ProjectBadge.tsxnew file mode 100644index 0000000000..19d4aece10--- /dev/null+++ b/client/src/components/Projects/ProjectBadge.tsx@@ -0,0 +1,26 @@+import { memo } from 'react';+import { Folder } from 'lucide-react';+import { Link } from 'react-router-dom';+import { useProjectQuery } from '~/data-provider';+import { useLocalize } from '~/hooks';++function ProjectBadge({ projectId }: { projectId: string }) {+ const localize = useLocalize();+ const { data: project } = useProjectQuery(projectId);+ const name = project?.name ?? localize('com_ui_project');++ return (+ <div className="pointer-events-none absolute inset-x-0 top-12 z-5 flex justify-center px-3 md:top-14">+ <Link+ to={`/projects/${encodeURIComponent(projectId)}`}+ className="border-border-light bg-surface-secondary text-text-secondary hover:bg-surface-hover hover:text-text-primary focus-visible:ring-text-primary pointer-events-auto inline-flex max-w-full items-center gap-1.5 rounded-full border px-3 py-1.5 text-xs font-medium transition-colors focus-visible:ring-2 focus-visible:outline-hidden"+ aria-label={localize('com_ui_project_open_workspace', { name })}+ >+ <Folder className="size-3.5 shrink-0" aria-hidden="true" />+ <span className="truncate">{name}</span>+ </Link>+ </div>+ );+}++export default memo(ProjectBadge);diff --git a/client/src/components/Projects/ProjectChatList.tsx b/client/src/components/Projects/ProjectChatList.tsxindex f9d0f7f91b..220a61c70a 100644--- a/client/src/components/Projects/ProjectChatList.tsx+++ b/client/src/components/Projects/ProjectChatList.tsx@@ -10,7 +10,8 @@ import {type ReactNode,} from 'react';import throttle from 'lodash/throttle';-import { Spinner } from '@librechat/client';+import { MessagesSquare } from 'lucide-react';+import { Button, EmptyState, Spinner } from '@librechat/client';import { AutoSizer, CellMeasurer, CellMeasurerCache, List } from 'react-virtualized';import type { TConversation } from 'librechat-data-provider';import type { MeasuredCellParent } from '~/components/Conversations/Conversations';@@ -27,8 +28,7 @@ type ChatSortField = 'updatedAt' | 'createdAt';type FlattenedItem =| { type: 'date'; groupName: string }| { type: 'convo'; convo: TConversation }- | { type: 'loading' }- | { type: 'empty' };+ | { type: 'loading' };interface ProjectChatListProps {conversations: TConversation[];@@ -53,8 +53,8 @@ const MeasuredRow: FC<MeasuredRowProps> = memo(({ cache, rowKey, parent, index, style, children }) => (<CellMeasurer cache={cache} columnIndex={0} key={rowKey} parent={parent} rowIndex={index}>{({ registerChild }) => (- <div ref={registerChild as React.LegacyRef<HTMLDivElement>} style={style}>- {children}+ <div ref={registerChild as React.LegacyRef<HTMLDivElement>} style={style} role="row">+ <div role="gridcell">{children}</div></div>)}</CellMeasurer>@@ -67,7 +67,7 @@ const LoadingRow = memo(() => {const localize = useLocalize();return (<div className="text-text-secondary flex items-center justify-center gap-2 py-4 text-sm">- <Spinner className="text-text-primary" />+ <Spinner className="shrink-0" /><span>{localize('com_ui_loading')}</span></div>);@@ -96,9 +96,11 @@ const ConversationRow = memo(isMenuOpen && 'bg-surface-hover',)}>- <button+ <Buttontype="button"- className="focus-visible:ring-text-primary flex min-w-0 flex-1 items-center gap-3 rounded-2xl px-3.5 py-3 text-left outline-hidden focus-visible:ring-2 focus-visible:ring-inset"+ variant="card"+ size="row"+ className="min-w-0 flex-1"onClick={() => navigateToConvo(conversation)}><span className="flex h-10 w-10 shrink-0 items-center justify-center">@@ -111,12 +113,9 @@ const ConversationRow = memo(</span></span>{isGenerating ? (- <Spinner- className="text-text-primary h-4 w-4 shrink-0"- aria-label={localize('com_ui_generating')}- />+ <Spinner className="h-4 w-4 shrink-0" aria-label={localize('com_ui_generating')} />) : null}- </button>+ </Button>{conversationId ? (<div className="pr-2"><ProjectChatOptions@@ -145,6 +144,7 @@ const ProjectChatList = ({emptyLabel,loadMore,}: ProjectChatListProps) => {+ const localize = useLocalize();const { data: activeJobsData } = useActiveJobs();const activeJobIds = useMemo(() => new Set(activeJobsData?.activeJobIds ?? []),@@ -154,9 +154,6 @@ const ProjectChatList = ({if (isLoading) {return [{ type: 'loading' as const }];}- if (!conversations.length) {- return [{ type: 'empty' as const }];- }const items: FlattenedItem[] = [];groupConversations(conversations, { field: sortBy }).forEach(([groupName, convos]) => {@@ -219,14 +216,6 @@ const ProjectChatList = ({);}- if (item.type === 'empty') {- return (- <MeasuredRow key={key} {...rowProps}>- <div className="text-text-secondary px-3 py-14 text-center text-sm">{emptyLabel}</div>- </MeasuredRow>- );- }-if (item.type === 'date') {return (<MeasuredRow key={key} {...rowProps}>@@ -246,7 +235,7 @@ const ProjectChatList = ({</MeasuredRow>);},- [activeJobIds, cache, emptyLabel, flattenedItems],+ [activeJobIds, cache, flattenedItems],);const getRowHeight = useCallback(@@ -263,11 +252,23 @@ const ProjectChatList = ({[flattenedItems.length, hasNextPage, throttledLoadMore],);+ /** Outside the virtualized list: as a measured row the message sits at the top of a+ * full-height viewport, and the panel is the thing that should center it. */+ if (!isLoading && !conversations.length) {+ return (+ <div className="min-h-[280px] flex-1">+ <EmptyState icon={MessagesSquare} description={emptyLabel} className="h-full" />+ </div>+ );+ }+return (<div className="min-h-[280px] flex-1 overflow-hidden"><AutoSizer>{({ width, height }) => (<List+ aria-label={localize('com_ui_chats')}+ containerRole="rowgroup"ref={listRef}width={width}height={height}diff --git a/client/src/components/Projects/ProjectCreateDialog.tsx b/client/src/components/Projects/ProjectCreateDialog.tsxindex 9c60fb0403..de31ef5d99 100644--- a/client/src/components/Projects/ProjectCreateDialog.tsx+++ b/client/src/components/Projects/ProjectCreateDialog.tsx@@ -22,7 +22,7 @@ import {useToastContext,} from '@librechat/client';import type { TChatProject } from 'librechat-data-provider';-import { useCreateProjectMutation } from '~/data-provider';+import { useCreateProjectMutation, useGetStartupConfig } from '~/data-provider';import { useLocalize } from '~/hooks';type ProjectCreateDialogProps = {@@ -46,6 +46,9 @@ export default function ProjectCreateDialog({const [name, setName] = useState('');const [description, setDescription] = useState('');const createProject = useCreateProjectMutation();+ const { data: startupConfig } = useGetStartupConfig();+ const descriptionLimit =+ startupConfig?.projects?.maxDescriptionLength ?? MAX_CHAT_PROJECT_DESCRIPTION_LENGTH;const { showToast } = useToastContext();useEffect(() => {@@ -102,7 +105,7 @@ export default function ProjectCreateDialog({main={<form id={formId} onSubmit={handleCreate} className="flex flex-col gap-4"><div className="space-y-2">- <Label htmlFor={`${formId}-name`} className="text-sm font-medium text-text-primary">+ <Label htmlFor={`${formId}-name`} className="text-text-primary text-sm font-medium">{localize('com_ui_project_name')}</Label><Input@@ -118,10 +121,10 @@ export default function ProjectCreateDialog({<div className="space-y-2"><LabelhtmlFor={`${formId}-description`}- className="text-sm font-medium text-text-primary"+ className="text-text-primary text-sm font-medium">{localize('com_ui_description')}{' '}- <span className="font-normal text-text-secondary">+ <span className="text-text-secondary font-normal">{localize('com_ui_optional')}</span></Label>@@ -130,7 +133,7 @@ export default function ProjectCreateDialog({value={description}onChange={(event) => setDescription(event.target.value)}rows={3}- maxLength={MAX_CHAT_PROJECT_DESCRIPTION_LENGTH}+ maxLength={descriptionLimit}className="min-h-[4.5rem] bg-transparent"/></div>diff --git a/client/src/components/Projects/ProjectDeleteDialog.tsx b/client/src/components/Projects/ProjectDeleteDialog.tsxindex 9c8ee49aa0..dcbfcedf73 100644--- a/client/src/components/Projects/ProjectDeleteDialog.tsx+++ b/client/src/components/Projects/ProjectDeleteDialog.tsx@@ -10,6 +10,7 @@ import {useToastContext,} from '@librechat/client';import type { TChatProject } from 'librechat-data-provider';+import type { ComponentProps } from 'react';import { useDeleteProjectMutation } from '~/data-provider';import { NotificationSeverity } from '~/common';import { useLocalize } from '~/hooks';@@ -18,12 +19,14 @@ type ProjectDeleteDialogProps = {open: boolean;onOpenChange: (open: boolean) => void;project: TChatProject;+ triggerRef?: ComponentProps<typeof OGDialog>['triggerRef'];};export default function ProjectDeleteDialog({open,onOpenChange,project,+ triggerRef,}: ProjectDeleteDialogProps) {const localize = useLocalize();const navigate = useNavigate();@@ -49,12 +52,12 @@ export default function ProjectDeleteDialog({};return (- <OGDialog open={open} onOpenChange={onOpenChange}>+ <OGDialog open={open} onOpenChange={onOpenChange} triggerRef={triggerRef}><OGDialogContent className="w-11/12 max-w-md" showCloseButton={false}><OGDialogHeader><OGDialogTitle>{localize('com_ui_delete_project')}</OGDialogTitle></OGDialogHeader>- <div className="text-sm text-text-secondary">+ <div className="text-text-secondary text-sm">{localize('com_ui_delete_project_confirm', { name: project.name })}</div><div className="flex justify-end gap-4 pt-4">diff --git a/client/src/components/Projects/ProjectEditDialog.tsx b/client/src/components/Projects/ProjectEditDialog.tsxdeleted file mode 100644index 829749fcdd..0000000000--- a/client/src/components/Projects/ProjectEditDialog.tsx+++ /dev/null@@ -1,138 +0,0 @@-import { useEffect, useId, useRef, useState, type FormEvent } from 'react';-import {- MAX_CHAT_PROJECT_NAME_LENGTH,- MAX_CHAT_PROJECT_DESCRIPTION_LENGTH,-} from 'librechat-data-provider';-import {- Button,- Input,- Label,- OGDialog,- OGDialogTemplate,- Spinner,- Textarea,- useToastContext,-} from '@librechat/client';-import type { TChatProject } from 'librechat-data-provider';-import { useUpdateProjectMutation } from '~/data-provider';-import { NotificationSeverity } from '~/common';-import { useLocalize } from '~/hooks';--type ProjectEditDialogProps = {- open: boolean;- onOpenChange: (open: boolean) => void;- project: TChatProject;-};--export default function ProjectEditDialog({ open, onOpenChange, project }: ProjectEditDialogProps) {- const localize = useLocalize();- const formId = useId();- const inputRef = useRef<HTMLInputElement | null>(null);- const [name, setName] = useState(project.name);- const [description, setDescription] = useState(project.description ?? '');- const [wasOpen, setWasOpen] = useState(open);- const updateProject = useUpdateProjectMutation();- const { showToast } = useToastContext();-- if (open !== wasOpen) {- setWasOpen(open);- if (open) {- setName(project.name);- setDescription(project.description ?? '');- }- }-- useEffect(() => {- if (!open) {- return;- }- const frameId = requestAnimationFrame(() => inputRef.current?.focus());- return () => cancelAnimationFrame(frameId);- }, [open]);-- const trimmedName = name.trim();- const trimmedDescription = description.trim();- const isUnchanged =- trimmedName === project.name && trimmedDescription === (project.description ?? '').trim();-- const handleSubmit = (event: FormEvent<HTMLFormElement>) => {- event.preventDefault();- if (!trimmedName || isUnchanged || updateProject.isLoading) {- return;- }-- updateProject.mutate(- {- projectId: project._id,- name: trimmedName,- description: trimmedDescription,- },- {- onSuccess: () => onOpenChange(false),- onError: () =>- showToast({- message: localize('com_ui_project_rename_error'),- severity: NotificationSeverity.ERROR,- showIcon: true,- }),- },- );- };-- return (- <OGDialog open={open} onOpenChange={onOpenChange}>- <OGDialogTemplate- title={localize('com_ui_edit_project')}- showCloseButton={false}- className="w-11/12 max-w-md"- main={- <form id={formId} onSubmit={handleSubmit} className="flex flex-col gap-4">- <div className="space-y-2">- <Label htmlFor={`${formId}-name`} className="text-sm font-medium text-text-primary">- {localize('com_ui_project_name')}- </Label>- <Input- id={`${formId}-name`}- ref={inputRef}- value={name}- onChange={(event) => setName(event.target.value)}- maxLength={MAX_CHAT_PROJECT_NAME_LENGTH}- className="w-full"- />- </div>- <div className="space-y-2">- <Label- htmlFor={`${formId}-description`}- className="text-sm font-medium text-text-primary"- >- {localize('com_ui_description')}{' '}- <span className="font-normal text-text-secondary">- {localize('com_ui_optional')}- </span>- </Label>- <Textarea- id={`${formId}-description`}- value={description}- onChange={(event) => setDescription(event.target.value)}- rows={3}- maxLength={MAX_CHAT_PROJECT_DESCRIPTION_LENGTH}- className="min-h-[4.5rem] bg-transparent"- />- </div>- </form>- }- buttons={- <Button- type="submit"- form={formId}- variant="submit"- disabled={!trimmedName || isUnchanged || updateProject.isLoading}- className="active:scale-[0.96]"- >- {updateProject.isLoading ? <Spinner className="size-4" /> : localize('com_ui_save')}- </Button>- }- />- </OGDialog>- );-}diff --git a/client/src/components/Projects/ProjectEditor.tsx b/client/src/components/Projects/ProjectEditor.tsxnew file mode 100644index 0000000000..effd120ede--- /dev/null+++ b/client/src/components/Projects/ProjectEditor.tsx@@ -0,0 +1,250 @@+import { useEffect, useRef } from 'react';+import { Folder } from 'lucide-react';+import { useForm } from 'react-hook-form';+import { Button, Input, Label, Spinner, Textarea, useToastContext } from '@librechat/client';+import {+ MAX_CHAT_PROJECT_DESCRIPTION_LENGTH,+ MAX_CHAT_PROJECT_NAME_LENGTH,+} from 'librechat-data-provider';+import type { KeyboardEvent, MutableRefObject, RefObject } from 'react';+import type { TChatProject } from 'librechat-data-provider';+import { useUpdateProjectMutation, useGetStartupConfig } from '~/data-provider';+import { NotificationSeverity } from '~/common';+import { useLocalize } from '~/hooks';+import { cn } from '~/utils';++export type ProjectEditorProps = {+ project: TChatProject;+ onDone: () => void;+ layout?: 'workspace' | 'card';+ inputRef?: RefObject<HTMLInputElement>;+ initialField?: 'name' | 'description';+};++type ProjectEditorForm = {+ name: string;+ description: string;+};++export default function ProjectEditor({+ project,+ onDone,+ layout = 'workspace',+ inputRef,+ initialField = 'name',+}: ProjectEditorProps) {+ const localize = useLocalize();+ const updateProject = useUpdateProjectMutation();+ const { data: startupConfig } = useGetStartupConfig();+ const descriptionLimit =+ startupConfig?.projects?.maxDescriptionLength ?? MAX_CHAT_PROJECT_DESCRIPTION_LENGTH;+ const { showToast } = useToastContext();+ const isSavingRef = useRef(false);+ const nameInputRef = useRef<HTMLInputElement | null>(null);+ const {+ register,+ handleSubmit,+ setFocus,+ formState: { errors },+ } = useForm<ProjectEditorForm>({+ defaultValues: {+ name: project.name,+ description: project.description ?? '',+ },+ });+ const nameRegistration = register('name', {+ validate: (value) => value.trim().length > 0 || localize('com_ui_field_required'),+ maxLength: {+ value: MAX_CHAT_PROJECT_NAME_LENGTH,+ message: localize('com_ui_field_max_length', {+ field: localize('com_ui_project_name'),+ length: MAX_CHAT_PROJECT_NAME_LENGTH,+ }),+ },+ });+ const descriptionRegistration = register('description', {+ maxLength: {+ value: descriptionLimit,+ message: localize('com_ui_field_max_length', {+ field: localize('com_ui_description'),+ length: descriptionLimit,+ }),+ },+ });+ const isBusy = updateProject.isLoading;+ const isWorkspace = layout === 'workspace';+ const nameId = `project-editor-${project._id}-name`;+ const descriptionId = `project-editor-${project._id}-description`;+ const nameErrorId = `${nameId}-error`;+ const descriptionErrorId = `${descriptionId}-error`;++ useEffect(() => {+ const focusField = () => setFocus(initialField);+ /** Sidebar navigation can mount this form before the pane loses `inert`. */+ const inertAncestor = nameInputRef.current?.closest('[inert]');+ if (!inertAncestor) {+ focusField();+ return;+ }++ const observer = new MutationObserver(() => {+ if (nameInputRef.current?.closest('[inert]')) {+ return;+ }+ observer.disconnect();+ focusField();+ });+ observer.observe(inertAncestor, { attributes: true, attributeFilter: ['inert'] });+ return () => observer.disconnect();+ }, [initialField, setFocus]);++ const assignNameRef = (node: HTMLInputElement | null) => {+ nameRegistration.ref(node);+ nameInputRef.current = node;+ if (inputRef) {+ (inputRef as MutableRefObject<HTMLInputElement | null>).current = node;+ }+ };++ const onSubmit = ({ name, description }: ProjectEditorForm) => {+ if (isSavingRef.current || updateProject.isLoading) {+ return;+ }++ const trimmedName = name.trim();+ const trimmedDescription = description.trim();+ if (!trimmedName) {+ return;+ }++ const isUnchanged =+ trimmedName === project.name && trimmedDescription === (project.description ?? '').trim();+ if (isUnchanged) {+ onDone();+ return;+ }++ isSavingRef.current = true;+ updateProject.mutate(+ {+ projectId: project._id,+ name: trimmedName,+ description: trimmedDescription,+ },+ {+ onSuccess: () => {+ isSavingRef.current = false;+ onDone();+ },+ onError: () => {+ isSavingRef.current = false;+ showToast({+ message: localize('com_ui_project_rename_error'),+ severity: NotificationSeverity.ERROR,+ showIcon: true,+ });+ },+ },+ );+ };++ const handleKeyDown = (event: KeyboardEvent<HTMLFormElement>) => {+ if (event.key === 'Escape') {+ event.preventDefault();+ event.stopPropagation();+ if (!isSavingRef.current && !updateProject.isLoading) {+ onDone();+ }+ }+ };++ return (+ <form+ onSubmit={handleSubmit(onSubmit)}+ onKeyDown={handleKeyDown}+ aria-busy={isBusy}+ className={cn('flex w-full min-w-0 flex-col', isWorkspace ? 'gap-4' : 'gap-3')}+ >+ <div+ className={cn(+ 'min-w-0',+ isWorkspace+ ? 'grid grid-cols-[auto_minmax(0,1fr)] items-start gap-x-3 gap-y-3'+ : 'flex flex-col gap-3',+ )}+ >+ <span+ className={cn(+ 'text-text-secondary flex shrink-0 items-center justify-center',+ isWorkspace+ ? 'bg-surface-secondary size-12 rounded-2xl'+ : 'bg-surface-tertiary h-11 w-11 rounded-xl',+ )}+ aria-hidden="true"+ >+ <Folder className={isWorkspace ? 'size-6' : 'size-5'} aria-hidden="true" />+ </span>+ <div className="w-full min-w-0">+ <Label htmlFor={nameId} className="sr-only">+ {localize('com_ui_project_name')}+ </Label>+ <Input+ {...nameRegistration}+ ref={assignNameRef}+ id={nameId}+ required+ readOnly={isBusy}+ maxLength={MAX_CHAT_PROJECT_NAME_LENGTH}+ aria-invalid={errors.name ? 'true' : 'false'}+ aria-describedby={errors.name ? nameErrorId : undefined}+ variant={isWorkspace ? 'title' : 'title-sm'}+ className="w-full max-w-full min-w-0 overflow-hidden wrap-anywhere"+ />+ {errors.name ? (+ <p id={nameErrorId} role="alert" className="text-text-destructive mt-1 text-xs">+ {errors.name.message}+ </p>+ ) : null}+ </div>+ <div className={cn('w-full min-w-0', isWorkspace && 'col-span-2')}>+ <Label htmlFor={descriptionId} className="sr-only">+ {localize('com_ui_description')} {localize('com_ui_optional')}+ </Label>+ <Textarea+ {...descriptionRegistration}+ id={descriptionId}+ rows={3}+ readOnly={isBusy}+ maxLength={descriptionLimit}+ aria-invalid={errors.description ? 'true' : 'false'}+ aria-describedby={errors.description ? descriptionErrorId : undefined}+ variant="transparent"+ className={cn(+ 'w-full max-w-full min-w-0 resize-none overflow-y-auto wrap-anywhere',+ isWorkspace ? 'h-24 max-h-32' : 'h-20 max-h-24',+ )}+ />+ {errors.description ? (+ <p id={descriptionErrorId} role="alert" className="text-text-destructive mt-1 text-xs">+ {errors.description.message}+ </p>+ ) : null}+ </div>+ </div>+ <div className="flex min-w-0 justify-end gap-2">+ <Button type="button" variant="outline" size="sm" onClick={onDone} disabled={isBusy}>+ {localize('com_ui_cancel')}+ </Button>+ <Button+ type="submit"+ variant="submit"+ size="sm"+ disabled={isBusy}+ aria-label={localize('com_ui_save')}+ >+ {isBusy ? <Spinner className="size-4" /> : localize('com_ui_save')}+ </Button>+ </div>+ </form>+ );+}diff --git a/client/src/components/Projects/ProjectInstructionsDialog.spec.tsx b/client/src/components/Projects/ProjectInstructionsDialog.spec.tsxnew file mode 100644index 0000000000..d8b6c86049--- /dev/null+++ b/client/src/components/Projects/ProjectInstructionsDialog.spec.tsx@@ -0,0 +1,206 @@+import { useState } from 'react';+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';+import type { TChatProject } from 'librechat-data-provider';+import type * as ReactModule from 'react';+import type { ReactNode } from 'react';+import ProjectInstructionsDialog from './ProjectInstructionsDialog';++const mockMutate = jest.fn();+const mockInvalidateQueries = jest.fn();+const mockShowToast = jest.fn();++jest.mock('@tanstack/react-query', () => ({+ useQueryClient: () => ({ invalidateQueries: mockInvalidateQueries }),+}));++jest.mock('@librechat/client', () => {+ const React = jest.requireActual<typeof ReactModule>('react');+ return {+ Button: ({ children, ...props }: React.ButtonHTMLAttributes<HTMLButtonElement>) =>+ React.createElement('button', props, children),+ Label: ({ children, ...props }: React.LabelHTMLAttributes<HTMLLabelElement>) =>+ React.createElement('label', props, children),+ Textarea: React.forwardRef<+ HTMLTextAreaElement,+ React.TextareaHTMLAttributes<HTMLTextAreaElement>+ >((props, ref) => React.createElement('textarea', { ...props, ref })),+ Spinner: () => React.createElement('span', { 'data-testid': 'spinner' }),+ TooltipAnchor: ({ render }: { render: ReactNode }) => render,+ OGDialog: ({ open, children }: { open: boolean; children: ReactNode }) =>+ open ? React.createElement(React.Fragment, null, children) : null,+ OGDialogTemplate: ({+ title,+ main,+ buttons,+ showCancelButton = true,+ cancelDisabled = false,+ }: {+ title: ReactNode;+ main: ReactNode;+ buttons: ReactNode;+ showCancelButton?: boolean;+ cancelDisabled?: boolean;+ }) =>+ React.createElement('section', { role: 'dialog' }, [+ React.createElement('h2', { key: 'title' }, title),+ React.createElement('div', { key: 'main' }, main),+ showCancelButton+ ? React.createElement(+ 'button',+ { key: 'cancel', type: 'button', disabled: cancelDisabled },+ 'Cancel',+ )+ : null,+ React.createElement('div', { key: 'buttons' }, buttons),+ ]),+ useToastContext: () => ({ showToast: mockShowToast }),+ };+});++jest.mock('~/data-provider', () => {+ const React = jest.requireActual<typeof ReactModule>('react');+ return {+ useUpdateProjectMutation: () => {+ const [isLoading, setIsLoading] = React.useState(false);+ const mutate = (+ payload: unknown,+ callbacks: {+ onSuccess?: (...args: unknown[]) => void;+ onError?: (...args: unknown[]) => void;+ },+ ) => {+ setIsLoading(true);+ mockMutate(payload, {+ onSuccess: (...args: unknown[]) => {+ setIsLoading(false);+ callbacks.onSuccess?.(...args);+ },+ onError: (...args: unknown[]) => {+ setIsLoading(false);+ callbacks.onError?.(...args);+ },+ });+ };+ return { mutate, isLoading };+ },+ useGetStartupConfig: () => ({ data: undefined }),+ };+});++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string, options?: { name?: string | number }) => {+ const translations: Record<string, string> = {+ com_ui_project_instructions: 'Instructions',+ com_ui_project_instructions_label: 'Workspace instructions',+ com_ui_project_instructions_help: 'Additional context',+ com_ui_project_instructions_error: 'Could not save project instructions',+ com_ui_project_conflict_error: 'Project changed elsewhere',+ com_ui_save: 'Save',+ com_ui_saving: 'Saving',+ com_ui_cancel: 'Cancel',+ };+ return (translations[key] ?? key).replace('{{name}}', String(options?.name ?? ''));+ },+}));++const project = {+ _id: 'project-1',+ name: 'Writing project',+ instructions: 'Use a concise tone.',+ contextRevision: 3,+ conversationCount: 0,+ createdAt: '2026-01-01',+ updatedAt: '2026-01-01',+} as TChatProject;++describe('ProjectInstructionsDialog', () => {+ beforeEach(() => jest.clearAllMocks());++ it('keeps the edited draft after a failed save and closes only after success', async () => {+ function Editor() {+ const [open, setOpen] = useState(true);+ return <ProjectInstructionsDialog open={open} onOpenChange={setOpen} project={project} />;+ }+ mockMutate.mockImplementationOnce((_payload, callbacks) =>+ callbacks.onError(new Error('Save unavailable')),+ );+ render(<Editor />);+ const textarea = screen.getByRole('textbox', { name: 'Workspace instructions' });+ fireEvent.change(textarea, { target: { value: 'Keep this unsaved draft.' } });+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));+ await waitFor(() => expect(mockMutate).toHaveBeenCalledTimes(1));+ expect(screen.getByRole('dialog')).toBeInTheDocument();+ expect(textarea).toHaveValue('Keep this unsaved draft.');++ mockMutate.mockImplementationOnce((_payload, callbacks) => callbacks.onSuccess(project));+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());+ });++ it('sends the project revision and keeps the draft when the save conflicts', async () => {+ const onOpenChange = jest.fn();+ mockMutate.mockImplementationOnce((_payload, callbacks) =>+ callbacks.onError({ response: { status: 409, data: { code: 'CHAT_PROJECT_CONFLICT' } } }),+ );+ render(<ProjectInstructionsDialog open onOpenChange={onOpenChange} project={project} />);+ const textarea = screen.getByRole('textbox', { name: 'Workspace instructions' });+ fireEvent.change(textarea, { target: { value: 'Keep this unsaved draft.' } });+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));++ await waitFor(() => expect(mockShowToast).toHaveBeenCalledTimes(1));+ expect(mockMutate.mock.calls[0][0]).toMatchObject({ contextRevision: 3 });+ expect(mockShowToast).toHaveBeenCalledWith(+ expect.objectContaining({ message: 'Project changed elsewhere' }),+ );+ expect(mockInvalidateQueries).toHaveBeenCalledWith(+ expect.objectContaining({ queryKey: ['project', 'project-1'] }),+ );+ expect(onOpenChange).not.toHaveBeenCalled();+ expect(textarea).toHaveValue('Keep this unsaved draft.');+ });++ it('protects the draft and dismissal controls while a save is pending', async () => {+ let pendingCallbacks: { onSuccess: () => void; onError: (error: unknown) => void } | undefined;+ mockMutate.mockImplementationOnce((_payload, callbacks) => {+ pendingCallbacks = callbacks;+ });++ render(<ProjectInstructionsDialog open onOpenChange={jest.fn()} project={project} />);+ const textarea = screen.getByRole('textbox', { name: 'Workspace instructions' });+ fireEvent.change(textarea, { target: { value: 'Draft A' } });+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));++ await waitFor(() => expect(mockMutate).toHaveBeenCalledTimes(1));+ expect(textarea).toHaveAttribute('readonly');+ expect(screen.getByRole('button', { name: 'Cancel' })).toBeDisabled();++ await act(async () => pendingCallbacks?.onError(new Error('Save unavailable')));+ await waitFor(() => expect(textarea).not.toHaveAttribute('readonly'));+ expect(screen.getByRole('button', { name: 'Cancel' })).not.toBeDisabled();+ expect(textarea).toHaveValue('Draft A');+ });++ it('does not close a newer editing session when an old save completes', async () => {+ let pendingCallbacks: { onSuccess: () => void; onError: (error: unknown) => void } | undefined;+ mockMutate.mockImplementationOnce((_payload, callbacks) => {+ pendingCallbacks = callbacks;+ });++ const onOpenChange = jest.fn();+ const dialog = (open: boolean) => (+ <ProjectInstructionsDialog open={open} onOpenChange={onOpenChange} project={project} />+ );+ const { rerender } = render(dialog(true));+ fireEvent.change(screen.getByRole('textbox', { name: 'Workspace instructions' }), {+ target: { value: 'Draft A' },+ });+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));+ await waitFor(() => expect(mockMutate).toHaveBeenCalledTimes(1));++ rerender(dialog(false));+ rerender(dialog(true));+ await act(async () => pendingCallbacks?.onSuccess());++ expect(onOpenChange).not.toHaveBeenCalled();+ });+});diff --git a/client/src/components/Projects/ProjectInstructionsDialog.tsx b/client/src/components/Projects/ProjectInstructionsDialog.tsxnew file mode 100644index 0000000000..e65cff4a3d--- /dev/null+++ b/client/src/components/Projects/ProjectInstructionsDialog.tsx@@ -0,0 +1,212 @@+import { useEffect, useId, useRef } from 'react';+import { Info } from 'lucide-react';+import { useForm } from 'react-hook-form';+import { useQueryClient } from '@tanstack/react-query';+import { MAX_CHAT_PROJECT_INSTRUCTIONS_LENGTH, QueryKeys } from 'librechat-data-provider';+import {+ Button,+ Label,+ OGDialog,+ OGDialogTemplate,+ Spinner,+ Textarea,+ TooltipAnchor,+ useToastContext,+} from '@librechat/client';+import type { TChatProject } from 'librechat-data-provider';+import type { RefObject } from 'react';+import { useUpdateProjectMutation, useGetStartupConfig } from '~/data-provider';+import { NotificationSeverity } from '~/common';+import { useLocalize } from '~/hooks';++type ProjectInstructionsDialogProps = {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ project: TChatProject;+ triggerRef?: RefObject<HTMLButtonElement | null>;+};++type InstructionsForm = {+ instructions: string;+};++type ConflictError = { response?: { status?: number; data?: { code?: string } } };++const isProjectConflict = (error: unknown): boolean => {+ const { response } = (error ?? {}) as ConflictError;+ return response?.status === 409 && response.data?.code === 'CHAT_PROJECT_CONFLICT';+};++export default function ProjectInstructionsDialog({+ open,+ onOpenChange,+ project,+ triggerRef,+}: ProjectInstructionsDialogProps) {+ const localize = useLocalize();+ const formId = useId();+ const { data: startupConfig } = useGetStartupConfig();+ const instructionsLimit =+ startupConfig?.projects?.maxInstructionsLength ?? MAX_CHAT_PROJECT_INSTRUCTIONS_LENGTH;+ const queryClient = useQueryClient();+ const updateProject = useUpdateProjectMutation();+ const { showToast } = useToastContext();+ const dialogSessionRef = useRef(0);+ const wasOpenRef = useRef(open);+ const keepDraftRef = useRef(false);+ const { register, handleSubmit, reset, watch, setFocus } = useForm<InstructionsForm>({+ defaultValues: { instructions: project.instructions ?? '' },+ });+ const instructions = watch('instructions');+ const isBusy = updateProject.isLoading;+ useEffect(() => {+ if (open && !wasOpenRef.current) {+ dialogSessionRef.current += 1;+ }+ wasOpenRef.current = open;+ if (!open) {+ keepDraftRef.current = false;+ }+ if (open && !keepDraftRef.current) {+ reset({ instructions: project.instructions ?? '' });+ }+ }, [open, project.instructions, reset]);++ const onSubmit = ({ instructions: value }: InstructionsForm) => {+ if (isBusy) {+ return;+ }++ const submittedSession = dialogSessionRef.current;+ updateProject.mutate(+ {+ projectId: project._id,+ instructions: value.trim(),+ contextRevision: project.contextRevision,+ },+ {+ onSuccess: () => {+ if (dialogSessionRef.current === submittedSession) {+ onOpenChange(false);+ }+ },+ onError: (error) => {+ if (isProjectConflict(error)) {+ keepDraftRef.current = true;+ void queryClient.invalidateQueries({+ queryKey: [QueryKeys.project, project._id],+ refetchType: 'all',+ });+ showToast({+ message: localize('com_ui_project_conflict_error'),+ severity: NotificationSeverity.ERROR,+ showIcon: true,+ });+ return;+ }+ showToast({+ message: localize('com_ui_project_instructions_error'),+ severity: NotificationSeverity.ERROR,+ showIcon: true,+ });+ },+ },+ );+ };++ const handleOpenChange = (nextOpen: boolean) => {+ if (!nextOpen && isBusy) {+ return;+ }+ onOpenChange(nextOpen);+ };++ return (+ <OGDialog open={open} onOpenChange={handleOpenChange} triggerRef={triggerRef}>+ <OGDialogTemplate+ title={localize('com_ui_project_instructions')}+ showCloseButton={false}+ cancelDisabled={isBusy}+ className="w-11/12 max-w-3xl"+ onOpenAutoFocus={(event) => {+ event.preventDefault();+ setFocus('instructions');+ }}+ onCloseAutoFocus={(event) => {+ if (triggerRef?.current) {+ event.preventDefault();+ triggerRef.current.focus();+ }+ }}+ onEscapeKeyDown={(event) => {+ if (isBusy) {+ event.preventDefault();+ }+ }}+ onInteractOutside={(event) => {+ if (isBusy) {+ event.preventDefault();+ }+ }}+ main={+ <form+ id={formId}+ onSubmit={handleSubmit(onSubmit)}+ aria-busy={isBusy}+ className="flex flex-col gap-3"+ >+ <div className="space-y-2">+ <div className="flex items-center gap-1">+ <Label htmlFor={`${formId}-instructions`} className="text-sm font-medium">+ {localize('com_ui_project_instructions_label')}+ </Label>+ <TooltipAnchor+ description={localize('com_ui_project_instructions_help')}+ render={+ <Button+ type="button"+ variant="section-action"+ size="icon-xs"+ className="relative after:absolute after:-inset-1.5"+ aria-label={localize('com_ui_project_instructions_info')}+ disabled={isBusy}+ >+ <Info className="size-3.5" aria-hidden="true" />+ </Button>+ }+ />+ </div>+ <Textarea+ id={`${formId}-instructions`}+ rows={18}+ maxLength={instructionsLimit}+ aria-describedby={`${formId}-instructions-help`}+ variant="document"+ className="h-[clamp(12rem,50dvh,32rem)] wrap-anywhere"+ readOnly={isBusy}+ {...register('instructions')}+ />+ <p id={`${formId}-instructions-help`} className="sr-only">+ {localize('com_ui_project_instructions_help')}+ </p>+ <p className="text-text-tertiary text-right text-xs tabular-nums" aria-live="polite">+ {instructions.length}/{instructionsLimit}+ </p>+ </div>+ </form>+ }+ buttons={+ <Button+ type="submit"+ form={formId}+ variant="submit"+ disabled={isBusy}+ aria-label={isBusy ? localize('com_ui_saving') : localize('com_ui_save')}+ >+ {isBusy ? <Spinner className="size-4" aria-hidden="true" /> : localize('com_ui_save')}+ </Button>+ }+ />+ </OGDialog>+ );+}diff --git a/client/src/components/Projects/ProjectResources.spec.tsx b/client/src/components/Projects/ProjectResources.spec.tsxnew file mode 100644index 0000000000..0ce8f4469c--- /dev/null+++ b/client/src/components/Projects/ProjectResources.spec.tsx@@ -0,0 +1,359 @@+import userEvent from '@testing-library/user-event';+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import type { TChatProjectFile, TFile, TFileUpload } from 'librechat-data-provider';+import type * as ClientModule from '@librechat/client';+import type * as ReactModule from 'react';+import type { ReactNode } from 'react';+import ProjectResources from './ProjectResources';++const mockUploadMutateAsync = jest.fn();+const mockCanUseFileSearch = jest.fn(() => true);+const mockAddMutateAsync = jest.fn();+const mockRemoveMutateAsync = jest.fn();+const mockRefetch = jest.fn();+const mockShowToast = jest.fn();++let projectFilesState: TChatProjectFile[] = [];+let mockProjectQueryState = {+ data: projectFilesState as TChatProjectFile[] | undefined,+ isLoading: false,+ isError: false,+ refetch: mockRefetch,+};+let mockAvailableFilesState = {+ data: { pages: [{ files: [] as TFile[], nextCursor: null }] },+ isLoading: false,+ isFetchingNextPage: false,+ hasNextPage: false,+ fetchNextPage: jest.fn(),+ isError: false,+ refetch: mockRefetch,+};++jest.mock('@librechat/client', () => {+ const React = jest.requireActual<typeof ReactModule>('react');+ const actual = jest.requireActual<typeof ClientModule>('@librechat/client');+ return {+ Spinner: () => React.createElement('span', { 'aria-hidden': true }),+ Alert: ({ children, role }: React.HTMLAttributes<HTMLDivElement>) =>+ React.createElement('div', { role }, children),+ Button: actual.Button,+ DropdownPopup: actual.DropdownPopup,+ EmptyState: actual.EmptyState,+ Input: actual.Input,+ FileUpload: React.forwardRef<+ HTMLInputElement,+ { children: ReactNode; handleFileChange: React.ChangeEventHandler<HTMLInputElement> }+ >(({ children, handleFileChange }, ref) =>+ React.createElement(+ React.Fragment,+ null,+ children,+ React.createElement('input', {+ ref,+ type: 'file',+ 'data-testid': 'project-upload-input',+ onChange: handleFileChange,+ }),+ ),+ ),+ OGDialog: ({ open, children }: { open: boolean; children: ReactNode }) =>+ open ? React.createElement(React.Fragment, null, children) : null,+ OGDialogContent: ({ children }: { children: ReactNode }) =>+ React.createElement('div', null, children),+ OGDialogHeader: ({ children }: { children: ReactNode }) =>+ React.createElement('div', null, children),+ OGDialogTitle: ({ children }: { children: ReactNode }) =>+ React.createElement('h2', null, children),+ TooltipAnchor: ({ render }: { render: ReactNode }) => render,+ useToastContext: () => ({ showToast: mockShowToast }),+ };+});++jest.mock('~/data-provider', () => ({+ useProjectFilesQuery: () => mockProjectQueryState,+ useProjectAvailableFilesInfiniteQuery: () => mockAvailableFilesState,+ useUploadFileMutation: () => ({ mutateAsync: mockUploadMutateAsync, isLoading: false }),+ useAddProjectFileMutation: () => ({ mutateAsync: mockAddMutateAsync, isLoading: false }),+ useRemoveProjectFileMutation: () => ({ mutateAsync: mockRemoveMutateAsync, isLoading: false }),+ useGetStartupConfig: () => ({ data: undefined }),+}));++jest.mock('~/hooks', () => ({+ useAgentCapabilities: () => ({ fileSearchEnabled: true }),+ useGetAgentsConfig: () => ({ agentsConfig: { capabilities: ['file_search'] } }),+ useHasAccess: () => mockCanUseFileSearch(),+ useLocalize: () => (key: string, options?: { count?: number; name?: string }) => {+ const translations: Record<string, string> = {+ com_error_files_upload: 'An error occurred while uploading the file.',+ com_error_files_upload_canceled: 'The file upload was canceled.',+ com_ui_project_add_files: 'Add files',+ com_ui_project_files: 'Reference files',+ com_ui_project_files_help: 'Files are searched',+ com_ui_project_files_retrieval_only: 'Retrieval only',+ com_ui_project_upload_file: 'Upload file',+ com_ui_project_choose_file: 'Choose an existing file',+ com_ui_search_files: 'Search files',+ com_ui_project_file_processing: 'Processing',+ com_ui_project_file_failed: 'Upload failed',+ com_ui_project_file_ready: 'Ready',+ com_ui_project_file_unavailable: 'Unavailable',+ com_ui_project_file_attach_error: 'Could not add this file',+ com_ui_project_file_remove_error: 'Could not remove this file',+ com_ui_project_file_limit: 'This project can use up to {{count}} reference files.',+ com_ui_project_file_excess: `Could not add ${options?.count ?? ''} selected file(s)`,+ com_ui_project_files_error: 'Could not load project files',+ com_ui_project_no_files: 'No reference files yet',+ com_ui_project_no_eligible_files: 'No eligible indexed files',+ com_ui_project_remove_file: `Remove ${options?.name ?? ''} from project`,+ com_ui_project_dismiss_upload: `Dismiss ${options?.name ?? ''} upload`,+ com_ui_retry: 'Retry',+ com_ui_loading: 'Loading',+ com_ui_load_more: 'Load more',+ com_ui_no_search_results: 'No results match your search',+ };+ return (translations[key] ?? key).replace('{{count}}', String(options?.count ?? ''));+ },+}));++const project = { _id: 'project-1', fileCount: 0 };+const uploadedFile = {+ file_id: 'canonical-file-id',+ temp_file_id: 'different-temporary-id',+ filename: 'reference.txt',+ bytes: 10,+ embedded: true,+ context: 'message_attachment',+ type: 'text/plain',+} as unknown as TFileUpload;++function renderResources() {+ return render(<ProjectResources project={project} />);+}++describe('ProjectResources', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ projectFilesState = [];+ mockProjectQueryState = {+ data: projectFilesState,+ isLoading: false,+ isError: false,+ refetch: mockRefetch,+ };+ mockAvailableFilesState = {+ data: { pages: [{ files: [], nextCursor: null }] },+ isLoading: false,+ isFetchingNextPage: false,+ hasNextPage: false,+ fetchNextPage: jest.fn(),+ isError: false,+ refetch: mockRefetch,+ };+ mockCanUseFileSearch.mockReturnValue(true);+ mockAddMutateAsync.mockResolvedValue({});+ mockRemoveMutateAsync.mockResolvedValue({});+ });++ it('renders loading, error, and empty states with recovery controls', () => {+ mockProjectQueryState = { ...mockProjectQueryState, isLoading: true };+ renderResources();+ expect(screen.getByRole('status')).toBeInTheDocument();+ cleanup();++ mockProjectQueryState = { ...mockProjectQueryState, isLoading: false, isError: true };+ renderResources();+ expect(screen.getByRole('alert')).toHaveTextContent('Could not load project files');+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(mockRefetch).toHaveBeenCalled();+ cleanup();++ mockProjectQueryState = { ...mockProjectQueryState, isError: false };+ renderResources();+ expect(screen.getByText('No reference files yet')).toBeInTheDocument();+ });++ it('uses the canonical upload identity and exposes pending and failed attempts', async () => {+ let resolveUpload: (file: TFileUpload) => void = () => undefined;+ mockUploadMutateAsync.mockImplementation(+ () => new Promise<TFileUpload>((resolve) => (resolveUpload = resolve)),+ );+ renderResources();+ const input = screen.getByTestId('project-upload-input');+ fireEvent.change(input, { target: { files: [new File(['x'], 'reference.txt')] } });+ expect(screen.getByText('Processing')).toBeInTheDocument();++ resolveUpload(uploadedFile);+ await waitFor(() =>+ expect(mockAddMutateAsync).toHaveBeenCalledWith({+ projectId: 'project-1',+ file_id: 'canonical-file-id',+ }),+ );+ await waitFor(() => expect(screen.queryByText('Processing')).not.toBeInTheDocument());++ mockUploadMutateAsync.mockRejectedValueOnce({+ message: 'unsafe internal upload detail',+ response: { data: { message: 'Images are not supported for File Search.' } },+ });+ fireEvent.change(input, { target: { files: [new File(['y'], 'failed.txt')] } });+ await waitFor(() =>+ expect(screen.getByText('Images are not supported for File Search.')).toBeInTheDocument(),+ );+ expect(screen.queryByText('unsafe internal upload detail')).not.toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Dismiss failed.txt upload' })).toBeInTheDocument();+ });+ it('reserves remaining capacity across overlapping multi-file selections', async () => {+ let finishFirstUpload!: (file: TFileUpload) => void;+ mockProjectQueryState = { ...mockProjectQueryState, data: undefined, isLoading: true };+ mockUploadMutateAsync+ .mockImplementationOnce(+ () => new Promise<TFileUpload>((resolve) => (finishFirstUpload = resolve)),+ )+ .mockResolvedValueOnce({ ...uploadedFile, file_id: 'second-canonical-id' });+ render(<ProjectResources project={{ ...project, fileCount: 48 }} />);+ const input = screen.getByTestId('project-upload-input');+ fireEvent.change(input, {+ target: {+ files: [+ new File(['a'], 'first.txt'),+ new File(['b'], 'second.txt'),+ new File(['c'], 'excess.txt'),+ ],+ },+ });+ fireEvent.change(input, { target: { files: [new File(['d'], 'another-excess.txt')] } });+ expect(mockUploadMutateAsync).toHaveBeenCalledTimes(1);+ expect(mockShowToast).toHaveBeenCalledTimes(2);+ expect(mockShowToast).toHaveBeenLastCalledWith(+ expect.objectContaining({ message: 'Could not add 1 selected file(s)' }),+ );+ finishFirstUpload(uploadedFile);+ await waitFor(() => expect(mockAddMutateAsync).toHaveBeenCalledTimes(2));+ expect(mockUploadMutateAsync).toHaveBeenCalledTimes(2);+ expect(mockAddMutateAsync.mock.calls.map(([payload]) => payload.file_id)).toEqual([+ uploadedFile.file_id,+ 'second-canonical-id',+ ]);+ });++ it('retries a failed association without uploading another binary', async () => {+ mockUploadMutateAsync.mockResolvedValue(uploadedFile);+ mockAddMutateAsync.mockRejectedValueOnce({+ message: 'unsafe association detail',+ response: { status: 409, data: { error: 'Project file limit reached' } },+ });+ renderResources();+ fireEvent.change(screen.getByTestId('project-upload-input'), {+ target: { files: [new File(['x'], 'reference.txt')] },+ });+ expect(await screen.findByRole('alert')).toHaveTextContent(+ 'This project can use up to 50 reference files.',+ );+ expect(screen.queryByText('Project file limit reached')).not.toBeInTheDocument();+ expect(screen.queryByText('unsafe association detail')).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ await waitFor(() => expect(screen.queryByText('Upload failed')).not.toBeInTheDocument());+ await waitFor(() => expect(screen.queryByText('Processing')).not.toBeInTheDocument());+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ expect(mockUploadMutateAsync).toHaveBeenCalledTimes(1);+ expect(mockAddMutateAsync).toHaveBeenLastCalledWith({+ projectId: 'project-1',+ file_id: 'canonical-file-id',+ });+ });++ it('lists server-filtered files and preserves unit-bearing file sizes', async () => {+ mockProjectQueryState = {+ ...mockProjectQueryState,+ data: [+ { file_id: 'attached-id', filename: 'attached.txt', availability: 'ready' },+ { file_id: 'gone-id', availability: 'unavailable' },+ ],+ };+ mockAvailableFilesState = {+ ...mockAvailableFilesState,+ data: {+ pages: [+ {+ files: [+ { ...uploadedFile, file_id: 'ready-id', filename: 'ready.txt', bytes: 12800 },+ ] as TFile[],+ nextCursor: null,+ },+ ],+ },+ };+ renderResources();+ expect(screen.getByText('Unavailable')).toBeInTheDocument();+ const user = userEvent.setup();+ await user.click(screen.getByRole('button', { name: 'Add files' }));+ await user.click(screen.getByRole('menuitem', { name: 'Choose an existing file' }));+ expect(await screen.findByRole('button', { name: /ready.txt/ })).toHaveTextContent('12.5 KB');+ });++ it('separates an empty file history from a search that matches nothing', async () => {+ renderResources();+ const user = userEvent.setup();+ await user.click(screen.getByRole('button', { name: 'Add files' }));+ await user.click(screen.getByRole('menuitem', { name: 'Choose an existing file' }));+ expect(await screen.findByText('No eligible indexed files')).toBeInTheDocument();++ await user.type(screen.getByRole('textbox', { name: 'Search files' }), 'invoice');+ expect(await screen.findByText('No results match your search')).toBeInTheDocument();+ expect(screen.queryByText('No eligible indexed files')).not.toBeInTheDocument();+ });++ it('names the file limit when attaching an existing file to a full project', async () => {+ mockAddMutateAsync.mockRejectedValueOnce({+ message: 'unsafe association detail',+ response: { status: 409, data: { error: 'Project file limit reached' } },+ });+ mockAvailableFilesState = {+ ...mockAvailableFilesState,+ data: {+ pages: [+ {+ files: [{ ...uploadedFile, file_id: 'ready-id', filename: 'ready.txt' }] as TFile[],+ nextCursor: null,+ },+ ],+ },+ };+ renderResources();+ const user = userEvent.setup();+ await user.click(screen.getByRole('button', { name: 'Add files' }));+ await user.click(screen.getByRole('menuitem', { name: 'Choose an existing file' }));+ await user.click(await screen.findByRole('button', { name: /ready.txt/ }));+ await waitFor(() =>+ expect(mockShowToast).toHaveBeenLastCalledWith(+ expect.objectContaining({ message: 'This project can use up to 50 reference files.' }),+ ),+ );+ });++ it('keeps eligible existing files available when device upload is denied', async () => {+ mockCanUseFileSearch.mockReturnValue(false);+ mockAvailableFilesState = {+ ...mockAvailableFilesState,+ data: {+ pages: [+ {+ files: [{ ...uploadedFile, file_id: 'ready-id', filename: 'ready.txt' }] as TFile[],+ nextCursor: null,+ },+ ],+ },+ };+ renderResources();+ const user = userEvent.setup();+ await user.click(screen.getByRole('button', { name: 'Add files' }));+ expect(screen.queryByRole('menuitem', { name: 'Upload file' })).not.toBeInTheDocument();+ await user.click(screen.getByRole('menuitem', { name: 'Choose an existing file' }));+ await user.click(await screen.findByRole('button', { name: /ready.txt/ }));+ expect(mockAddMutateAsync).toHaveBeenCalledWith({+ projectId: 'project-1',+ file_id: 'ready-id',+ });+ });+});diff --git a/client/src/components/Projects/ProjectResources.tsx b/client/src/components/Projects/ProjectResources.tsxnew file mode 100644index 0000000000..10ff50cf0b--- /dev/null+++ b/client/src/components/Projects/ProjectResources.tsx@@ -0,0 +1,640 @@+import { useDeferredValue, useEffect, useId, useMemo, useRef, useState } from 'react';+import { v4 } from 'uuid';+import * as Ariakit from '@ariakit/react';+import {+ ChevronDown,+ FilePlus2,+ Files,+ Info,+ Link2,+ Loader2,+ Paperclip,+ Plus,+ Trash2,+ Upload,+ X,+} from 'lucide-react';+import {+ defaultAgentCapabilities,+ EToolResources,+ FileContext,+ MAX_CHAT_PROJECT_FILES,+ PermissionTypes,+ Permissions,+} from 'librechat-data-provider';+import {+ Alert,+ Button,+ DropdownPopup,+ EmptyState,+ FileUpload,+ Input,+ OGDialog,+ OGDialogContent,+ OGDialogHeader,+ OGDialogTitle,+ Spinner,+ TooltipAnchor,+ useToastContext,+} from '@librechat/client';+import type { TChatProjectFile, TError, TFile, TFileUpload } from 'librechat-data-provider';+import {+ useAddProjectFileMutation,+ useGetStartupConfig,+ useProjectAvailableFilesInfiniteQuery,+ useProjectFilesQuery,+ useRemoveProjectFileMutation,+ useUploadFileMutation,+} from '~/data-provider';+import { useAgentCapabilities, useGetAgentsConfig, useHasAccess, useLocalize } from '~/hooks';+import { NotificationSeverity, type LocalizeFunction } from '~/common';+import { formatFileSize } from '~/utils';+type ProjectResourcesProps = {+ project: { _id: string; fileCount?: number };+};++type UploadState = {+ id: string;+ filename: string;+ file: File;+ fileId?: string;+ errorMessage?: string;+ status: 'processing' | 'failed';+};++const getUploadErrorMessage = (error: unknown, localize: LocalizeFunction): string => {+ const uploadError = error as TError | undefined;+ if (uploadError?.code === 'ERR_CANCELED') {+ return localize('com_error_files_upload_canceled');+ }+ const responseData = uploadError?.response?.data;+ if (typeof responseData?.message === 'string' && responseData.message.trim().length > 0) {+ return responseData.message;+ }+ return localize('com_error_files_upload');+};++/** Attaching answers 409 only when the project is full; every other failure reads the same. */+const getAssociationErrorMessage = (+ error: unknown,+ localize: LocalizeFunction,+ fileLimit: number,+): string =>+ (error as TError | undefined)?.response?.status === 409+ ? localize('com_ui_project_file_limit', { count: fileLimit })+ : localize('com_ui_project_file_attach_error');+function statusLabel(localize: LocalizeFunction, availability: TChatProjectFile['availability']) {+ return availability === 'ready'+ ? localize('com_ui_project_file_ready')+ : localize('com_ui_project_file_unavailable');+}++const isEligibleFile = (file: TFile) =>+ file.embedded === true &&+ file.context === FileContext.message_attachment &&+ (!file.expiredAt || new Date(file.expiredAt).getTime() > Date.now());+export default function ProjectResources({ project }: ProjectResourcesProps) {+ const localize = useLocalize();+ const { agentsConfig } = useGetAgentsConfig();+ const { fileSearchEnabled } = useAgentCapabilities(+ agentsConfig?.capabilities ?? defaultAgentCapabilities,+ );+ const { data: startupConfig } = useGetStartupConfig();+ const projectFileLimit = startupConfig?.projects?.maxFiles ?? MAX_CHAT_PROJECT_FILES;+ const canUseFileSearch = useHasAccess({+ permissionType: PermissionTypes.FILE_SEARCH,+ permission: Permissions.USE,+ });+ const canUploadFromDevice = fileSearchEnabled && canUseFileSearch;+ const { showToast } = useToastContext();+ const inputRef = useRef<HTMLInputElement>(null);+ const pickerMenuRef = useRef<HTMLButtonElement>(null);+ const fileMenuId = useId();+ const [isFileMenuOpen, setIsFileMenuOpen] = useState(false);+ const [isPickerOpen, setIsPickerOpen] = useState(false);+ const [pickerSearch, setPickerSearch] = useState('');+ const deferredPickerSearch = useDeferredValue(pickerSearch);+ const [uploading, setUploading] = useState<UploadState[]>([]);+ const pendingUploadIdsRef = useRef(new Set<string>());+ const optimisticAttachedIdsRef = useRef(new Set<string>());+ const [optimisticAttachedIds, setOptimisticAttachedIds] = useState<string[]>([]);+ const { data: projectFiles, isLoading, isError, refetch } = useProjectFilesQuery(project._id);+ const listedCount = projectFiles?.length;+ const [tracked, setTracked] = useState({ projectId: project._id, count: listedCount });+ const [announcement, setAnnouncement] = useState('');+ if (tracked.projectId !== project._id || tracked.count !== listedCount) {+ const isSameProject = tracked.projectId === project._id;+ const previous = tracked.count;+ setTracked({ projectId: project._id, count: listedCount });+ if (!isSameProject || previous == null || listedCount == null) {+ setAnnouncement('');+ } else {+ setAnnouncement(+ localize(+ listedCount > previous ? 'com_ui_project_file_added' : 'com_ui_project_file_removed',+ ),+ );+ }+ }+ const availableFilesQuery = useProjectAvailableFilesInfiniteQuery(+ project._id,+ { search: deferredPickerSearch || undefined, limit: 20 },+ { enabled: isPickerOpen },+ );+ const {+ data: availableFilesData,+ isLoading: isFilesLoading,+ isFetchingNextPage,+ isError: isFilesError,+ hasNextPage,+ fetchNextPage,+ refetch: refetchFiles,+ } = availableFilesQuery;+ const uploadFile = useUploadFileMutation();+ const addFile = useAddProjectFileMutation();+ const removeFile = useRemoveProjectFileMutation();+ const attachedIds = useMemo(+ () => new Set((projectFiles ?? []).map((file) => file.file_id)),+ [projectFiles],+ );+ const availableFiles = useMemo(+ () => availableFilesData?.pages.flatMap((page) => page.files) ?? [],+ [availableFilesData?.pages],+ );+ const fileCount = projectFiles?.length ?? project.fileCount ?? 0;+ const getEffectiveFileCount = () => {+ let count = fileCount + pendingUploadIdsRef.current.size;+ for (const fileId of optimisticAttachedIdsRef.current) {+ if (!attachedIds.has(fileId)) {+ count++;+ }+ }+ return count;+ };+ const hasFileCapacity = getEffectiveFileCount() < projectFileLimit;++ useEffect(() => {+ const remaining = optimisticAttachedIds.filter((fileId) => !attachedIds.has(fileId));+ if (remaining.length !== optimisticAttachedIds.length) {+ const remainingSet = new Set(remaining);+ optimisticAttachedIdsRef.current = remainingSet;+ setOptimisticAttachedIds(remaining);+ }+ }, [attachedIds, optimisticAttachedIds]);++ useEffect(() => {+ if (+ isPickerOpen &&+ !isFilesLoading &&+ !isFilesError &&+ availableFiles.length === 0 &&+ hasNextPage &&+ !isFetchingNextPage+ ) {+ void fetchNextPage();+ }+ }, [+ availableFiles.length,+ fetchNextPage,+ hasNextPage,+ isFilesError,+ isFilesLoading,+ isFetchingNextPage,+ isPickerOpen,+ ]);+ useEffect(() => {+ setPickerSearch('');+ }, [project._id]);++ const addExistingFile = async (fileId: string) => {+ try {+ await addFile.mutateAsync({ projectId: project._id, file_id: fileId });+ setIsPickerOpen(false);+ } catch (error: unknown) {+ showToast({+ message: getAssociationErrorMessage(error, localize, projectFileLimit),+ severity: NotificationSeverity.ERROR,+ showIcon: true,+ });+ }+ };++ const runUpload = async (item: UploadState) => {+ let uploaded = false;+ try {+ let fileId = item.fileId;+ if (!fileId) {+ const formData = new FormData();+ formData.append('file', item.file);+ formData.append('file_id', item.id);+ formData.append('endpoint', 'agents');+ formData.append('message_file', 'true');+ formData.append('tool_resource', EToolResources.file_search);+ const uploaded = (await uploadFile.mutateAsync(formData)) as TFileUpload;+ if (!uploaded.file_id || !isEligibleFile(uploaded)) {+ throw new Error('Uploaded file is not eligible for project search');+ }+ fileId = uploaded.file_id;+ setUploading((current) =>+ current.map((candidate) =>+ candidate.id === item.id ? { ...candidate, fileId } : candidate,+ ),+ );+ }+ uploaded = true;+ await addFile.mutateAsync({ projectId: project._id, file_id: fileId });+ pendingUploadIdsRef.current.delete(item.id);+ optimisticAttachedIdsRef.current.add(fileId);+ setOptimisticAttachedIds(Array.from(optimisticAttachedIdsRef.current));+ setUploading((current) => current.filter((candidate) => candidate.id !== item.id));+ } catch (error: unknown) {+ pendingUploadIdsRef.current.delete(item.id);+ const errorMessage = uploaded+ ? getAssociationErrorMessage(error, localize, projectFileLimit)+ : getUploadErrorMessage(error, localize);+ setUploading((current) =>+ current.map((candidate) =>+ candidate.id === item.id ? { ...candidate, errorMessage, status: 'failed' } : candidate,+ ),+ );+ }+ };++ const processUploads = async (items: UploadState[]) => {+ for (const item of items) {+ await runUpload(item);+ }+ };++ const handleUploadChange = (event: React.ChangeEvent<HTMLInputElement>) => {+ const selected = Array.from(event.target.files ?? []);+ event.target.value = '';+ if (!selected.length || !canUploadFromDevice) {+ return;+ }+ const availableCapacity = Math.max(0, projectFileLimit - getEffectiveFileCount());+ const accepted = selected.slice(0, availableCapacity).map((file) => ({+ id: v4(),+ filename: file.name,+ file,+ status: 'processing' as const,+ }));+ accepted.forEach((item) => pendingUploadIdsRef.current.add(item.id));+ if (accepted.length) {+ setUploading((current) => [...current, ...accepted]);+ void processUploads(accepted);+ }+ if (selected.length > accepted.length) {+ showToast({+ message: localize('com_ui_project_file_excess', {+ count: selected.length - accepted.length,+ }),+ severity: NotificationSeverity.WARNING,+ showIcon: true,+ });+ }+ };++ const remove = async (fileId: string) => {+ try {+ await removeFile.mutateAsync({ projectId: project._id, file_id: fileId });+ } catch {+ showToast({+ message: localize('com_ui_project_file_remove_error'),+ severity: NotificationSeverity.ERROR,+ showIcon: true,+ });+ }+ };++ const retryUpload = (item: UploadState) => {+ if (pendingUploadIdsRef.current.has(item.id) || (!item.fileId && !canUploadFromDevice)) {+ return;+ }+ if (getEffectiveFileCount() >= projectFileLimit) {+ showToast({+ message: localize('com_ui_project_file_excess', { count: 1 }),+ severity: NotificationSeverity.WARNING,+ showIcon: true,+ });+ return;+ }+ pendingUploadIdsRef.current.add(item.id);+ setUploading((current) =>+ current.map((candidate) =>+ candidate.id === item.id+ ? { ...candidate, errorMessage: undefined, status: 'processing' }+ : candidate,+ ),+ );+ void runUpload({ ...item, errorMessage: undefined, status: 'processing' });+ };++ const dismissUpload = (id: string) => {+ pendingUploadIdsRef.current.delete(id);+ setUploading((current) => current.filter((item) => item.id !== id));+ };++ return (+ <section+ className="border-border-light bg-surface-secondary flex h-full min-h-0 min-w-0 flex-col rounded-2xl border p-4 sm:p-5"+ aria-labelledby="project-resources-heading"+ >+ <div className="mb-3 flex items-center justify-between gap-2">+ <div className="flex min-w-0 items-center gap-1">+ <h2 id="project-resources-heading" className="text-text-primary text-sm font-semibold">+ {localize('com_ui_project_files')}+ </h2>+ <TooltipAnchor+ description={`${localize('com_ui_project_files_help')} ${localize('com_ui_project_files_retrieval_only')}`}+ render={+ <Button+ type="button"+ variant="section-action"+ size="icon-xs"+ className="relative shrink-0 after:absolute after:-inset-1.5"+ aria-label={localize('com_ui_project_files_info')}+ >+ <Info className="size-3.5" aria-hidden="true" />+ </Button>+ }+ />+ </div>+ <FileUpload ref={inputRef} handleFileChange={handleUploadChange}>+ <DropdownPopup+ portal={true}+ focusLoop={true}+ unmountOnHide={true}+ menuId={fileMenuId}+ isOpen={isFileMenuOpen}+ setIsOpen={setIsFileMenuOpen}+ trigger={+ <Ariakit.MenuButton+ disabled={!hasFileCapacity || uploadFile.isLoading || addFile.isLoading}+ className="aria-expanded:bg-surface-hover"+ render={<Button type="button" variant="outline" size="sm" />}+ >+ <Plus className="size-4" aria-hidden="true" />+ {localize('com_ui_project_add_files')}+ <ChevronDown className="size-3.5" aria-hidden="true" />+ </Ariakit.MenuButton>+ }+ items={[+ ...(canUploadFromDevice+ ? [+ {+ label: localize('com_ui_project_upload_file'),+ icon: <Upload className="text-text-secondary size-4" aria-hidden="true" />,+ onClick: () => inputRef.current?.click(),+ },+ ]+ : []),+ {+ label: localize('com_ui_project_choose_file'),+ icon: <Link2 className="text-text-secondary size-4" aria-hidden="true" />,+ onClick: () => setIsPickerOpen(true),+ hideOnClick: false,+ ref: pickerMenuRef,+ render: (props) => <button {...props} />,+ },+ ]}+ />+ </FileUpload>+ </div>++ {!hasFileCapacity && (+ <p className="text-text-secondary mb-3 text-xs" role="note">+ {localize('com_ui_project_file_limit', { count: projectFileLimit })}+ </p>+ )}+ {isError && (+ <Alert+ variant="error"+ icon={false}+ role="alert"+ className="flex items-center justify-between"+ >+ <span>{localize('com_ui_project_files_error')}</span>+ <Button type="button" variant="outline" size="sm" onClick={() => refetch()}>+ {localize('com_ui_retry')}+ </Button>+ </Alert>+ )}+ {!isError && isLoading && (+ <div+ className="border-border-light bg-surface-secondary text-text-secondary flex min-h-16 items-center justify-center rounded-xl border"+ role="status"+ >+ <Spinner className="size-4" />+ <span className="sr-only">{localize('com_ui_loading')}</span>+ </div>+ )}+ {!isError && !isLoading && (+ <>+ <div className="sr-only" role="status" aria-live="polite">+ {announcement}+ </div>+ <div+ className="min-h-0 flex-1 space-y-2 overflow-y-auto"+ role="list"+ aria-label={localize('com_ui_project_files')}+ >+ {uploading.map((item) => (+ <div+ key={item.id}+ role="listitem"+ aria-describedby={item.errorMessage ? `${item.id}-error` : undefined}+ className="border-border-light bg-surface-secondary flex flex-wrap items-center gap-3 rounded-xl border px-3.5 py-3"+ >+ {item.status === 'processing' ? (+ <Loader2+ className="text-text-secondary size-4 shrink-0 animate-spin"+ aria-hidden="true"+ />+ ) : (+ <FilePlus2 className="text-text-destructive size-4 shrink-0" aria-hidden="true" />+ )}+ <span className="text-text-primary min-w-0 flex-1 truncate text-sm">+ {item.filename}+ </span>+ <span className="text-text-secondary text-xs">+ {item.status === 'processing'+ ? localize('com_ui_project_file_processing')+ : localize('com_ui_project_file_failed')}+ </span>+ {item.errorMessage && (+ <p+ id={`${item.id}-error`}+ role="alert"+ className="text-text-destructive basis-full text-xs"+ >+ {item.errorMessage}+ </p>+ )}+ {item.status === 'failed' && (+ <>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ disabled={!item.fileId && !canUploadFromDevice}+ onClick={() => retryUpload(item)}+ >+ {localize('com_ui_retry')}+ </Button>+ <Button+ type="button"+ variant="ghost"+ size="icon"+ className="size-8 shrink-0"+ aria-label={localize('com_ui_project_dismiss_upload', {+ name: item.filename,+ })}+ onClick={() => dismissUpload(item.id)}+ >+ <X className="size-4" aria-hidden="true" />+ </Button>+ </>+ )}+ </div>+ ))}+ {projectFiles?.map((file) => (+ <div+ key={file.file_id}+ role="listitem"+ className="border-border-light bg-surface-secondary flex items-center gap-3 rounded-xl border px-3.5 py-3"+ >+ <Paperclip className="text-text-secondary size-4 shrink-0" aria-hidden="true" />+ <TooltipAnchor+ description={file.filename ?? file.file_id}+ render={+ <span className="text-text-primary min-w-0 flex-1 truncate text-sm">+ {file.filename ?? file.file_id}+ </span>+ }+ />+ <span+ className={+ file.availability === 'ready'+ ? 'text-text-secondary text-xs'+ : 'text-text-destructive text-xs'+ }+ >+ {statusLabel(localize, file.availability)}+ </span>+ <Button+ type="button"+ variant="ghost"+ size="icon"+ className="size-8 shrink-0"+ aria-label={localize('com_ui_project_remove_file', {+ name: file.filename ?? file.file_id,+ })}+ onClick={() => void remove(file.file_id)}+ disabled={removeFile.isLoading}+ >+ <Trash2 className="size-4" aria-hidden="true" />+ </Button>+ </div>+ ))}+ {!uploading.length && !projectFiles?.length && (+ <EmptyState+ icon={Files}+ description={localize('com_ui_project_no_files')}+ className="h-full"+ />+ )}+ </div>+ </>+ )}++ <OGDialog open={isPickerOpen} onOpenChange={setIsPickerOpen} triggerRef={pickerMenuRef}>+ <OGDialogContent className="w-11/12 max-w-lg" showCloseButton={true}>+ <OGDialogHeader>+ <OGDialogTitle>{localize('com_ui_project_choose_file')}</OGDialogTitle>+ </OGDialogHeader>+ <label className="sr-only" htmlFor="project-file-search">+ {localize('com_ui_search_files')}+ </label>+ <Input+ id="project-file-search"+ value={pickerSearch}+ onChange={(event) => setPickerSearch(event.target.value)}+ placeholder={localize('com_ui_search_files')}+ aria-label={localize('com_ui_search_files')}+ />+ <div+ className="mt-3 max-h-80 space-y-2 overflow-y-auto"+ role="region"+ aria-live="polite"+ aria-label={localize('com_ui_project_choose_file')}+ >+ {(isFilesLoading || isFetchingNextPage) && (+ <div role="status" className="text-text-secondary flex justify-center py-6">+ <Spinner className="size-4" />+ <span className="sr-only">{localize('com_ui_loading')}</span>+ </div>+ )}+ {isFilesError && (+ <Alert variant="error" role="alert">+ {localize('com_ui_project_files_error')}+ <Button type="button" variant="outline" size="sm" onClick={() => refetchFiles()}>+ {localize('com_ui_retry')}+ </Button>+ </Alert>+ )}+ {!isFilesLoading &&+ !isFilesError &&+ !isFetchingNextPage &&+ !availableFiles.length &&+ !hasNextPage && (+ <p className="text-text-secondary py-6 text-center text-sm">+ {deferredPickerSearch+ ? localize('com_ui_no_search_results')+ : localize('com_ui_project_no_eligible_files')}+ </p>+ )}+ {!isFilesLoading && !isFilesError && availableFiles.length > 0 && (+ <ul className="space-y-2">+ {availableFiles.map((file) => (+ <li key={file.file_id}>+ <Button+ type="button"+ variant="outline"+ size="row"+ className="w-full"+ onClick={() => void addExistingFile(file.file_id)}+ disabled={addFile.isLoading || !hasFileCapacity}+ >+ <Paperclip+ className="text-text-secondary size-4 shrink-0"+ aria-hidden="true"+ />+ <span className="text-text-primary min-w-0 flex-1 truncate text-sm">+ {file.filename}+ </span>+ <span className="text-text-secondary shrink-0 text-xs">+ {formatFileSize(file.bytes)}+ </span>+ </Button>+ </li>+ ))}+ </ul>+ )}+ {!isFilesLoading && !isFilesError && hasNextPage && (+ <Button+ type="button"+ variant="outline"+ className="w-full"+ onClick={() => void fetchNextPage()}+ disabled={isFetchingNextPage}+ >+ {isFetchingNextPage ? localize('com_ui_loading') : localize('com_ui_load_more')}+ </Button>+ )}+ </div>+ </OGDialogContent>+ </OGDialog>+ </section>+ );+}diff --git a/client/src/components/Projects/ProjectWorkspace.tsx b/client/src/components/Projects/ProjectWorkspace.tsxindex ca8c668d88..7deb0943da 100644--- a/client/src/components/Projects/ProjectWorkspace.tsx+++ b/client/src/components/Projects/ProjectWorkspace.tsx@@ -1,55 +1,135 @@-import { useCallback, useId, useMemo, useState } from 'react';+import { useCallback, useId, useMemo, useRef, useState } from 'react';import { useRecoilValue } from 'recoil';import * as Ariakit from '@ariakit/react';import { useQueryClient } from '@tanstack/react-query';-import { useNavigate, useParams } from 'react-router-dom';+import { useDefaultLayout } from 'react-resizable-panels';import { Constants, QueryKeys } from 'librechat-data-provider';-import { ArrowLeft, ArrowUpDown, Check, Folder, Pencil, Plus, Trash2 } from 'lucide-react';-import { Button, Spinner, DropdownPopup, TooltipAnchor, useMediaQuery } from '@librechat/client';+import { useNavigate, useParams, useSearchParams } from 'react-router-dom';+import {+ ArrowLeft,+ ArrowUpDown,+ Check,+ Folder,+ Info,+ MoreHorizontal,+ NotebookPen,+ Pencil,+ Plus,+ Trash2,+} from 'lucide-react';+import {+ Button,+ DropdownPopup,+ EmptyState,+ ResizableHandleAlt,+ ResizablePanel,+ ResizablePanelGroup,+ Spinner,+ TooltipAnchor,+ useMediaQuery,+} from '@librechat/client';import type { ConversationListResponse } from 'librechat-data-provider';-import type { MenuItemProps, RenderProp } from '~/common';-import { useConversationsInfiniteQuery, useProjectQuery } from '~/data-provider';+import {+ useConversationsInfiniteQuery,+ useGetStartupConfig,+ useProjectQuery,+} from '~/data-provider';+import ProjectInstructionsDialog from './ProjectInstructionsDialog';+import { useElementSize, useLocalize, useNewConvo } from '~/hooks';import OpenSidebar from '~/components/Chat/Menus/OpenSidebar';import ProjectDeleteDialog from './ProjectDeleteDialog';-import ProjectEditDialog from './ProjectEditDialog';-import { useLocalize, useNewConvo } from '~/hooks';-import { cn, clearMessagesCache } from '~/utils';+import ProjectResources from './ProjectResources';import ProjectChatList from './ProjectChatList';+import { clearMessagesCache } from '~/utils';+import ProjectEditor from './ProjectEditor';import store from '~/store';type ChatSortField = 'updatedAt' | 'createdAt';-function renderSortMenuItem(label: string, isSelected: boolean): RenderProp {- return function SortMenuItem({ className, ...props }) {- return (- <div {...props} className={cn(className, 'justify-between gap-5')}>- <span className="truncate">{label}</span>- {isSelected ? (- <Check className="text-text-primary h-4 w-4 shrink-0" aria-hidden="true" />- ) : (- <span className="h-4 w-4 shrink-0" aria-hidden="true" />- )}- </div>- );- };-}+const WORKSPACE_PANEL_IDS = ['project-details', 'project-chats'];+const DETAILS_PANEL_IDS_WITH_FILES = ['project-instructions', 'project-files'];+const DETAILS_PANEL_IDS = ['project-instructions'];++/** Both separators grab from a band this wide, and the junction that moves all three+ * panels is where the two bands cross: at the library's 10px default the crossing is+ * only ~4.5px of aim, so the bands are widened to keep it comfortable. Both stay+ * inside the 12px gutters flanking each separator, so no panel content is covered. */+const RESIZE_TARGET_SIZE = { coarse: 32, fine: 22 };++/** A section is its header plus an empty-state card (badge, two wrapped lines); shrinking+ * a panel past that would scroll chrome that has nothing to scroll, so the drag stops+ * here instead. Panels holding content still scroll, which is the point of scrolling.+ * The cap preserves that floor when the group is tall while the measured group height+ * keeps both panels' floors feasible in short viewports. */+const DETAILS_PANEL_MAX_MIN_SIZE = 240;+const DETAILS_PANEL_HANDLE_ALLOWANCE = 1;export default function ProjectWorkspace() {const localize = useLocalize();const navigate = useNavigate();const queryClient = useQueryClient();const { projectId = '' } = useParams();+ const [searchParams, setSearchParams] = useSearchParams();const [sortBy, setSortBy] = useState<ChatSortField>('updatedAt');- const [isEditOpen, setIsEditOpen] = useState(false);+ const [editingProjectId, setEditingProjectId] = useState<string | null>(null);+ const [initialEditField, setInitialEditField] = useState<'name' | 'description'>('name');+ const isEditOpen = editingProjectId === projectId || searchParams.get('edit') === '1';+ const [isInstructionsOpen, setIsInstructionsOpen] = useState(false);const [isDeleteOpen, setIsDeleteOpen] = useState(false);+ const projectMenuId = useId();const sortMenuId = useId();+ const [isProjectMenuOpen, setIsProjectMenuOpen] = useState(false);const [isSortMenuOpen, setIsSortMenuOpen] = useState(false);+ const nameInputRef = useRef<HTMLInputElement>(null);+ const titleButtonRef = useRef<HTMLButtonElement>(null);+ const descriptionButtonRef = useRef<HTMLButtonElement>(null);+ const deleteMenuRef = useRef<HTMLButtonElement>(null);+ const instructionsButtonRef = useRef<HTMLButtonElement>(null);const { data: project, isLoading: isProjectLoading } = useProjectQuery(projectId);+ const { data: startupConfig } = useGetStartupConfig();+ const isRagEnabled = startupConfig?.ragEnabled === true;const conversation = useRecoilValue(store.conversationByIndex(0));const { newConversation } = useNewConvo();const activeProjectId = project?._id;const isSmallScreen = useMediaQuery('(max-width: 768px)');+ /** Panel sizes are a workspace-wide preference, so they persist per browser+ * rather than per project; the files panel keys its own layout so hiding it+ * (no RAG service) does not overwrite the split used when it is present. */+ const workspaceLayout = useDefaultLayout({+ id: 'project-workspace-layout',+ panelIds: WORKSPACE_PANEL_IDS,+ storage: localStorage,+ });+ const detailsLayout = useDefaultLayout({+ id: 'project-details-layout',+ panelIds: isRagEnabled ? DETAILS_PANEL_IDS_WITH_FILES : DETAILS_PANEL_IDS,+ storage: localStorage,+ });+ const { ref: detailsGroupRef, height: detailsGroupHeight } = useElementSize<HTMLDivElement>();+ const detailsPanelMinSize = `${Math.min(+ DETAILS_PANEL_MAX_MIN_SIZE,+ Math.max(0, Math.floor((detailsGroupHeight - DETAILS_PANEL_HANDLE_ALLOWANCE) / 2)),+ )}px`;++ const startEditing = (field: 'name' | 'description') => {+ setInitialEditField(field);+ setEditingProjectId(projectId);+ };++ const finishEditing = () => {+ setEditingProjectId(null);+ if (searchParams.has('edit')) {+ const nextParams = new URLSearchParams(searchParams);+ nextParams.delete('edit');+ setSearchParams(nextParams, { replace: true });+ }+ requestAnimationFrame(() => {+ const target = initialEditField === 'description' ? descriptionButtonRef : titleButtonRef;+ target.current?.focus();+ });+ };+const sortOptions = useMemo(() => [{ value: 'updatedAt' as const, label: localize('com_ui_sort_updated') },@@ -59,20 +139,6 @@ export default function ProjectWorkspace() {);const selectedSortLabel =sortOptions.find((option) => option.value === sortBy)?.label ?? localize('com_ui_sort_updated');- const sortMenuItems = useMemo<MenuItemProps[]>(- () =>- sortOptions.map((option) => {- const isSelected = sortBy === option.value;- return {- id: `project-chat-sort-${option.value}`,- ariaLabel: option.label,- ariaChecked: isSelected,- onClick: () => setSortBy(option.value),- render: renderSortMenuItem(option.label, isSelected),- };- }),- [sortBy, sortOptions],- );const {data,@@ -118,8 +184,8 @@ export default function ProjectWorkspace() {if (isProjectLoading) {return (- <div className="bg-presentation flex h-full items-center justify-center">- <Spinner className="text-text-primary" />+ <div className="bg-presentation text-text-primary flex h-full items-center justify-center">+ <Spinner /></div>);}@@ -135,142 +201,309 @@ export default function ProjectWorkspace() {);}+ const detailsHeader = isEditOpen ? (+ <ProjectEditor+ key={project._id}+ project={project}+ inputRef={nameInputRef}+ initialField={initialEditField}+ onDone={finishEditing}+ />+ ) : (+ <div className="min-w-0">+ <div className="flex min-w-0 items-start gap-4">+ <span className="bg-surface-secondary text-text-secondary flex size-12 shrink-0 items-center justify-center rounded-2xl">+ <Folder className="size-6" aria-hidden="true" />+ </span>+ <h1 className="min-w-0 flex-1">+ <Button+ ref={titleButtonRef}+ type="button"+ variant="inline-edit"+ onClick={() => startEditing('name')}+ className="min-h-12 w-full min-w-0"+ >+ <span className="line-clamp-2 min-w-0 text-2xl font-semibold tracking-tight wrap-anywhere md:line-clamp-1">+ {project.name}+ </span>+ <span className="sr-only">, {localize('com_ui_project_edit_name')}</span>+ </Button>+ </h1>+ </div>+ <Button+ ref={descriptionButtonRef}+ type="button"+ variant="inline-edit"+ onClick={() => startEditing('description')}+ className="mt-1 min-h-10 w-full min-w-0"+ >+ <span className="text-text-secondary line-clamp-3 min-w-0 text-sm leading-relaxed font-normal wrap-anywhere">+ {project.description || localize('com_ui_add_description')}+ </span>+ <span className="sr-only">, {localize('com_ui_project_edit_description')}</span>+ </Button>+ </div>+ );++ const instructionsSection = (+ <section+ className="border-border-light bg-surface-secondary flex h-full min-h-0 min-w-0 flex-col rounded-2xl border p-4 sm:p-5"+ aria-labelledby="project-instructions-heading"+ >+ <div className="mb-3 flex items-center justify-between gap-2">+ <div className="flex min-w-0 items-center gap-1">+ <h2 id="project-instructions-heading" className="text-text-primary text-sm font-semibold">+ {localize('com_ui_project_instructions')}+ </h2>+ <TooltipAnchor+ description={localize('com_ui_project_instructions_future_turns')}+ render={+ <Button+ type="button"+ variant="section-action"+ size="icon-xs"+ className="relative shrink-0 after:absolute after:-inset-1.5"+ aria-label={localize('com_ui_project_instructions_info')}+ >+ <Info className="size-3.5" aria-hidden="true" />+ </Button>+ }+ />+ </div>+ <Button+ ref={instructionsButtonRef}+ type="button"+ variant="ghost"+ size="sm"+ aria-label={localize('com_ui_project_edit_instructions')}+ onClick={() => setIsInstructionsOpen(true)}+ >+ <Pencil className="size-4" aria-hidden="true" />+ {localize('com_ui_edit')}+ </Button>+ </div>+ <div+ role="region"+ aria-label={localize('com_ui_project_instructions_preview')}+ tabIndex={project.instructions?.trim() ? 0 : undefined}+ className="focus-visible:ring-text-primary min-h-0 flex-1 overflow-y-auto rounded-md focus-visible:ring-2 focus-visible:outline-hidden focus-visible:ring-inset"+ >+ {project.instructions?.trim() ? (+ <p className="text-text-secondary text-base leading-relaxed wrap-anywhere whitespace-pre-wrap">+ {project.instructions}+ </p>+ ) : (+ <EmptyState+ icon={NotebookPen}+ description={localize('com_ui_project_no_instructions')}+ className="h-full"+ />+ )}+ </div>+ </section>+ );++ const chatsSection = (+ <section+ className="flex h-full min-h-0 min-w-0 flex-col"+ aria-labelledby="project-chats-heading"+ >+ <div className="mb-3 flex items-center justify-between gap-3">+ <h2+ id="project-chats-heading"+ className="text-text-primary flex items-baseline gap-2 text-sm font-semibold"+ >+ {localize('com_ui_chats')}+ <span className="text-text-secondary tabular-nums">{project.conversationCount}</span>+ </h2>+ <DropdownPopup+ portal={true}+ focusLoop={true}+ unmountOnHide={true}+ menuId={sortMenuId}+ isOpen={isSortMenuOpen}+ setIsOpen={setIsSortMenuOpen}+ trigger={+ <Ariakit.MenuButton+ aria-label={localize('com_ui_sort_chats_by')}+ className="aria-expanded:bg-surface-hover"+ render={<Button type="button" variant="ghost" size="sm" />}+ >+ <ArrowUpDown className="size-4" aria-hidden="true" />+ {selectedSortLabel}+ </Ariakit.MenuButton>+ }+ items={sortOptions.map((option) => ({+ label: option.label,+ ariaChecked: sortBy === option.value,+ icon:+ sortBy === option.value ? (+ <Check className="text-text-secondary size-4" aria-hidden="true" />+ ) : (+ <span className="size-4" aria-hidden="true" />+ ),+ onClick: () => setSortBy(option.value),+ }))}+ />+ </div>+ <ProjectChatList+ conversations={conversations}+ isLoading={isConversationsLoading}+ isFetchingNextPage={isFetchingNextPage}+ hasNextPage={hasNextPage}+ sortBy={sortBy}+ emptyLabel={localize('com_ui_no_project_chats')}+ loadMore={() => fetchNextPage()}+ />+ </section>+ );++ const filesSection = isRagEnabled ? (+ <ProjectResources key={project._id} project={project} />+ ) : null;+return (- <main className="bg-presentation text-text-primary flex h-full min-h-0 flex-col overflow-y-auto">+ <main className="bg-presentation text-text-primary flex h-full min-h-0 min-w-0 flex-col"><header className="border-border-light bg-presentation sticky top-0 z-10 border-b">- <div className="mx-auto flex h-14 w-full max-w-6xl items-center gap-2 px-4 md:h-16 md:px-6">+ <div className="flex h-14 w-full items-center gap-2 px-4 md:h-16 md:px-6">{isSmallScreen ? <OpenSidebar className="size-9 shrink-0" /> : null}<Buttontype="button"- variant="ghost"+ variant="section-action"size="sm"onClick={() => navigate('/projects')}- className="text-text-secondary hover:text-text-primary -ml-1.5"+ className="-ml-1.5">- <ArrowLeft className="h-4 w-4" aria-hidden="true" />+ <ArrowLeft className="size-4" aria-hidden="true" />{localize('com_ui_all_projects')}</Button>- </div>- </header>-- <div className="mx-auto flex w-full max-w-6xl flex-1 flex-col px-4 pt-6 pb-10 md:px-6 md:pt-8">- <div className="flex items-start gap-3.5">- <span className="bg-surface-secondary text-text-secondary flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl">- <Folder className="h-6 w-6" aria-hidden="true" />- </span>- <div className="min-w-0 flex-1 pt-0.5">- <h1 className="text-text-primary truncate text-2xl font-semibold tracking-tight text-balance">- {project.name}- </h1>- {project.description ? (- <p className="text-text-secondary mt-1 text-sm leading-relaxed text-pretty">- {project.description}- </p>- ) : (- <button- type="button"- onClick={() => setIsEditOpen(true)}- className="text-text-tertiary hover:text-text-primary focus-visible:ring-text-primary mt-1 text-sm transition-colors focus-visible:ring-2 focus-visible:outline-hidden"+ <Button+ type="button"+ size="sm"+ className="ml-auto shrink-0"+ variant="default"+ onClick={startProjectChat}+ aria-label={localize('com_ui_new_chat_in_project', { name: project.name })}+ >+ <Plus className="size-4" aria-hidden="true" />+ <span className="hidden sm:inline">{localize('com_ui_new_chat')}</span>+ </Button>+ <DropdownPopup+ portal={true}+ focusLoop={true}+ unmountOnHide={true}+ menuId={projectMenuId}+ isOpen={isProjectMenuOpen}+ setIsOpen={setIsProjectMenuOpen}+ trigger={+ <Ariakit.MenuButton+ aria-label={localize('com_ui_project_options')}+ className="aria-expanded:bg-surface-hover shrink-0"+ render={<Button type="button" variant="outline" size="icon" />}>- {localize('com_ui_add_description')}- </button>- )}- </div>- <div className="flex shrink-0 items-center gap-0.5 pt-1">- <TooltipAnchor- description={localize('com_ui_edit_project')}- render={- <Button- type="button"- variant="ghost"- size="icon"- className="text-text-secondary hover:text-text-primary size-8 shrink-0"- aria-label={localize('com_ui_edit_project')}- onClick={() => setIsEditOpen(true)}- >- <Pencil className="h-4 w-4" aria-hidden="true" />- </Button>- }- />- <TooltipAnchor- description={localize('com_ui_delete_project_action')}- render={- <Button- type="button"- variant="ghost"- size="icon"- className="text-text-secondary hover:text-text-destructive size-8 shrink-0"- aria-label={localize('com_ui_delete_project_action')}- onClick={() => setIsDeleteOpen(true)}- >- <Trash2 className="h-4 w-4" aria-hidden="true" />- </Button>- }- />- </div>+ <MoreHorizontal className="size-5" aria-hidden="true" />+ </Ariakit.MenuButton>+ }+ items={[+ {+ label: localize('com_ui_delete_project_action'),+ icon: <Trash2 className="text-text-secondary size-4" aria-hidden="true" />,+ onClick: () => setIsDeleteOpen(true),+ hideOnClick: false,+ ref: deleteMenuRef,+ render: (props) => <button {...props} />,+ },+ ]}+ /></div>+ </header>- <ProjectEditDialog open={isEditOpen} onOpenChange={setIsEditOpen} project={project} />- <ProjectDeleteDialog open={isDeleteOpen} onOpenChange={setIsDeleteOpen} project={project} />+ <ProjectDeleteDialog+ open={isDeleteOpen}+ onOpenChange={setIsDeleteOpen}+ project={project}+ triggerRef={deleteMenuRef}+ />+ <ProjectInstructionsDialog+ open={isInstructionsOpen}+ onOpenChange={setIsInstructionsOpen}+ project={project}+ triggerRef={instructionsButtonRef}+ />- <button- type="button"- onClick={startProjectChat}- className={cn(- 'border-border-light bg-surface-secondary mt-7 flex w-full items-center gap-3 rounded-2xl border px-3.5 py-3 text-left',- 'hover:bg-surface-hover transition-colors duration-150',- 'focus-visible:ring-text-primary focus-visible:ring-2 focus-visible:outline-hidden',- )}- aria-label={localize('com_ui_new_chat_in_project', { name: project.name })}+ {isSmallScreen ? (+ /** Panels need a bounded height to resize against, which a stacked phone+ * layout cannot give them; scroll the column instead. */+ <div className="flex min-w-0 flex-1 flex-col gap-4 overflow-y-auto px-4 py-6">+ {detailsHeader}+ <div className="h-72 shrink-0">{instructionsSection}</div>+ {filesSection != null && <div className="h-72 shrink-0">{filesSection}</div>}+ <div className="flex min-h-[420px] flex-col">{chatsSection}</div>+ </div>+ ) : (+ <ResizablePanelGroup+ orientation="horizontal"+ id="project-workspace"+ defaultLayout={workspaceLayout.defaultLayout}+ onLayoutChanged={workspaceLayout.onLayoutChanged}+ resizeTargetMinimumSize={RESIZE_TARGET_SIZE}+ className="min-h-0 flex-1">- <span className="bg-surface-tertiary text-text-primary flex h-9 w-9 shrink-0 items-center justify-center rounded-xl">- <Plus className="h-4 w-4" aria-hidden="true" />- </span>- <span className="text-text-primary min-w-0 flex-1 truncate text-sm">- {localize('com_ui_new_chat_in_project', { name: project.name })}- </span>- </button>-- <section className="mt-8 flex min-h-0 flex-1 flex-col">- <div className="mb-3 flex items-center justify-between gap-3">- <h2 className="text-text-primary flex items-baseline gap-2 text-sm font-medium">- {localize('com_ui_chats')}- <span className="text-text-secondary tabular-nums">{project.conversationCount}</span>- </h2>- <DropdownPopup- portal={true}- focusLoop={true}- unmountOnHide={true}- menuId={sortMenuId}- isOpen={isSortMenuOpen}- setIsOpen={setIsSortMenuOpen}- className="z-[125] min-w-44"- trigger={- <Ariakit.MenuButton- aria-label={localize('com_ui_sort_chats_by')}- className={cn(- 'text-text-secondary hover:bg-surface-hover hover:text-text-primary focus-visible:ring-text-primary inline-flex h-8 items-center justify-center gap-1.5 rounded-lg px-2.5 text-sm font-medium whitespace-nowrap transition-colors focus-visible:ring-2 focus-visible:outline-hidden',- isSortMenuOpen && 'bg-surface-hover text-text-primary',- )}+ <ResizablePanel+ id="project-details"+ defaultSize="45"+ minSize="25"+ maxSize="70"+ className="min-w-0"+ >+ <div className="flex h-full min-h-0 min-w-0 flex-col gap-4 py-6 pl-4 md:pl-6">+ <div className="pr-3">{detailsHeader}</div>+ {/** The gutter before the workspace separator lives on each section rather than+ * this column, so the details group reaches the panel edge and its horizontal+ * separator overlaps the vertical one. Dragging that overlap resizes both+ * groups at once, which is what moves all three panels together. */}+ <div ref={detailsGroupRef} className="min-h-0 flex-1">+ <ResizablePanelGroup+ orientation="vertical"+ id="project-details-panels"+ defaultLayout={detailsLayout.defaultLayout}+ onLayoutChanged={detailsLayout.onLayoutChanged}+ resizeTargetMinimumSize={RESIZE_TARGET_SIZE}+ className="h-full">- <ArrowUpDown className="h-4 w-4" aria-hidden="true" />- {selectedSortLabel}- </Ariakit.MenuButton>- }- items={sortMenuItems}- />- </div>- <ProjectChatList- conversations={conversations}- isLoading={isConversationsLoading}- isFetchingNextPage={isFetchingNextPage}- hasNextPage={hasNextPage}- sortBy={sortBy}- emptyLabel={localize('com_ui_no_project_chats')}- loadMore={() => fetchNextPage()}- />- </section>- </div>+ <ResizablePanel+ id="project-instructions"+ defaultSize="55"+ minSize={detailsPanelMinSize}+ className="min-h-0"+ >+ <div className="h-full pr-3 pb-3">{instructionsSection}</div>+ </ResizablePanel>+ {filesSection != null && (+ <>+ <ResizableHandleAlt withHandle />+ <ResizablePanel+ id="project-files"+ defaultSize="45"+ minSize={detailsPanelMinSize}+ className="min-h-0"+ >+ <div className="h-full pt-3 pr-3">{filesSection}</div>+ </ResizablePanel>+ </>+ )}+ </ResizablePanelGroup>+ </div>+ </div>+ </ResizablePanel>+ <ResizableHandleAlt withHandle />+ <ResizablePanel id="project-chats" defaultSize="55" minSize="30" className="min-w-0">+ <div className="flex h-full min-h-0 min-w-0 flex-col py-6 pr-4 pl-3 md:pr-6">+ {chatsSection}+ </div>+ </ResizablePanel>+ </ResizablePanelGroup>+ )}</main>);}diff --git a/client/src/components/Projects/ProjectsNavBar.tsx b/client/src/components/Projects/ProjectsNavBar.tsxindex 54d6f224ea..715384f001 100644--- a/client/src/components/Projects/ProjectsNavBar.tsx+++ b/client/src/components/Projects/ProjectsNavBar.tsx@@ -1,29 +1,37 @@import { Plus } from 'lucide-react';-import { Button, useMediaQuery } from '@librechat/client';+import { Button, FilterInput, useMediaQuery } from '@librechat/client';import OpenSidebar from '~/components/Chat/Menus/OpenSidebar';import { useLocalize } from '~/hooks';type ProjectsNavBarProps = {onCreate: () => void;+ search: string;+ onSearchChange: (search: string) => void;};-export default function ProjectsNavBar({ onCreate }: ProjectsNavBarProps) {+export default function ProjectsNavBar({ onCreate, search, onSearchChange }: ProjectsNavBarProps) {const localize = useLocalize();const isSmallScreen = useMediaQuery('(max-width: 768px)');-return (- <header className="sticky top-0 z-10 border-b border-border-light bg-presentation">- <div className="mx-auto flex h-14 w-full max-w-6xl items-center justify-between gap-3 px-4 md:h-16 md:px-6">- <div className="flex min-w-0 items-center gap-2.5">- {isSmallScreen ? <OpenSidebar className="size-9 shrink-0" /> : null}- <h1 className="truncate text-balance text-lg font-semibold tracking-tight text-text-primary md:text-xl">- {localize('com_ui_projects')}- </h1>+ <header className="border-border-light bg-presentation sticky top-0 z-10 border-b">+ <div className="flex min-h-14 w-full flex-wrap items-center gap-2 px-4 py-2.5 md:min-h-16 md:flex-nowrap md:px-6">+ {isSmallScreen ? <OpenSidebar className="size-9 shrink-0" /> : null}+ <h1 className="sr-only">{localize('com_ui_projects')}</h1>+ <FilterInput+ inputId="projects-search"+ type="text"+ value={search}+ onChange={(event) => onSearchChange(event.target.value)}+ label={localize('com_ui_search_projects')}+ surface="presentation"+ containerClassName="order-last w-full min-w-0 md:order-none md:w-auto md:max-w-md md:flex-1"+ />+ <div className="ml-auto flex shrink-0 items-center gap-2">+ <Button type="button" variant="default" size="sm" onClick={onCreate} className="shrink-0">+ <Plus className="size-4" aria-hidden="true" />+ {localize('com_ui_new_project')}+ </Button></div>- <Button type="button" variant="default" size="sm" onClick={onCreate} className="shrink-0">- <Plus className="h-4 w-4" aria-hidden="true" />- {localize('com_ui_new_project')}- </Button></div></header>);diff --git a/client/src/components/Projects/ProjectsSortMenu.tsx b/client/src/components/Projects/ProjectsSortMenu.tsxnew file mode 100644index 0000000000..2041e7dc94--- /dev/null+++ b/client/src/components/Projects/ProjectsSortMenu.tsx@@ -0,0 +1,88 @@+import { useId, useMemo, useState } from 'react';+import * as Ariakit from '@ariakit/react';+import { ArrowUpDown, Check } from 'lucide-react';+import { DropdownPopup } from '@librechat/client';+import type { MenuItemProps, RenderProp } from '~/common';+import { useLocalize } from '~/hooks';+import { cn } from '~/utils';++export type ProjectSort = 'name' | 'createdAt' | 'lastConversationAt';++type ProjectsSortMenuProps = {+ sortBy: ProjectSort;+ onSortChange: (sortBy: ProjectSort) => void;+};++function renderSortMenuItem(label: string, isSelected: boolean): RenderProp {+ return function SortMenuItem({ className, ...props }) {+ return (+ <div {...props} className={cn(className, 'justify-between gap-5')}>+ <span className="truncate">{label}</span>+ {isSelected ? (+ <Check className="text-text-primary h-4 w-4 shrink-0" aria-hidden="true" />+ ) : (+ <span className="h-4 w-4 shrink-0" aria-hidden="true" />+ )}+ </div>+ );+ };+}++export default function ProjectsSortMenu({ sortBy, onSortChange }: ProjectsSortMenuProps) {+ const localize = useLocalize();+ const sortMenuId = useId();+ const [isOpen, setIsOpen] = useState(false);++ const sortOptions = useMemo(+ () => [+ { value: 'lastConversationAt' as const, label: localize('com_ui_latest_activity') },+ { value: 'createdAt' as const, label: localize('com_ui_sort_created') },+ { value: 'name' as const, label: localize('com_ui_name') },+ ],+ [localize],+ );+ const selectedSortLabel =+ sortOptions.find((option) => option.value === sortBy)?.label ??+ localize('com_ui_latest_activity');+ const sortMenuItems = useMemo<MenuItemProps[]>(+ () =>+ sortOptions.map((option) => {+ const isSelected = sortBy === option.value;+ return {+ id: `project-sort-${option.value}`,+ ariaLabel: option.label,+ ariaChecked: isSelected,+ onClick: () => onSortChange(option.value),+ render: renderSortMenuItem(option.label, isSelected),+ };+ }),+ [onSortChange, sortBy, sortOptions],+ );++ return (+ <DropdownPopup+ portal={true}+ focusLoop={true}+ unmountOnHide={true}+ menuId={sortMenuId}+ isOpen={isOpen}+ setIsOpen={setIsOpen}+ className="z-[125] min-w-56"+ trigger={+ <Ariakit.MenuButton+ aria-label={localize('com_ui_sort_projects_by')}+ className={cn(+ 'text-text-secondary inline-flex h-8 shrink-0 items-center justify-center gap-2 rounded-lg px-2 text-sm font-medium transition-colors',+ 'hover:bg-surface-hover hover:text-text-primary',+ 'focus-visible:ring-text-primary focus-visible:ring-2 focus-visible:outline-hidden',+ isOpen && 'bg-surface-hover text-text-primary',+ )}+ >+ <ArrowUpDown className="size-4 shrink-0" aria-hidden="true" />+ <span className="truncate">{selectedSortLabel}</span>+ </Ariakit.MenuButton>+ }+ items={sortMenuItems}+ />+ );+}diff --git a/client/src/components/Projects/ProjectsView.tsx b/client/src/components/Projects/ProjectsView.tsxindex 464fff5cec..5e978755c1 100644--- a/client/src/components/Projects/ProjectsView.tsx+++ b/client/src/components/Projects/ProjectsView.tsx@@ -1,54 +1,20 @@-import { useDeferredValue, useEffect, useId, useMemo, useState } from 'react';+import { useCallback, useDeferredValue, useEffect, useId, useMemo, useRef, useState } from 'react';import * as Ariakit from '@ariakit/react';import { useNavigate, useSearchParams } from 'react-router-dom';-import { Input, Button, Skeleton, DropdownPopup } from '@librechat/client';-import {- ArrowUpDown,- Check,- Ellipsis,- Folder,- FolderPlus,- Pencil,- Search,- Trash2,-} from 'lucide-react';+import { Ellipsis, Folder, FolderPlus, Pencil, Trash2 } from 'lucide-react';+import { Button, DropdownPopup, Skeleton, Spinner } from '@librechat/client';import type { TChatProject } from 'librechat-data-provider';-import type { LocalizeFunction, MenuItemProps, RenderProp } from '~/common';+import type { ProjectSort } from './ProjectsSortMenu';+import type { MenuItemProps } from '~/common';import { useProjectsInfiniteQuery } from '~/data-provider';import ProjectCreateDialog from './ProjectCreateDialog';import ProjectDeleteDialog from './ProjectDeleteDialog';-import ProjectEditDialog from './ProjectEditDialog';+import ProjectsSortMenu from './ProjectsSortMenu';import ProjectsNavBar from './ProjectsNavBar';+import ProjectEditor from './ProjectEditor';import { useLocalize } from '~/hooks';import { cn } from '~/utils';-type ProjectSort = 'name' | 'createdAt' | 'lastConversationAt';--function renderSortMenuItem(label: string, isSelected: boolean): RenderProp {- return function SortMenuItem({ className, ...props }) {- return (- <div {...props} className={cn(className, 'justify-between gap-5')}>- <span className="truncate">{label}</span>- {isSelected ? (- <Check className="text-text-primary h-4 w-4 shrink-0" aria-hidden="true" />- ) : (- <span className="h-4 w-4 shrink-0" aria-hidden="true" />- )}- </div>- );- };-}--function getProjectCountLabel(count: number, hasMore: boolean, localize: LocalizeFunction) {- if (hasMore) {- return localize('com_ui_project_count_partial', { count });- }- if (count === 1) {- return localize('com_ui_project_count_single');- }- return localize('com_ui_project_count', { count });-}-function formatActivity(project: TChatProject) {const value = project.lastConversationAt ?? project.updatedAt ?? project.createdAt;if (!value) {@@ -63,15 +29,16 @@ function formatActivity(project: TChatProject) {function ProjectCard({project,- index,onOpen,}: {project: TChatProject;- index: number;onOpen: (projectId: string) => void;}) {const localize = useLocalize();const menuId = useId();+ const navigationButtonRef = useRef<HTMLButtonElement>(null);+ const inputRef = useRef<HTMLInputElement>(null);+ const deleteMenuRef = useRef<HTMLButtonElement>(null);const [isMenuOpen, setIsMenuOpen] = useState(false);const [isEditOpen, setIsEditOpen] = useState(false);const [isDeleteOpen, setIsDeleteOpen] = useState(false);@@ -89,6 +56,9 @@ function ProjectCard({label: localize('com_ui_delete'),icon: <Trash2 className="text-text-secondary size-4" aria-hidden="true" />,onClick: () => setIsDeleteOpen(true),+ hideOnClick: false,+ ref: deleteMenuRef,+ render: (props) => <button {...props} />,},],[localize, menuId],@@ -97,51 +67,69 @@ function ProjectCard({return (<articleclassName={cn(- 'group/project border-border-light bg-surface-secondary relative flex min-h-[9.5rem] flex-col rounded-2xl border',+ 'group/project border-border-light bg-surface-secondary relative flex min-h-[9.5rem] max-w-full min-w-0 flex-col rounded-2xl border','hover:bg-surface-hover transition-colors duration-150 ease-out',- 'motion-safe:animate-in motion-safe:fade-in motion-safe:slide-in-from-bottom-1 motion-safe:fill-mode-both',)}- style={{ animationDelay: `${Math.min(index, 8) * 40}ms` }}>- <button- type="button"- className="focus-visible:ring-text-primary flex min-h-[9.5rem] flex-1 flex-col rounded-2xl p-4 pr-12 text-left focus-visible:ring-2 focus-visible:outline-hidden focus-visible:ring-inset"- onClick={() => onOpen(project._id)}- >- <span className="bg-surface-tertiary text-text-secondary group-hover/project:text-text-primary flex h-11 w-11 shrink-0 items-center justify-center rounded-xl transition-colors">- <Folder className="h-5 w-5" aria-hidden="true" />- </span>- <span className="text-text-primary mt-3 truncate text-base font-semibold tracking-tight">- {project.name}- </span>- {project.description ? (- <span className="text-text-secondary mt-1 line-clamp-2 text-sm leading-relaxed text-pretty">- {project.description}+ {isEditOpen ? (+ <div className="min-w-0 p-4 pr-12">+ <ProjectEditor+ project={project}+ layout="card"+ inputRef={inputRef}+ onDone={() => {+ setIsEditOpen(false);+ requestAnimationFrame(() => navigationButtonRef.current?.focus());+ }}+ />+ </div>+ ) : (+ <Button+ ref={navigationButtonRef}+ type="button"+ variant="card"+ size="tile"+ className="min-h-[9.5rem] w-full max-w-full min-w-0 flex-1 flex-col items-stretch"+ onClick={() => onOpen(project._id)}+ >+ <span className="bg-surface-tertiary text-text-secondary group-hover/project:text-text-primary flex h-11 w-11 shrink-0 items-center justify-center rounded-xl transition-colors">+ <Folder className="h-5 w-5" aria-hidden="true" /></span>- ) : null}- <span className="text-text-secondary mt-auto flex items-center gap-2 pt-4 text-xs tabular-nums">- <span>- {project.conversationCount === 1- ? localize('com_ui_project_chat_count_single')- : localize('com_ui_project_chat_count', {- count: project.conversationCount,- })}+ <span className="text-text-primary mt-3 line-clamp-2 max-w-full min-w-0 text-base font-semibold tracking-tight wrap-anywhere md:line-clamp-1">+ {project.name}</span>- {activity ? (- <>- <span aria-hidden="true">·</span>- <time dateTime={project.lastConversationAt ?? project.updatedAt ?? project.createdAt}>- {activity}- </time>- </>+ {project.description ? (+ <span className="text-text-secondary mt-1 line-clamp-2 max-w-full min-w-0 text-sm leading-relaxed text-pretty wrap-anywhere">+ {project.description}+ </span>) : null}- </span>- </button>+ <span className="text-text-secondary mt-auto flex max-w-full min-w-0 items-center gap-2 pt-4 text-xs tabular-nums">+ <span>+ {project.conversationCount === 1+ ? localize('com_ui_project_chat_count_single')+ : localize('com_ui_project_chat_count', {+ count: project.conversationCount,+ })}+ </span>+ {activity ? (+ <>+ <span aria-hidden="true">·</span>+ <time+ dateTime={project.lastConversationAt ?? project.updatedAt ?? project.createdAt}+ >+ {activity}+ </time>+ </>+ ) : null}+ </span>+ </Button>+ )}<div className="absolute top-2 right-2"><DropdownPopupportal={true}focusLoop={true}unmountOnHide={true}+ finalFocus={isEditOpen ? inputRef : undefined}menuId={menuId}isOpen={isMenuOpen}setIsOpen={setIsMenuOpen}@@ -163,15 +151,19 @@ function ProjectCard({items={menuItems}/></div>- <ProjectEditDialog open={isEditOpen} onOpenChange={setIsEditOpen} project={project} />- <ProjectDeleteDialog open={isDeleteOpen} onOpenChange={setIsDeleteOpen} project={project} />+ <ProjectDeleteDialog+ open={isDeleteOpen}+ onOpenChange={setIsDeleteOpen}+ project={project}+ triggerRef={deleteMenuRef}+ /></article>);}function ProjectGridSkeleton() {return (- <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3" aria-hidden="true">+ <div className="grid grid-cols-[repeat(auto-fill,minmax(17rem,1fr))] gap-3" aria-hidden="true">{Array.from({ length: 6 }, (_, index) => (<divkey={index}@@ -194,47 +186,18 @@ export default function ProjectsView() {const [search, setSearch] = useState('');const [sortBy, setSortBy] = useState<ProjectSort>('lastConversationAt');const [isCreating, setIsCreating] = useState(searchParams.get('new') === '1');- const sortMenuId = useId();- const [isSortMenuOpen, setIsSortMenuOpen] = useState(false);const deferredSearch = useDeferredValue(search);+ const scrollRef = useRef<HTMLElement | null>(null);+ const [pageSentinel, setPageSentinel] = useState<HTMLDivElement | null>(null);- const { data, fetchNextPage, isFetchingNextPage, isLoading } = useProjectsInfiniteQuery({- search: deferredSearch || undefined,- sortBy,- sortDirection: sortBy === 'name' ? 'asc' : 'desc',- });+ const { data, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage, isLoading } =+ useProjectsInfiniteQuery({+ search: deferredSearch || undefined,+ sortBy,+ sortDirection: sortBy === 'name' ? 'asc' : 'desc',+ });const projects = useMemo(() => data?.pages.flatMap((page) => page.projects) ?? [], [data?.pages]);- const hasNextPage = data?.pages[data.pages.length - 1]?.nextCursor != null;- const sortOptions = useMemo(- () => [- { value: 'lastConversationAt' as const, label: localize('com_ui_latest_activity') },- { value: 'createdAt' as const, label: localize('com_ui_sort_created') },- { value: 'name' as const, label: localize('com_ui_name') },- ],- [localize],- );- const selectedSortLabel =- sortOptions.find((option) => option.value === sortBy)?.label ??- localize('com_ui_latest_activity');- const sortMenuItems = useMemo<MenuItemProps[]>(- () =>- sortOptions.map((option) => {- const isSelected = sortBy === option.value;- return {- id: `project-sort-${option.value}`,- ariaLabel: option.label,- ariaChecked: isSelected,- onClick: () => setSortBy(option.value),- render: renderSortMenuItem(option.label, isSelected),- };- }),- [sortBy, sortOptions],- );-- /** `projects` only holds the pages fetched so far, so while another page- * exists this is a lower bound rather than the total. */- const projectCountLabel = getProjectCountLabel(projects.length, hasNextPage, localize);useEffect(() => {if (searchParams.get('new') === '1') {@@ -251,57 +214,52 @@ export default function ProjectsView() {}};- return (- <main className="bg-surface-primary-alt text-text-primary flex h-full min-h-0 flex-col overflow-auto">- <ProjectsNavBar onCreate={() => setIsCreating(true)} />+ const loadMore = useCallback(() => {+ if (hasNextPage === true && !isFetching) {+ /** `cancelRefetch: false` so a scroll burst coalesces into one request+ * instead of each intersection restarting the page in flight. */+ void fetchNextPage({ cancelRefetch: false });+ }+ }, [fetchNextPage, hasNextPage, isFetching]);- <div className="mx-auto flex w-full max-w-6xl flex-1 flex-col px-4 pt-6 pb-10 md:px-6 md:pt-8">- <div className="flex flex-col gap-3 sm:flex-row sm:items-center">- <label className="relative min-w-0 flex-1">- <span className="sr-only">{localize('com_ui_search_projects')}</span>- <Search- className="text-text-tertiary pointer-events-none absolute top-1/2 left-3.5 h-4 w-4 -translate-y-1/2"- aria-hidden="true"- />- <Input- value={search}- onChange={(event) => setSearch(event.target.value)}- placeholder={localize('com_ui_search_projects')}- className="bg-surface-secondary h-11 rounded-xl pl-10"- />- </label>- <DropdownPopup- portal={true}- focusLoop={true}- unmountOnHide={true}- menuId={sortMenuId}- isOpen={isSortMenuOpen}- setIsOpen={setIsSortMenuOpen}- className="z-[125] min-w-56"- trigger={- <Ariakit.MenuButton- aria-label={localize('com_ui_sort_projects_by')}- className={cn(- 'text-text-secondary inline-flex h-11 shrink-0 items-center justify-center gap-2 rounded-xl px-3 text-sm font-medium transition-colors',- 'hover:bg-surface-hover hover:text-text-primary',- 'focus-visible:ring-text-primary focus-visible:ring-2 focus-visible:outline-hidden',- isSortMenuOpen && 'bg-surface-hover text-text-primary',- )}- >- <ArrowUpDown className="h-4 w-4 shrink-0" aria-hidden="true" />- <span className="truncate">{selectedSortLabel}</span>- </Ariakit.MenuButton>- }- items={sortMenuItems}- />- </div>+ /** The list scrolls inside `<main>`, so the viewport root would clip the+ * sentinel and only report it once it is already on screen; observing the+ * scroll container lets `rootMargin` prefetch a page ahead of the edge. */+ useEffect(() => {+ const root = scrollRef.current;+ if (pageSentinel == null || root == null) {+ return;+ }+ const observer = new IntersectionObserver(+ ([entry]) => {+ if (entry.isIntersecting) {+ loadMore();+ }+ },+ { root, rootMargin: '600px 0px' },+ );+ observer.observe(pageSentinel);+ return () => observer.disconnect();+ }, [loadMore, pageSentinel]);++ return (+ <main+ ref={scrollRef}+ className="bg-surface-primary-alt text-text-primary flex h-full min-h-0 flex-col overflow-auto"+ >+ <ProjectsNavBar+ onCreate={() => setIsCreating(true)}+ search={search}+ onSearchChange={setSearch}+ />- <div className="mt-8 flex items-baseline justify-between gap-3">+ <div className="flex w-full flex-1 flex-col px-4 pt-3 pb-10 md:px-6 md:pt-4">+ <div className="flex min-h-8 items-center justify-between gap-3"><h2 className="text-text-primary text-sm font-medium">{localize('com_ui_your_projects')}</h2>{!isLoading && projects.length > 0 ? (- <p className="text-text-secondary text-sm tabular-nums">{projectCountLabel}</p>+ <ProjectsSortMenu sortBy={sortBy} onSortChange={setSortBy} />) : null}</div>@@ -314,12 +272,11 @@ export default function ProjectsView() {<div className="mt-4 flex flex-1 flex-col">{isLoading && <ProjectGridSkeleton />}{!isLoading && projects.length > 0 && (- <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">- {projects.map((project, index) => (+ <div className="grid grid-cols-[repeat(auto-fill,minmax(17rem,1fr))] gap-3">+ {projects.map((project) => (<ProjectCardkey={project._id}project={project}- index={index}onOpen={(projectId) => navigate(`/projects/${projectId}`)}/>))}@@ -355,15 +312,15 @@ export default function ProjectsView() {</div>{hasNextPage && (- <Button- type="button"- variant="outline"- className="mx-auto mt-8"- onClick={() => fetchNextPage()}- disabled={isFetchingNextPage}+ <div+ ref={setPageSentinel}+ className="text-text-primary flex h-16 shrink-0 items-center justify-center"+ role="status"+ aria-live="polite"+ aria-label={localize('com_ui_loading')}>- {isFetchingNextPage ? localize('com_ui_loading') : localize('com_ui_load_more')}- </Button>+ {isFetchingNextPage ? <Spinner className="size-5" /> : null}+ </div>)}</div></main>diff --git a/client/src/data-provider/Projects/mutations.ts b/client/src/data-provider/Projects/mutations.tsindex af28992b45..ba6eb8ddea 100644--- a/client/src/data-provider/Projects/mutations.ts+++ b/client/src/data-provider/Projects/mutations.ts@@ -10,7 +10,7 @@ import type {TAssignConversationToProjectRequest,TAssignConversationToProjectResponse,} from 'librechat-data-provider';-import type { UseMutationResult } from '@tanstack/react-query';+import type { QueryClient, UseMutationResult } from '@tanstack/react-query';import { enqueue, invalidateConversationLists } from '~/utils';import { getSessionPrincipal } from '~/utils/session';import store from '~/store';@@ -216,3 +216,50 @@ export const useAssignConversationToProjectMutation = (): UseMutationResult<},);};++export type ProjectFileMutationVariables = {+ projectId: string;+ file_id: string;+};++const invalidateProjectFiles = (queryClient: QueryClient, projectId: string): void => {+ queryClient.invalidateQueries({+ queryKey: [QueryKeys.project, projectId],+ refetchType: 'all',+ });+ queryClient.invalidateQueries([QueryKeys.projectFiles, projectId]);+ queryClient.invalidateQueries([QueryKeys.projectAvailableFiles, projectId]);+ queryClient.invalidateQueries([QueryKeys.projects]);+};++export const useAddProjectFileMutation = (): UseMutationResult<+ TChatProject,+ unknown,+ ProjectFileMutationVariables,+ unknown+> => {+ const queryClient = useQueryClient();+ return useMutation(+ ({ projectId, file_id }: ProjectFileMutationVariables) =>+ dataService.addProjectFile({ projectId, file_id }),+ {+ onSuccess: (_project, variables) => invalidateProjectFiles(queryClient, variables.projectId),+ },+ );+};++export const useRemoveProjectFileMutation = (): UseMutationResult<+ TChatProject,+ unknown,+ ProjectFileMutationVariables,+ unknown+> => {+ const queryClient = useQueryClient();+ return useMutation(+ ({ projectId, file_id }: ProjectFileMutationVariables) =>+ dataService.removeProjectFile({ projectId, file_id }),+ {+ onSuccess: (_project, variables) => invalidateProjectFiles(queryClient, variables.projectId),+ },+ );+};diff --git a/client/src/data-provider/Projects/queries.ts b/client/src/data-provider/Projects/queries.tsindex 6a8a4ccefd..37de0add31 100644--- a/client/src/data-provider/Projects/queries.ts+++ b/client/src/data-provider/Projects/queries.ts@@ -1,11 +1,18 @@-import { useInfiniteQuery, useQuery } from '@tanstack/react-query';import { dataService, QueryKeys } from 'librechat-data-provider';+import { useInfiniteQuery, useQuery } from '@tanstack/react-query';+import type {+ ProjectAvailableFilesParams,+ ProjectAvailableFilesResponse,+ ProjectListParams,+ ProjectListResponse,+ TChatProject,+ TChatProjectFile,+} from 'librechat-data-provider';import type {UseInfiniteQueryOptions,QueryObserverResult,UseQueryOptions,} from '@tanstack/react-query';-import type { ProjectListParams, ProjectListResponse, TChatProject } from 'librechat-data-provider';export const useProjectsInfiniteQuery = (params: ProjectListParams = {},@@ -47,3 +54,37 @@ export const useProjectQuery = (},);};+export const useProjectFilesQuery = (+ projectId?: string | null,+ config?: UseQueryOptions<TChatProjectFile[]>,+): QueryObserverResult<TChatProjectFile[], unknown> => {+ return useQuery<TChatProjectFile[]>(+ [QueryKeys.projectFiles, projectId],+ () => dataService.getProjectFiles(projectId ?? ''),+ {+ enabled: Boolean(projectId),+ refetchOnWindowFocus: false,+ ...config,+ },+ );+};+export const useProjectAvailableFilesInfiniteQuery = (+ projectId?: string | null,+ params: ProjectAvailableFilesParams = {},+ config?: UseInfiniteQueryOptions<ProjectAvailableFilesResponse, unknown>,+) => {+ const queryParams = { limit: params.limit, search: params.search };++ return useInfiniteQuery<ProjectAvailableFilesResponse>({+ queryKey: [QueryKeys.projectAvailableFiles, projectId, queryParams],+ queryFn: ({ pageParam }) =>+ dataService.getAvailableProjectFiles(projectId ?? '', {+ ...queryParams,+ cursor: pageParam?.toString(),+ }),+ getNextPageParam: (lastPage) => lastPage?.nextCursor ?? undefined,+ enabled: Boolean(projectId),+ refetchOnWindowFocus: false,+ ...config,+ });+};diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex e386615096..a40384abdc 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -2099,11 +2099,45 @@"com_ui_pro": "Pro","com_ui_production": "Production","com_ui_project": "Project",+ "com_ui_project_add_files": "Add files",+ "com_ui_project_files_info": "About project files",+ "com_ui_project_instructions_info": "About project instructions",+ "com_ui_project_instructions_preview": "Saved instructions",+ "com_ui_project_options": "Project options","com_ui_project_chat_count": "{{count}} chats","com_ui_project_chat_count_single": "1 chat",- "com_ui_project_count": "{{count}} projects",- "com_ui_project_count_partial": "{{count}}+ projects",- "com_ui_project_count_single": "1 project",+ "com_ui_project_choose_file": "Choose from your files",+ "com_ui_search_files": "Search files",+ "com_ui_project_dismiss_upload": "Dismiss {{name}} upload",+ "com_ui_project_edit_description": "Edit project description",+ "com_ui_project_edit_instructions": "Edit instructions",+ "com_ui_project_edit_name": "Edit project name",+ "com_ui_project_conflict_error": "This project was changed in another session. Reload to see the latest version.",+ "com_ui_project_file_added": "File added",+ "com_ui_project_file_removed": "File removed",+ "com_ui_project_file_excess": "Could not add {{count}} selected file(s) because the project is at its file limit.",+ "com_ui_project_file_attach_error": "Could not add this file to the project",+ "com_ui_project_file_limit": "This project can use up to {{count}} reference files.",+ "com_ui_project_file_failed": "Upload failed",+ "com_ui_project_file_processing": "Processing",+ "com_ui_project_file_ready": "Ready",+ "com_ui_project_file_unavailable": "Unavailable",+ "com_ui_project_file_remove_error": "Could not remove this file from the project",+ "com_ui_project_files": "Files",+ "com_ui_project_files_error": "Could not load project files",+ "com_ui_project_files_help": "When File Search is enabled, chats can use relevant excerpts rather than whole files.",+ "com_ui_project_files_retrieval_only": "Removing a file affects future messages, not chat history.",+ "com_ui_project_instructions": "Instructions",+ "com_ui_project_instructions_error": "Could not save project instructions",+ "com_ui_project_instructions_future_turns": "Used for new messages in this project. Changes won't rewrite earlier messages.",+ "com_ui_project_instructions_help": "Set the tone, goals, or background for chats in this project. Platform and safety rules still apply.",+ "com_ui_project_instructions_label": "Workspace instructions",+ "com_ui_project_no_eligible_files": "No searchable files available. Upload a file to add it here.",+ "com_ui_project_no_files": "Add documents for your chats to reference.",+ "com_ui_project_no_instructions": "Add preferences or background for chats in this project.",+ "com_ui_project_open_workspace": "Open {{name}} workspace",+ "com_ui_project_remove_file": "Remove {{name}} from project",+ "com_ui_project_upload_file": "Upload from device","com_ui_project_create_error": "Failed to create project","com_ui_project_delete_error": "Failed to delete project","com_ui_project_name": "Project name",diff --git a/client/src/utils/files.ts b/client/src/utils/files.tsindex 929617d126..08ca380094 100644--- a/client/src/utils/files.ts+++ b/client/src/utils/files.ts@@ -305,6 +305,17 @@ export function formatBytes(bytes: number, decimals = 2) {return parseFloat((bytes / Math.pow(k, i)).toFixed(dm));}+/** Formats bytes with unit suffix (differs from ~/utils/formatBytes which returns a raw number). */+export function formatFileSize(bytes: number): string {+ if (bytes >= 1048576) {+ return `${(bytes / 1048576).toFixed(1)} MB`;+ }+ if (bytes >= 1024) {+ return `${(bytes / 1024).toFixed(1)} KB`;+ }+ return `${bytes} B`;+}+const { checkType } = defaultFileConfig;type FileSizeValidationParams = {diff --git a/e2e/setup/env.ts b/e2e/setup/env.tsindex 95d8217320..285ee86713 100644--- a/e2e/setup/env.ts+++ b/e2e/setup/env.ts@@ -161,9 +161,13 @@ export function getLocalE2EEnv(): Record<string, string> {TOOL_CALL_VIOLATION_SCORE: '0',CONVO_ACCESS_VIOLATION_SCORE: '0',ILLEGAL_MODEL_REQ_SCORE: '0',- LOGIN_MAX: '20',+ /** The suite authenticates far more often than a person does: a spec that+ * exercises a second account logs in once per Playwright project, and the+ * admin-config specs log in per test. 20 per minute throttles those runs+ * into flakes; no spec asserts login or registration throttling. */+ LOGIN_MAX: '200',LOGIN_WINDOW: '1',- REGISTER_MAX: '20',+ REGISTER_MAX: '200',REGISTER_WINDOW: '1',LIMIT_CONCURRENT_MESSAGES: 'false',CONCURRENT_MESSAGE_MAX: '20',diff --git a/e2e/setup/fake-model.js b/e2e/setup/fake-model.jsindex 2cfc0408c2..c226b3ee87 100644--- a/e2e/setup/fake-model.js+++ b/e2e/setup/fake-model.js@@ -33,6 +33,7 @@ const INVOKE_SKILL_MARKER = 'E2E_INVOKE_SKILL:';const ASSERT_PROVIDER_FILE_MARKER = 'E2E_ASSERT_PROVIDER_FILE:';const ASSERT_AGENT_CONTEXT_MARKER = 'E2E_ASSERT_AGENT_CONTEXT:';const ASSERT_HISTORY_MARKER = 'E2E_ASSERT_HISTORY:';+const ASSERT_PROJECT_CONTEXT_MARKER = 'E2E_ASSERT_PROJECT_CONTEXT:';const ASSERT_QUOTE_MARKER = 'E2E_ASSERT_QUOTE:';const REPLY_MARKER = 'E2E_REPLY:';const THINK_REPLY_MARKER = 'E2E_THINK_REPLY:';@@ -105,6 +106,7 @@ const PROVIDER_FILE_ASSERTION_FINAL_TEXT = 'E2E provider file assertion passed';const AGENT_CONTEXT_ASSERTION_FINAL_TEXT = 'E2E agent context assertion passed';const HISTORY_ASSERTION_PRESENT_TEXT = 'E2E history assertion present';const HISTORY_ASSERTION_ABSENT_TEXT = 'E2E history assertion absent';+const PROJECT_CONTEXT_ASSERTION_FINAL_TEXT = 'E2E project context assertion passed';const QUOTE_ASSERTION_FINAL_TEXT = 'E2E quote assertion passed';const STEER_TOOL_FINAL_TEXT = 'E2E steer tool reply done';const STEER_SPLIT_FINAL_TEXT = 'E2E steer split reply done';@@ -446,6 +448,44 @@ function agentContextAssertionResponses({ messages, text }) {};}+function collectSystemPromptText(messages) {+ return (messages ?? [])+ .filter((message) => messageType(message) === 'system')+ .map((message) => getContentText(message.content))+ .join('\n');+}++/**+ * Project probes deliberately inspect only system messages. The user marker+ * itself and prior human/history messages must never satisfy this assertion.+ * An optional second token asserts that a value is absent after a detach/move.+ */+function projectContextAssertionResponses({ messages, text }) {+ const markerIndex = text.indexOf(ASSERT_PROJECT_CONTEXT_MARKER);+ if (markerIndex === -1) {+ return null;+ }+ const [expected, absent] = text+ .slice(markerIndex + ASSERT_PROJECT_CONTEXT_MARKER.length)+ .trim()+ .split(/\s+/, 2);+ const systemText = collectSystemPromptText(messages);+ const foundExpected = expected === '-' || (Boolean(expected) && systemText.includes(expected));+ const foundAbsent = Boolean(absent) && systemText.includes(absent);+ if (foundExpected && !foundAbsent) {+ return {+ responses: [`${PROJECT_CONTEXT_ASSERTION_FINAL_TEXT}: ${expected || 'absent check'}`],+ };+ }+ return {+ responses: [+ `E2E project context assertion failed: expected ${expected || 'a marker'}${+ absent ? ` without ${absent}` : ''+ }; saw ${systemText || 'no system context'}`,+ ],+ };+}+/*** Answers whether a token from an EARLIER turn still reaches the model. Scans* every prompt message except the current user turn: the marker line carries@@ -3333,6 +3373,21 @@ function resolveResponses({ graph, messages, text, toolNames }) {return askUserQuestionResponses(askUserQuestionLabel, toolNames);}+ if (text.includes(ASSERT_PROJECT_CONTEXT_MARKER)) {+ return {+ responses: [MOCK_REPLY],+ resolveOnStream: async (streamMessages, streamOptions, runManager) => {+ const agentView = await getStreamAgentView({+ graph,+ messages: streamMessages,+ options: streamOptions,+ runManager,+ });+ return projectContextAssertionResponses({ messages: agentView.messages, text });+ },+ };+ }+if (text.includes(ASSERT_AGENT_CONTEXT_MARKER)) {return {responses: [MOCK_REPLY],diff --git a/e2e/specs/mock/content-filters.persisted.spec.ts b/e2e/specs/mock/content-filters.persisted.spec.tsindex 7bcbda8198..f328ae7d7a 100644--- a/e2e/specs/mock/content-filters.persisted.spec.ts+++ b/e2e/specs/mock/content-filters.persisted.spec.ts@@ -1,6 +1,7 @@import { randomUUID } from 'crypto';import { ObjectId } from 'mongodb';import { expect, test } from '@playwright/test';+import { FileContext } from 'librechat-data-provider';import type { Document, Filter } from 'mongodb';import type { FiltersConfig } from 'librechat-data-provider';import { withMongo } from './db';@@ -2214,6 +2215,226 @@ test.describe('persisted source-aware content filters', () => {}});+ test('rejects filtered and deleted Projects before creating an Agent turn', async ({+ request,+ }) => {+ const token = await loginAdmin(request);+ const suffix = randomUUID();+ const marker = `E2E-PROJECT-GUIDANCE-${suffix}`;+ const fixtures: StoredFixtures = { conversationIds: [], agentIds: [] };+ let projectId: string | undefined;+ try {+ await restoreRuntimeFilters(request, token);+ const agent = await createAgent(request, token, fixtures, suffix);+ const agentId = requireString(agent.id, 'Project Agent id');+ const created = await requestResult(request, {+ path: '/api/projects',+ token,+ method: 'POST',+ data: { name: `Project admission ${suffix}`, instructions: marker },+ });+ expectSuccess(created, 201);+ projectId = requireString(asObject(created.body)._id, 'Project id');+ await setRuntimeFilters(request, token, {+ agentInstructions: {+ pii: {+ fields: ['instructions'],+ starterPatterns: [],+ customPatterns: [+ { id: `project-guidance-${suffix}`, label: 'Project guidance', regex: marker },+ ],+ },+ },+ } as FiltersConfig);+ const messageId = randomUUID();+ const sendProjectTurn = () =>+ requestResult(request, {+ path: '/api/agents/chat/agents',+ token,+ method: 'POST',+ data: {+ text: 'Apply the Project instructions.',+ sender: 'User',+ clientTimestamp: new Date().toISOString(),+ isCreatedByUser: true,+ parentMessageId: NO_PARENT,+ conversationId: 'new',+ clientRequestId: suffix,+ messageId,+ responseMessageId: `${messageId}_response`,+ endpoint: 'agents',+ endpointType: 'agents',+ agent_id: agentId,+ chatProjectId: projectId,+ files: [],+ isTemporary: false,+ isRegenerate: false,+ error: false,+ },+ });++ const blocked = await expectNoMongoSideEffects(+ ['conversations', 'messages'],+ sendProjectTurn,+ );+ expectContentFilterBlock(blocked, {+ source: 'agent_instruction',+ field: 'instructions',+ marker,+ });++ const deleted = await requestResult(request, {+ path: `/api/projects/${projectId}`,+ token,+ method: 'DELETE',+ });+ expectSuccess(deleted, 200);+ const missing = await expectNoMongoSideEffects(+ ['conversations', 'messages'],+ sendProjectTurn,+ );+ expect(missing.status, missing.text).toBe(404);+ expect(missing.body).not.toHaveProperty('streamId');+ } finally {+ await restoreRuntimeFilters(request, token);+ if (projectId) {+ await requestResult(request, {+ path: `/api/projects/${projectId}`,+ token,+ method: 'DELETE',+ });+ }+ await cleanupFixtures(request, token, fixtures);+ }+ });++ test('rechecks canonical Project file text after policy activation', async ({ request }) => {+ const token = await loginAdmin(request);+ const suffix = randomUUID();+ const marker = `E2E-PROJECT-CANONICAL-CONTENT-${suffix}`;+ const label = 'E2E Project canonical file';+ const fixtures: StoredFixtures = { conversationIds: [], agentIds: [] };+ let projectId: string | undefined;+ try {+ await restoreRuntimeFilters(request, token);+ const agent = await createAgent(request, token, fixtures, suffix, {+ tools: ['file_search'],+ });+ const agentId = requireString(agent.id, 'Project file-search Agent id');+ const uploaded = await requestResult(request, {+ path: '/api/files',+ token,+ method: 'POST',+ multipart: {+ endpoint: MOCK_ENDPOINTS[0].label,+ endpointType: 'custom',+ message_file: 'true',+ tool_resource: 'context',+ file_id: randomUUID(),+ file: {+ name: `project-reference-${suffix}.txt`,+ mimeType: 'text/plain',+ buffer: Buffer.from(marker),+ },+ },+ });+ expectSuccess(uploaded, 200);+ const file = asObject(uploaded.body);+ fixtures.file = {+ file_id: requireString(file.file_id, 'Project reference file id'),+ filepath: requireString(file.filepath, 'Project reference file path'),+ };+ /** The external RAG index is not needed to test pre-search admission. */+ await withMongo(async (db) => {+ await db+ .collection('files')+ .updateOne(+ { file_id: fixtures.file!.file_id },+ { $set: { embedded: true, context: FileContext.message_attachment } },+ );+ });+ const created = await requestResult(request, {+ path: '/api/projects',+ token,+ method: 'POST',+ data: { name: `Project content policy ${suffix}` },+ });+ expectSuccess(created, 201);+ projectId = requireString(asObject(created.body)._id, 'Project id');+ const attached = await requestResult(request, {+ path: `/api/projects/${projectId}/files`,+ token,+ method: 'POST',+ data: { file_id: fixtures.file.file_id },+ });+ expectSuccess(attached, 200);+ const selectors: MongoSnapshotSelector[] = [+ { key: 'file', collection: 'files', filter: { file_id: fixtures.file.file_id } },+ ];+ const before = await captureMongoSnapshot(selectors);+ await setRuntimeFilters(request, token, {+ files: {+ pii: {+ fields: ['extracted_text'],+ starterPatterns: [],+ customPatterns: [{ id: `project-file-${suffix}`, label, regex: marker }],+ uninspectable: 'block',+ },+ },+ } as FiltersConfig);+ const preview = await requestResult(request, {+ path: `/api/files/${fixtures.file.file_id}/preview`,+ token,+ });+ expectStoredMarker(preview, marker);+ const messageId = randomUUID();+ const started = await requestResult(request, {+ path: '/api/agents/chat/agents',+ token,+ method: 'POST',+ data: {+ text: 'Use the Project references for this response.',+ sender: 'User',+ clientTimestamp: new Date().toISOString(),+ isCreatedByUser: true,+ parentMessageId: NO_PARENT,+ conversationId: 'new',+ messageId,+ responseMessageId: `${messageId}_response`,+ endpoint: 'agents',+ endpointType: 'agents',+ agent_id: agentId,+ chatProjectId: projectId,+ files: [],+ isTemporary: false,+ isRegenerate: false,+ error: false,+ },+ });+ fixtures.conversationIds.push(+ await expectAsyncFilterStreamError(request, token, started, label, marker),+ );+ expect(await captureMongoSnapshot(selectors)).toEqual(before);+ } finally {+ await restoreRuntimeFilters(request, token);+ if (projectId) {+ await requestResult(request, {+ path: `/api/projects/${projectId}`,+ token,+ method: 'DELETE',+ });+ }+ if (fixtures.file) {+ await withMongo(async (db) => {+ await db+ .collection('files')+ .updateOne({ file_id: fixtures.file!.file_id }, { $unset: { embedded: '' } });+ });+ }+ await cleanupFixtures(request, token, fixtures);+ }+ });+test('rechecks a provider-backed Assistant created before policy activation', async ({request,}) => {diff --git a/e2e/specs/mock/enforced-model-specs.spec.ts b/e2e/specs/mock/enforced-model-specs.spec.tsindex d8f9ad1abb..704509bb61 100644--- a/e2e/specs/mock/enforced-model-specs.spec.ts+++ b/e2e/specs/mock/enforced-model-specs.spec.ts@@ -4,6 +4,7 @@ import type { Page } from '@playwright/test';import {MOCK_ENDPOINTS,NEW_CHAT_PATH,+ escapeRegExp,getAccessToken,messagesView,replyPrompt,@@ -31,7 +32,7 @@ async function createProject(page: Page, name: string): Promise<string> {await dialog.getByRole('textbox', { name: 'Project name' }).fill(name);await dialog.getByRole('button', { name: 'Create project' }).click();- await expect(page.getByRole('heading', { name })).toBeVisible();+ await expect(page.getByRole('heading', { name: new RegExp(escapeRegExp(name)) })).toBeVisible();const projectId = new URL(page.url()).pathname.split('/projects/')[1];expect(projectId).toBeTruthy();return projectId;diff --git a/e2e/specs/mock/projects.spec.ts b/e2e/specs/mock/projects.spec.tsindex a336a94d3e..725599e48b 100644--- a/e2e/specs/mock/projects.spec.ts+++ b/e2e/specs/mock/projects.spec.ts@@ -1,6 +1,12 @@import { expect, test } from '@playwright/test';import type { Page } from '@playwright/test';-import { MOCK_ENDPOINTS, mockReply, selectMockEndpoint, sendMessage } from './helpers';+import {+ MOCK_ENDPOINTS,+ escapeRegExp,+ mockReply,+ selectMockEndpoint,+ sendMessage,+} from './helpers';/*** Creates a project from the all-projects page and returns its id.@@ -14,7 +20,7 @@ async function createProject(page: Page, name: string): Promise<string> {await dialog.getByRole('textbox', { name: 'Project name' }).fill(name);await dialog.getByRole('button', { name: 'Create project' }).click();- await expect(page.getByRole('heading', { name })).toBeVisible();+ await expect(page.getByRole('heading', { name: new RegExp(escapeRegExp(name)) })).toBeVisible();const projectId = new URL(page.url()).pathname.split('/projects/')[1];expect(projectId).toBeTruthy();return projectId;@@ -23,16 +29,222 @@ async function createProject(page: Page, name: string): Promise<string> {const uniqueName = (prefix: string) => `${prefix} ${Date.now()}-${Math.floor(Math.random() * 1e4)}`;test.describe('chat projects', () => {- test('creates a project and lists it on the all-projects page', async ({ page }) => {+ test('creates a project with full-width instructions when RAG is disabled', async ({ page }) => {test.setTimeout(60000);const name = uniqueName('E2E Project');+ await page.route(+ (url) => url.pathname === '/api/config',+ async (route) => {+ const response = await route.fetch();+ await route.fulfill({+ response,+ json: { ...(await response.json()), ragEnabled: false },+ });+ },+ );await createProject(page, name);+ await expect(page.getByRole('region', { name: 'Files', exact: true })).toHaveCount(0);+ const instructions = page.getByRole('region', { name: 'Instructions', exact: true });+ const widths = await instructions.evaluate((element) => {+ const parent = element.parentElement!;+ const padding = getComputedStyle(parent);+ return {+ instructions: element.getBoundingClientRect().width,+ /** The gutter that separates the column from the workspace separator lives on+ * this wrapper, so "full width" means the wrapper's content box. */+ available:+ parent.getBoundingClientRect().width -+ Number.parseFloat(padding.paddingLeft) -+ Number.parseFloat(padding.paddingRight),+ };+ });+ expect(widths.instructions).toBeCloseTo(widths.available, 0);++ const header = page.getByRole('main').locator('header');+ const newChat = await header.getByRole('button', { name: /^New chat in / }).boundingBox();+ const options = await header+ .getByRole('button', { name: 'Project options', exact: true })+ .boundingBox();+ expect(newChat!.x + newChat!.width).toBeLessThan(options!.x);+ expect(newChat!.y + newChat!.height / 2).toBeCloseTo(options!.y + options!.height / 2, 0);await page.goto('/projects', { timeout: 10000 });await expect(page.getByRole('button', { name }).first()).toBeVisible();});+ test('hands keyboard focus from the file menu to the picker and back', async ({ page }) => {+ await page.route(+ (url) => url.pathname === '/api/config',+ async (route) => {+ const response = await route.fetch();+ await route.fulfill({+ response,+ json: { ...(await response.json()), ragEnabled: true },+ });+ },+ );+ await createProject(page, uniqueName('E2E File Picker'));+ const addFiles = page.getByRole('button', { name: 'Add files', exact: true });+ await addFiles.focus();+ await page.keyboard.press('ArrowDown');+ await expect(page.getByRole('menuitem', { name: 'Upload from device' })).toBeFocused();+ await page.keyboard.press('End');+ await expect(page.getByRole('menuitem', { name: 'Choose from your files' })).toBeFocused();+ await page.keyboard.press('Enter');+ const picker = page.getByRole('dialog');+ await expect(picker.locator(':focus')).toHaveCount(1);+ await page.keyboard.press('Escape');+ await expect(picker).toBeHidden();+ await expect(page.getByRole('menuitem', { name: 'Choose from your files' })).toBeFocused();+ await page.keyboard.press('Escape');+ await expect(addFiles).toBeFocused();+ });++ test('edits long project metadata inline without overflowing mobile layouts', async ({+ page,+ }) => {+ const initialName = uniqueName('Inline project');+ await createProject(page, initialName);+ await page.setViewportSize({ width: 320, height: 844 });+ /** The workspace edits metadata in place: its title is the control that opens the+ * editor, and the options menu carries only destructive actions. */+ await page+ .getByRole('main')+ .getByRole('heading', { name: new RegExp(escapeRegExp(initialName)) })+ .getByRole('button', { name: new RegExp(escapeRegExp(initialName)) })+ .click();++ const nameInput = page.getByRole('textbox', { name: 'Project name', exact: true });+ await expect(nameInput).toBeFocused();+ await expect(page.getByRole('dialog')).toHaveCount(0);+ const longName = uniqueName('Inline').padEnd(100, 'x');+ const longDescription = 'd'.repeat(1000);+ await nameInput.fill(longName);+ await page.getByRole('textbox', { name: /^Description/ }).fill(longDescription);+ await page.getByRole('button', { name: 'Save', exact: true }).click();+ await expect(+ page.getByRole('heading', { name: new RegExp(escapeRegExp(longName)) }),+ ).toBeVisible();+ await page.reload();++ const title = page+ .getByRole('heading', { name: new RegExp(escapeRegExp(longName)) })+ .getByText(longName);+ await expect(title).toBeVisible();+ const mobileTitle = await title.evaluate((element) => ({+ height: element.getBoundingClientRect().height,+ lineHeight: Number.parseFloat(getComputedStyle(element).lineHeight),+ }));+ expect(mobileTitle.height).toBeLessThanOrEqual(mobileTitle.lineHeight * 2 + 1);+ expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(+ 320,+ );++ await page.getByRole('button', { name: new RegExp(escapeRegExp(longDescription)) }).click();+ await expect(page.getByRole('textbox', { name: /^Description/ })).toHaveValue(longDescription);+ await page.getByRole('textbox', { name: 'Project name', exact: true }).fill('Unsaved change');+ await page.keyboard.press('Escape');+ await expect(+ page.getByRole('heading', { name: new RegExp(escapeRegExp(longName)) }),+ ).toBeVisible();++ await page.setViewportSize({ width: 1280, height: 900 });+ /** The workspace swaps its stacked phone layout for resizable panels at the+ * breakpoint, remounting the title, and the header's sidebar toggle leaves in+ * the same commit; measure only once the desktop title is the one rendered. */+ await expect(+ page.getByRole('main').getByRole('button', { name: 'Open sidebar', exact: true }),+ ).toHaveCount(0);+ const desktopTitle = await title.evaluate((element) => ({+ height: element.getBoundingClientRect().height,+ lineHeight: Number.parseFloat(getComputedStyle(element).lineHeight),+ }));+ expect(desktopTitle.height).toBeLessThanOrEqual(desktopTitle.lineHeight + 1);++ await page.setViewportSize({ width: 390, height: 844 });+ /** A phone arrives at phone width: the mobile drawer registers its slide on load, and+ * crossing back from desktop without a reload leaves it on the desktop toggle path. */+ await page.reload();+ await page.getByRole('main').getByRole('button', { name: 'All projects', exact: true }).click();+ await expect(page.locator('article').filter({ hasText: longName })).toBeVisible();+ expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(+ 390,+ );++ await page.getByRole('main').getByRole('button', { name: 'Open sidebar', exact: true }).click();+ /** The drawer commits its open state in a transition after the slide starts, and that+ * commit moves focus to its close button (`mobile/Header.tsx`), which would close a+ * row menu opened ahead of it; wait for the handoff before opening one. */+ await expect(page.getByTestId('close-sidebar-button')).toBeFocused();+ await page+ .locator('li')+ .filter({ has: page.getByRole('button', { name: longName, exact: true }) })+ .getByRole('button', { name: 'More options', exact: true })+ .click();+ await page.getByRole('menuitem', { name: 'Edit project', exact: true }).click();+ await expect(nameInput).toBeFocused();+ await expect(nameInput).toHaveValue(longName);+ });++ test('persists workspace instructions and exposes a read-only project badge', async ({+ page,+ }) => {+ test.setTimeout(120000);+ const name = uniqueName('E2E Project');+ const projectId = await createProject(page, name);+ const guidance = 'project-guidance-token';++ await page.getByRole('button', { name: 'Edit instructions' }).click();+ const instructionsDialog = page.getByRole('dialog');+ await instructionsDialog+ .getByRole('textbox', { name: 'Workspace instructions' })+ .fill(`Always follow ${guidance} when answering.`);+ await instructionsDialog.getByRole('button', { name: 'Save' }).click();+ await expect(instructionsDialog).toBeHidden();+ await expect(page.getByRole('button', { name: 'Edit instructions' })).toBeFocused();+ await page.goto(`/c/new?projectId=${projectId}`, { timeout: 10000 });+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);+ await sendMessage(page, `E2E_ASSERT_PROJECT_CONTEXT:${guidance}`);+ const transcript = page.getByTestId('screenshot-target');+ await expect(+ transcript.getByText(`E2E project context assertion passed: ${guidance}`),+ ).toBeVisible({+ timeout: 20000,+ });+ await expect(page.getByRole('link', { name: `Open ${name} workspace` })).toBeVisible();++ const conversationUrl = page.url();+ await page.goto(`/projects/${projectId}`, { timeout: 10000 });+ await page.getByRole('button', { name: 'Edit instructions' }).click();+ const updatedDialog = page.getByRole('dialog');+ const updatedGuidance = 'project-updated-guidance-token';+ await updatedDialog+ .getByRole('textbox', { name: 'Workspace instructions' })+ .fill(`Use ${updatedGuidance} for future turns.`);+ await updatedDialog.getByRole('button', { name: 'Save' }).click();+ await expect(updatedDialog).toBeHidden();+ await page.goto(conversationUrl, { timeout: 10000 });+ await sendMessage(page, `E2E_ASSERT_PROJECT_CONTEXT:${updatedGuidance} ${guidance}`);+ await expect(+ transcript.getByText(`E2E project context assertion passed: ${updatedGuidance}`),+ ).toBeVisible({ timeout: 20000 });+ await page.goto(`/projects/${projectId}`, { timeout: 10000 });+ await page.getByRole('button', { name: 'Edit instructions' }).click();+ const clearDialog = page.getByRole('dialog');+ await clearDialog.getByRole('textbox', { name: 'Workspace instructions' }).fill('');+ await clearDialog.getByRole('button', { name: 'Save' }).click();+ await expect(clearDialog).toBeHidden();+ await page.goto(conversationUrl, { timeout: 10000 });+ await sendMessage(page, `E2E_ASSERT_PROJECT_CONTEXT:- ${updatedGuidance}`);+ await expect(transcript.getByText('E2E project context assertion passed: -')).toBeVisible({+ timeout: 20000,+ });++ await page.reload({ timeout: 10000 });+ await expect(page).toHaveURL(conversationUrl);+ await expect(page.getByRole('link', { name: `Open ${name} workspace` })).toBeVisible();+ });test('starts a project-scoped chat and persists it under the project', async ({ page }) => {test.setTimeout(120000);const name = uniqueName('E2E Project');diff --git a/e2e/specs/mock/scenarios/project-access.spec.ts b/e2e/specs/mock/scenarios/project-access.spec.tsnew file mode 100644index 0000000000..e2f6f745b3--- /dev/null+++ b/e2e/specs/mock/scenarios/project-access.spec.ts@@ -0,0 +1,508 @@+import { randomUUID } from 'crypto';+import { expect, request as playwrightRequest, test } from '@playwright/test';+import type { APIRequestContext, APIResponse } from '@playwright/test';+import { ObjectId } from 'mongodb';+import cleanupUser from '../../../setup/cleanupUser';+import { getPrimaryE2EUser, getSecondaryE2EUser } from '../../../setup/users.mock';+import type { User } from '../../../types';+import {+ deleteConversations,+ deleteMessagesByConversation,+ seedConversations,+ withMongo,+} from '../db';+import { loginAdmin } from '../content-filters.helpers';++const NO_PARENT = '00000000-0000-0000-0000-000000000000';+// Project reads and file reads map an owner-scoped miss to this 404 body+// (packages/api/src/projects/handlers.ts:24,198-205,250-260,274-292).+const PROJECT_NOT_FOUND = 'Project not found';++type ProjectResponse = {+ _id?: string;+ name?: string;+ instructions?: string;+ file_ids?: string[];+};++type UserDocument = {+ _id: ObjectId;+ tenantId?: string;+};++type ConversationDocument = {+ conversationId?: string;+};++type ProjectFileView = {+ file_id?: string;+ availability?: string;+};++type ProjectConversationsResponse = {+ conversations?: Array<{ conversationId?: string; chatProjectId?: string }>;+ nextCursor?: string | null;+};++function requireProjectId(project: ProjectResponse): string {+ if (typeof project._id !== 'string' || project._id.length === 0) {+ throw new Error('Project response did not include an id');+ }+ return project._id;+}++async function responseDetails(response: APIResponse): Promise<{ status: number; text: string }> {+ const details = { status: response.status(), text: await response.text() };+ await response.dispose();+ return details;+}++async function createProject(+ request: APIRequestContext,+ token: string,+ name: string,+ instructions: string,+): Promise<string> {+ const response = await request.post('/api/projects', {+ headers: { Authorization: `Bearer ${token}` },+ data: { name, instructions },+ failOnStatusCode: false,+ });+ // The projects router mounts this handler at POST /api/projects and the handler returns 201+ // with the created project (api/server/routes/projects.js:21-22; packages/api/src/projects/handlers.ts:151-163).+ expect(response.status()).toBe(201);+ const project = (await response.json()) as ProjectResponse;+ await response.dispose();+ return requireProjectId(project);+}++async function registerAndLoginSecondary(+ baseURL: string,+ user: User,+ tenantId: string,+): Promise<{ api: APIRequestContext; token: string }> {+ await cleanupUser(user);+ const api = await playwrightRequest.newContext({+ baseURL,+ storageState: { cookies: [], origins: [] },+ extraHTTPHeaders: { 'X-Tenant-Id': tenantId },+ });++ const register = await api.post('/api/auth/register', {+ data: {+ email: user.email,+ name: user.name,+ password: user.password,+ confirm_password: user.password,+ },+ failOnStatusCode: false,+ });+ expect(register.ok()).toBeTruthy();+ await register.dispose();++ const login = await api.post('/api/auth/login', {+ data: { email: user.email, password: user.password },+ failOnStatusCode: false,+ });+ expect(login.ok()).toBeTruthy();+ const payload = (await login.json()) as { token?: unknown };+ await login.dispose();+ if (typeof payload.token !== 'string' || payload.token.length === 0) {+ await api.dispose();+ throw new Error('Secondary login response did not include a bearer token');+ }+ return { api, token: payload.token };+}++async function seedProjectFile({+ fileId,+ filename,+ ownerEmail,+ text,+}: {+ fileId: string;+ filename: string;+ ownerEmail: string;+ text: string;+}): Promise<void> {+ await withMongo(async (db) => {+ const owner = await db.collection<UserDocument>('users').findOne({ email: ownerEmail });+ if (!owner) {+ throw new Error(`Expected project owner ${ownerEmail} to exist`);+ }+ const now = new Date();+ await db.collection('files').insertOne({+ user: owner._id,+ file_id: fileId,+ bytes: Buffer.byteLength(text),+ filename,+ filepath: `/tmp/${fileId}.txt`,+ object: 'file',+ embedded: true,+ context: 'message_attachment',+ type: 'text/plain',+ text,+ textFormat: 'text',+ status: 'ready',+ usage: 0,+ source: 'local',+ ...(owner.tenantId ? { tenantId: owner.tenantId } : {}),+ createdAt: now,+ updatedAt: now,+ });+ });+}++async function deleteSeededFile(fileId: string): Promise<void> {+ await withMongo(async (db) => {+ await db.collection('files').deleteMany({ file_id: fileId });+ });+}++async function conversationIdsForUser(email: string): Promise<string[]> {+ return withMongo(async (db) => {+ const user = await db.collection<UserDocument>('users').findOne({ email });+ if (!user) {+ throw new Error(`Expected conversation owner ${email} to exist`);+ }+ const userId = user._id.toString();+ const conversations = await db+ .collection<ConversationDocument & { user?: unknown }>('conversations')+ .find({ $or: [{ user: userId }, { user: user._id }] })+ .project({ _id: 0, conversationId: 1 })+ .toArray();+ return conversations+ .map((conversation) => conversation.conversationId)+ .filter((conversationId): conversationId is string => typeof conversationId === 'string')+ .sort();+ });+}++function assertNoProjectSecrets(text: string, secrets: string[]): void {+ for (const secret of secrets) {+ expect(text).not.toContain(secret);+ }+}++test.describe('project access', () => {+ test('a user from another tenant sees 404 for a project, its files and its file candidates @scenario:other-tenant-user-gets-404-for-project-and-files', async ({+ request,+ baseURL,+ }) => {+ test.setTimeout(60000);+ if (typeof baseURL !== 'string') {+ throw new Error('baseURL must be configured for project access tests');+ }++ const owner = getPrimaryE2EUser();+ const secondary = getSecondaryE2EUser();+ const suffix = randomUUID();+ const projectName = `Cross-tenant project ${suffix}`;+ const instructions = `Private project instructions ${suffix}`;+ const fileId = `cross-tenant-file-${suffix}`;+ const filename = `private-${suffix}.txt`;+ const ownerConversationId = randomUUID();+ const secondaryConversationId = randomUUID();+ const otherTenantId = `e2e-project-access-${suffix}`;+ const token = await loginAdmin(request);+ let projectId: string | undefined;+ let secondaryApi: APIRequestContext | undefined;+ try {+ projectId = await createProject(request, token, projectName, instructions);++ await seedProjectFile({+ fileId,+ filename,+ ownerEmail: owner.email,+ text: `Private file contents ${suffix}`,+ });+ const attach = await request.post(`/api/projects/${projectId}/files`, {+ headers: { Authorization: `Bearer ${token}` },+ data: { file_id: fileId },+ failOnStatusCode: false,+ });+ // addProjectFile returns 200 with the updated project on success+ // (api/server/routes/projects.js:26; packages/api/src/projects/handlers.ts:314-329).+ expect(attach.status()).toBe(200);+ await attach.dispose();++ await seedConversations(owner.email, [+ {+ conversationId: ownerConversationId,+ title: `Owner chat ${suffix}`,+ updatedAt: new Date(),+ },+ ]);+ const secondaryAuth = await registerAndLoginSecondary(baseURL, secondary, otherTenantId);+ const foreignApi = secondaryAuth.api;+ const foreignToken = secondaryAuth.token;+ secondaryApi = foreignApi;+ // Register/login creates the secondary user in the per-test tenant via X-Tenant-Id above.+ // Store its API context before the test's remaining assertions so the outer finally always+ // disposes it and removes the secondary user even when a later assertion fails.+ await seedConversations(secondary.email, [+ {+ conversationId: secondaryConversationId,+ title: `Secondary chat ${suffix}`,+ updatedAt: new Date(),+ },+ ]);+ const secretValues = [projectName, instructions, fileId, filename];+ const foreignProject = await responseDetails(+ await foreignApi.get(`/api/projects/${projectId}`, {+ headers: { Authorization: `Bearer ${foreignToken}` },+ failOnStatusCode: false,+ }),+ );+ // Project reads are owner/tenant scoped and return the same 404 body without project data+ // (api/server/routes/projects.js:28; packages/api/src/projects/handlers.ts:196-210).+ expect(foreignProject.status, foreignProject.text).toBe(404);+ expect(JSON.parse(foreignProject.text)).toEqual({ error: PROJECT_NOT_FOUND });+ assertNoProjectSecrets(foreignProject.text, secretValues);++ const foreignFiles = await responseDetails(+ await foreignApi.get(`/api/projects/${projectId}/files`, {+ headers: { Authorization: `Bearer ${foreignToken}` },+ failOnStatusCode: false,+ }),+ );+ // Project file listing is owner/tenant scoped and returns the same 404 body+ // (api/server/routes/projects.js:25; packages/api/src/projects/handlers.ts:250-270).+ expect(foreignFiles.status, foreignFiles.text).toBe(404);+ expect(JSON.parse(foreignFiles.text)).toEqual({ error: PROJECT_NOT_FOUND });+ assertNoProjectSecrets(foreignFiles.text, secretValues);++ const foreignAvailable = await responseDetails(+ await foreignApi.get(`/api/projects/${projectId}/files/available`, {+ headers: { Authorization: `Bearer ${foreignToken}` },+ failOnStatusCode: false,+ }),+ );+ // Available-file candidates use the same owner/tenant project check and 404 body+ // (api/server/routes/projects.js:24; packages/api/src/projects/handlers.ts:274-292).+ expect(foreignAvailable.status, foreignAvailable.text).toBe(404);+ expect(JSON.parse(foreignAvailable.text)).toEqual({ error: PROJECT_NOT_FOUND });+ assertNoProjectSecrets(foreignAvailable.text, secretValues);++ const foreignAssignment = await responseDetails(+ await foreignApi.put('/api/projects/conversations/' + secondaryConversationId, {+ headers: { Authorization: `Bearer ${foreignToken}` },+ data: { projectId },+ failOnStatusCode: false,+ }),+ );+ // This route delegates to assignConversationToProject (api/server/routes/projects.js:19,23).+ // Its database method checks conversation ownership before project ownership+ // (packages/data-schemas/src/methods/chatProject.ts:610-635), so this foreign caller+ // legitimately receives the non-leaking conversation miss from the handler+ // (packages/api/src/projects/handlers.ts:166-190).+ expect(foreignAssignment.status, foreignAssignment.text).toBe(404);+ expect(JSON.parse(foreignAssignment.text)).toEqual({ error: 'Conversation not found' });+ assertNoProjectSecrets(foreignAssignment.text, secretValues);++ const foreignConversations = await responseDetails(+ await foreignApi.get(`/api/convos?projectId=${encodeURIComponent(projectId)}`, {+ headers: { Authorization: `Bearer ${foreignToken}` },+ failOnStatusCode: false,+ }),+ );+ // The conversations route returns 200 and filters by the authenticated user before the+ // project id (api/server/routes/convos.js:146-180; packages/data-schemas/src/methods/conversation.ts:2699-2722).+ expect(foreignConversations.status, foreignConversations.text).toBe(200);+ const foreignConversationBody = JSON.parse(+ foreignConversations.text,+ ) as ProjectConversationsResponse;+ expect(foreignConversationBody.conversations).toEqual([]);+ assertNoProjectSecrets(foreignConversations.text, secretValues);++ const ownerAssignment = await request.put(+ `/api/projects/conversations/${ownerConversationId}`,+ {+ headers: { Authorization: `Bearer ${token}` },+ data: { projectId },+ failOnStatusCode: false,+ },+ );+ // Successful assignment returns 200 from the same handler (packages/api/src/projects/handlers.ts:177-186).+ expect(ownerAssignment.status()).toBe(200);+ await ownerAssignment.dispose();++ const ownerProject = await request.get(`/api/projects/${projectId}`, {+ headers: { Authorization: `Bearer ${token}` },+ failOnStatusCode: false,+ });+ // A project read returns the owner-scoped project body with status 200+ // (api/server/routes/projects.js:28; packages/api/src/projects/handlers.ts:196-207).+ expect(ownerProject.status()).toBe(200);+ const ownerProjectBody = (await ownerProject.json()) as ProjectResponse;+ expect(ownerProjectBody.name).toBe(projectName);+ expect(ownerProjectBody.instructions).toBe(instructions);+ expect(ownerProjectBody.file_ids).toContain(fileId);+ await ownerProject.dispose();++ const ownerFiles = await request.get(`/api/projects/${projectId}/files`, {+ headers: { Authorization: `Bearer ${token}` },+ failOnStatusCode: false,+ });+ // Owner-scoped project file listing returns 200 (api/server/routes/projects.js:25;+ // packages/api/src/projects/handlers.ts:250-267).+ expect(ownerFiles.status()).toBe(200);+ const ownerFileBody = (await ownerFiles.json()) as ProjectFileView[];+ expect(ownerFileBody.some((file) => file.file_id === fileId)).toBe(true);+ await ownerFiles.dispose();++ const ownerAvailable = await request.get(`/api/projects/${projectId}/files/available`, {+ headers: { Authorization: `Bearer ${token}` },+ failOnStatusCode: false,+ });+ // Available project files return 200 after the owner/tenant check+ // (api/server/routes/projects.js:24; packages/api/src/projects/handlers.ts:286-303).+ expect(ownerAvailable.status()).toBe(200);+ await ownerAvailable.dispose();++ const ownerConversations = await request.get(+ `/api/convos?projectId=${encodeURIComponent(projectId)}`,+ {+ headers: { Authorization: `Bearer ${token}` },+ failOnStatusCode: false,+ },+ );+ // The conversations route serializes a successful owner query as 200+ // (api/server/routes/convos.js:168-180).+ expect(ownerConversations.status()).toBe(200);+ const ownerConversationBody =+ (await ownerConversations.json()) as ProjectConversationsResponse;+ expect(+ ownerConversationBody.conversations?.some(+ (conversation) => conversation.conversationId === ownerConversationId,+ ),+ ).toBe(true);++ await ownerConversations.dispose();+ } finally {+ if (projectId && token) {+ const deleted = await request.delete(`/api/projects/${projectId}`, {+ headers: { Authorization: `Bearer ${token}` },+ failOnStatusCode: false,+ });+ await deleted.dispose();+ }+ await deleteMessagesByConversation([ownerConversationId, secondaryConversationId]);+ await deleteConversations([ownerConversationId, secondaryConversationId]);+ await deleteSeededFile(fileId);+ if (secondaryApi) {+ await secondaryApi.dispose();+ }+ await cleanupUser(secondary);+ }+ });++ test('a turn naming a deleted project fails with 404 and leaves no error conversation @scenario:turn-on-deleted-project-404s-without-error-turn', async ({+ request,+ }) => {+ test.setTimeout(60000);+ const token = await loginAdmin(request);+ const suffix = randomUUID();+ const projectName = `Deleted project ${suffix}`;+ const agentName = `Deleted project agent ${suffix}`;+ const clientRequestId = `deleted-project-turn-${suffix}`;+ const messageId = randomUUID();+ let projectId: string | undefined;+ let agentId: string | undefined;++ try {+ projectId = await createProject(request, token, projectName, 'Deleted project instructions');+ const agentResponse = await request.post('/api/agents', {+ headers: { Authorization: `Bearer ${token}` },+ data: {+ name: agentName,+ description: 'Agent for deleted-project admission coverage.',+ instructions: 'Use safe deterministic instructions.',+ provider: 'Mock Provider A',+ model: 'mock-model-a',+ model_parameters: {},+ tools: [],+ conversation_starters: [],+ },+ failOnStatusCode: false,+ });+ // Agent creation is mounted at POST /agents and returns 201 on success+ // (api/server/routes/agents/v1.js:42-47; api/server/controllers/agents/v1.js:913-914).+ expect(agentResponse.status()).toBe(201);+ const agent = (await agentResponse.json()) as { id?: unknown };+ await agentResponse.dispose();+ if (typeof agent.id !== 'string' || agent.id.length === 0) {+ throw new Error('Agent response did not include an id');+ }+ agentId = agent.id;++ const deleted = await request.delete(`/api/projects/${projectId}`, {+ headers: { Authorization: `Bearer ${token}` },+ failOnStatusCode: false,+ });+ // Project deletion returns 200 when the owner-scoped delete succeeds+ // (api/server/routes/projects.js:30; packages/api/src/projects/handlers.ts:363-374).+ expect(deleted.status()).toBe(200);++ const beforeConversationIds = await conversationIdsForUser(getPrimaryE2EUser().email);+ const failedTurn = await request.post('/api/agents/chat/agents', {+ headers: { Authorization: `Bearer ${token}` },+ data: {+ text: 'This turn must not create an error conversation.',+ sender: 'User',+ clientTimestamp: new Date().toISOString(),+ isCreatedByUser: true,+ parentMessageId: NO_PARENT,+ conversationId: 'new',+ clientRequestId,+ messageId,+ responseMessageId: `${messageId}_response`,+ endpoint: 'agents',+ endpointType: 'agents',+ agent_id: agentId,+ chatProjectId: projectId,+ files: [],+ isTemporary: false,+ isRegenerate: false,+ error: false,+ generationProtocolVersion: 2,+ },+ failOnStatusCode: false,+ });+ // resolveChatProjectContext signals the unavailable sentinel (packages/api/src/projects/context.ts:42,101-107).+ // getInitializationFailure maps it to status 404 and this error string, then+ // sendGenerationJson spreads that status and appends generationProtocolVersion+ // (api/server/controllers/agents/request.js:96-118).+ expect(failedTurn.status()).toBe(404);+ const failedBody = (await failedTurn.json()) as unknown;+ expect(failedBody).toEqual({+ error: 'Conversation context unavailable',+ generationProtocolVersion: 2,+ status: 404,+ });++ const afterConversationIds = await conversationIdsForUser(getPrimaryE2EUser().email);+ expect(afterConversationIds).toEqual(beforeConversationIds);+ await withMongo(async (db) => {+ expect(await db.collection('messages').countDocuments({ messageId })).toBe(0);+ });+ } finally {+ if (agentId) {+ const deletedAgent = await request.delete(`/api/agents/${encodeURIComponent(agentId)}`, {+ headers: { Authorization: `Bearer ${token}` },+ failOnStatusCode: false,+ });+ await deletedAgent.dispose();+ }+ // Cleanup repeats the owner-scoped delete and is intentionally safe after the project was+ // already deleted (api/server/routes/projects.js:30; packages/api/src/projects/handlers.ts:363-374).+ if (projectId) {+ const deletedProject = await request.delete(`/api/projects/${projectId}`, {+ headers: { Authorization: `Bearer ${token}` },+ failOnStatusCode: false,+ });+ await deletedProject.dispose();+ }+ }+ });+});diff --git a/e2e/specs/mock/scenarios/project-context.spec.ts b/e2e/specs/mock/scenarios/project-context.spec.tsnew file mode 100644index 0000000000..bd6e8563fb--- /dev/null+++ b/e2e/specs/mock/scenarios/project-context.spec.ts@@ -0,0 +1,293 @@+import { randomUUID } from 'crypto';+import { expect, test } from '@playwright/test';+import type { TMessage } from 'librechat-data-provider';+import {+ getAccessToken,+ MOCK_ENDPOINTS,+ selectMockEndpoint,+ sendMessageAndWaitForCompletion,+} from '../helpers';++type ProjectResponse = {+ _id?: string;+};++type ConversationResponse = {+ chatProjectId?: string | null;+};++type ConversationListResponse = {+ conversations?: Array<{ conversationId?: string }>;+};++type AssistantResponse = {+ id?: string;+};++type ProviderRequest = {+ path: string;+ body: {+ assistant_id?: string;+ additional_instructions?: string;+ };+};++type ProviderRequestLog = {+ requests: ProviderRequest[];+};++const uniqueName = (prefix: string) => `${prefix} ${Date.now()}-${Math.floor(Math.random() * 1e4)}`;++function requireString(value: string | undefined, label: string): string {+ if (!value) {+ throw new Error(`Expected ${label} in API response`);+ }+ return value;+}++function conversationIdFromUrl(url: string): string {+ const conversationId = new URL(url).pathname.match(/^\/c\/([^/]+)\/?$/)?.[1];+ if (!conversationId || conversationId === 'new') {+ throw new Error(`Expected a persisted conversation URL, got ${url}`);+ }+ return decodeURIComponent(conversationId);+}++test.describe('project context scenarios', () => {+ test('project instructions reach the model on the first and a later turn @scenario:project-instructions-apply-to-first-and-later-turns', async ({+ page,+ request,+ }) => {+ test.setTimeout(120000);+ let projectId: string | undefined;+ let conversationId: string | undefined;+ const projectName = uniqueName('Project Context');+ const guidanceToken = `E2E_PROJECT_GUIDANCE_${randomUUID()}`;++ await page.goto('/c/new', { timeout: 10000 });+ const token = await getAccessToken(page);+ const headers = () => ({ Authorization: `Bearer ${requireString(token, 'access token')}` });+ const transcript = page.getByTestId('screenshot-target');+ const projectAssertionFailure = transcript.getByText(/E2E project context assertion failed:/);++ try {+ const created = await request.post('/api/projects', {+ headers: headers(),+ data: {+ name: projectName,+ instructions: `Always follow ${guidanceToken} when answering project questions.`,+ },+ });+ expect(created.status()).toBe(201);+ const project = (await created.json()) as ProjectResponse;+ projectId = requireString(project._id, 'project id');++ await page.goto(`/c/new?projectId=${encodeURIComponent(projectId)}`, { timeout: 10000 });+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);++ await sendMessageAndWaitForCompletion(page, `E2E_ASSERT_PROJECT_CONTEXT:${guidanceToken}`);+ await expect(+ transcript.getByText(`E2E project context assertion passed: ${guidanceToken}`),+ ).toBeVisible({ timeout: 20000 });+ await expect(projectAssertionFailure).toHaveCount(0);++ conversationId = conversationIdFromUrl(page.url());++ await sendMessageAndWaitForCompletion(page, `E2E_ASSERT_PROJECT_CONTEXT:${guidanceToken}`);+ await expect(+ transcript.getByText(`E2E project context assertion passed: ${guidanceToken}`),+ ).toHaveCount(2, { timeout: 20000 });+ await expect(projectAssertionFailure).toHaveCount(0);++ const stored = await request.get(`/api/convos/${encodeURIComponent(conversationId)}`, {+ headers: headers(),+ });+ expect(stored.status()).toBe(200);+ const conversation = (await stored.json()) as ConversationResponse;+ expect(conversation.chatProjectId).toBe(projectId);++ const conversationUrl = page.url();+ await page.reload({ timeout: 10000 });+ await expect(page).toHaveURL(conversationUrl);+ const reloaded = await request.get(`/api/convos/${encodeURIComponent(conversationId)}`, {+ headers: headers(),+ });+ expect(reloaded.status()).toBe(200);+ expect(((await reloaded.json()) as ConversationResponse).chatProjectId).toBe(projectId);+ } finally {+ const cleanup: Promise<unknown>[] = [];+ if (token && conversationId) {+ cleanup.push(+ request.delete('/api/convos', {+ headers: headers(),+ data: { arg: { conversationId } },+ }),+ );+ }+ if (token && projectId) {+ cleanup.push(+ request.delete(`/api/projects/${encodeURIComponent(projectId)}`, {+ headers: headers(),+ }),+ );+ }+ await Promise.allSettled(cleanup);+ }+ });++ test('a project chat keeps its project on a hosted Assistant across turns @scenario:project-chat-stays-in-project-on-hosted-assistant', async ({+ page,+ request,+ }) => {+ test.setTimeout(120000);+ let projectId: string | undefined;+ let assistantId: string | undefined;+ let conversationId: string | undefined;+ const firstGuidance = 'Use the original project policy.';+ const revisedGuidance = 'Use the revised project policy.';++ await page.goto('/c/new', { timeout: 10000 });+ const token = await getAccessToken(page);+ const headers = () => ({ Authorization: `Bearer ${requireString(token, 'access token')}` });++ try {+ const projectResponse = await request.post('/api/projects', {+ headers: headers(),+ data: { name: uniqueName('Hosted Project'), instructions: firstGuidance },+ });+ expect(projectResponse.status()).toBe(201);+ projectId = requireString(+ ((await projectResponse.json()) as ProjectResponse)._id,+ 'project id',+ );++ const assistantResponse = await request.post('/api/assistants/v2', {+ headers: headers(),+ data: {+ endpoint: 'assistants',+ model: 'gpt-4o-mini',+ name: uniqueName('Project Assistant'),+ tools: [],+ },+ });+ expect(assistantResponse.status()).toBe(201);+ assistantId = requireString(+ ((await assistantResponse.json()) as AssistantResponse).id,+ 'assistant id',+ );++ const sendTurn = async (+ currentConversationId: string | null = null,+ parentMessageId = '00000000-0000-0000-0000-000000000000',+ threadId?: string,+ ): Promise<string> => {+ const messageId = randomUUID();+ const response = await request.post('/api/assistants/v2/chat', {+ headers: headers(),+ data: {+ text: 'Apply the project policy.',+ sender: 'User',+ clientTimestamp: new Date().toISOString(),+ isCreatedByUser: true,+ parentMessageId,+ conversationId: currentConversationId,+ messageId,+ responseMessageId: `${messageId}_response`,+ endpoint: 'assistants',+ endpointType: 'assistants',+ model: 'gpt-4o-mini',+ assistant_id: assistantId,+ thread_id: threadId,+ chatProjectId: currentConversationId ? undefined : projectId,+ files: [],+ isTemporary: false,+ isRegenerate: false,+ error: false,+ },+ });+ expect(response.status()).toBe(200);+ const text = await response.text();+ expect(text).toContain('"final":true');+ return text;+ };++ const firstTurn = await sendTurn();+ conversationId = requireString(+ firstTurn.match(/"conversationId":"([^"]+)"/)?.[1],+ 'conversation id',+ );++ const listed = await request.get(`/api/convos?projectId=${encodeURIComponent(projectId)}`, {+ headers: headers(),+ });+ expect(listed.status()).toBe(200);+ const listedConversations = (await listed.json()) as ConversationListResponse;+ expect(+ listedConversations.conversations?.some(+ (conversation) => conversation.conversationId === conversationId,+ ),+ ).toBe(true);+ const stored = await request.get(`/api/convos/${encodeURIComponent(conversationId)}`, {+ headers: headers(),+ });+ expect(stored.status()).toBe(200);+ expect(((await stored.json()) as ConversationResponse).chatProjectId).toBe(projectId);++ const messagesResponse = await request.get(+ `/api/messages/${encodeURIComponent(conversationId)}`,+ { headers: headers() },+ );+ expect(messagesResponse.status()).toBe(200);+ const messages = (await messagesResponse.json()) as TMessage[];+ const userMessage = messages.find((message) => message.isCreatedByUser);+ const reply = messages.find((message) => !message.isCreatedByUser);+ const threadId = requireString(userMessage?.thread_id, 'assistant thread id');+ const replyMessageId = requireString(reply?.messageId, 'assistant reply message id');++ const revised = await request.patch(`/api/projects/${encodeURIComponent(projectId)}`, {+ headers: headers(),+ data: { instructions: revisedGuidance },+ });+ expect(revised.status()).toBe(200);+ await sendTurn(conversationId, replyMessageId, threadId);++ const provider = `http://127.0.0.1:${process.env.E2E_ASSISTANTS_PORT || '8890'}`;+ const recorded = await request.get(`${provider}/__e2e/requests`);+ expect(recorded.status()).toBe(200);+ const history = (await recorded.json()) as ProviderRequestLog;+ const runs = history.requests.filter(+ (entry) => entry.path.endsWith('/runs') && entry.body.assistant_id === assistantId,+ );+ expect(runs).toHaveLength(2);+ expect(runs[0].body.additional_instructions).toContain(firstGuidance);+ expect(runs[1].body.additional_instructions).toContain(revisedGuidance);+ expect(runs[1].body.additional_instructions).not.toContain(firstGuidance);+ } finally {+ const cleanup: Promise<unknown>[] = [];+ if (token && conversationId) {+ cleanup.push(+ request.delete('/api/convos', {+ headers: headers(),+ data: { arg: { conversationId } },+ }),+ );+ }+ if (token && assistantId) {+ cleanup.push(+ request.delete(+ `/api/assistants/v2/${encodeURIComponent(assistantId)}?endpoint=assistants&model=gpt-4o-mini`,+ { headers: headers(), data: { endpoint: 'assistants' } },+ ),+ );+ }+ if (token && projectId) {+ cleanup.push(+ request.delete(`/api/projects/${encodeURIComponent(projectId)}`, {+ headers: headers(),+ }),+ );+ }+ await Promise.allSettled(cleanup);+ }+ });+});diff --git a/e2e/specs/mock/scenarios/project-files-ui.spec.ts b/e2e/specs/mock/scenarios/project-files-ui.spec.tsnew file mode 100644index 0000000000..85fe6de738--- /dev/null+++ b/e2e/specs/mock/scenarios/project-files-ui.spec.ts@@ -0,0 +1,408 @@+import { randomUUID } from 'crypto';+import { ObjectId } from 'mongodb';+import type { APIRequestContext, Locator, Page, Response, Route } from '@playwright/test';+import { expect, test } from '@playwright/test';+import { FileContext } from 'librechat-data-provider';+import { getE2EUser } from '../../../setup/user';+import { withMongo } from '../db';+import { escapeRegExp, getAccessToken, uniqueName } from '../helpers';+import { loginAdmin } from '../content-filters.helpers';++type UserDocument = {+ _id: ObjectId;+ email: string;+ tenantId?: string | null;+};++type UploadedFile = {+ file_id?: string;+};++const CONFIGURED_PROJECT_FILE_LIMIT = 2;++async function getPrimaryUserId(): Promise<string> {+ const owner = await withMongo(async (db) =>+ db+ .collection<UserDocument>('users')+ .findOne({ email: getE2EUser().email }, { projection: { _id: 1 } }),+ );+ if (!owner) {+ throw new Error('The authenticated e2e user was not found while resolving config override');+ }+ return owner._id.toString();+}++/** Creates a project from the all-projects page and returns its id. */+async function createProject(page: Page, name: string): Promise<string> {+ await page.goto('/projects', { timeout: 10000 });+ await page.getByRole('button', { name: 'New project' }).first().click();++ const dialog = page.getByRole('dialog');+ await dialog.getByRole('textbox', { name: 'Project name' }).fill(name);+ await dialog.getByRole('button', { name: 'Create project' }).click();++ await expect(page.getByRole('heading', { name: new RegExp(escapeRegExp(name)) })).toBeVisible();+ const projectId = new URL(page.url()).pathname.split('/projects/')[1];+ expect(projectId).toBeTruthy();+ return projectId;+}++function isFileUpload(response: Response): boolean {+ return (+ response.request().method() === 'POST' && new URL(response.url()).pathname === '/api/files'+ );+}++async function seedProjectFiles(+ projectId: string,+ count: number,+ prefix: string,+ firstFilename?: string,+ associateWithProject = true,+): Promise<{ fileIds: string[]; filenames: string[] }> {+ const fileIds = Array.from({ length: count }, () => randomUUID());+ const filenames = fileIds.map((_, index) =>+ index === 0 && firstFilename ? firstFilename : `${prefix}-${index + 1}.txt`,+ );++ await withMongo(async (db) => {+ const owner = await db.collection<UserDocument>('users').findOne({ email: getE2EUser().email });+ if (!owner) {+ throw new Error('The authenticated e2e user was not found while seeding files');+ }++ const now = new Date();+ await db.collection('files').insertMany(+ fileIds.map((fileId, index) => ({+ _id: new ObjectId(),+ user: owner._id,+ ...(owner.tenantId ? { tenantId: owner.tenantId } : {}),+ file_id: fileId,+ bytes: 2048,+ filename: filenames[index],+ filepath: `/tmp/${fileId}.txt`,+ object: 'file',+ embedded: true,+ type: 'text/plain',+ text: `seeded project file ${index + 1}`,+ textFormat: 'text',+ status: 'ready',+ usage: 0,+ source: 'local',+ context: FileContext.message_attachment,+ createdAt: now,+ updatedAt: now,+ })),+ );+ if (associateWithProject) {+ const result = await db+ .collection('chatprojects')+ .updateOne({ _id: new ObjectId(projectId) }, { $set: { file_ids: fileIds } });+ if (result.matchedCount !== 1) {+ throw new Error(`Project ${projectId} was not found while seeding files`);+ }+ }+ });++ return { fileIds, filenames };+}++async function cleanupProjectAndFiles(+ page: Page,+ request: APIRequestContext,+ projectId: string | undefined,+ fileIds: string[],+ filenames: string[],+): Promise<void> {+ let token: string | undefined;+ try {+ token = await getAccessToken(page);+ } catch {+ token = undefined;+ }++ if (projectId && token) {+ try {+ await request.delete(`/api/projects/${encodeURIComponent(projectId)}`, {+ headers: { Authorization: `Bearer ${token}` },+ });+ } catch {+ // Mongo cleanup below is the final isolation boundary.+ }+ }+ if (fileIds.length > 0 && token) {+ try {+ await request.delete('/api/files', {+ headers: { Authorization: `Bearer ${token}` },+ data: { files: fileIds },+ });+ } catch {+ // Mongo cleanup below is the final isolation boundary.+ }+ }++ await withMongo(async (db) => {+ if (projectId) {+ await db.collection('chatprojects').deleteOne({ _id: new ObjectId(projectId) });+ }+ await db.collection('files').deleteMany({+ $or: [{ file_id: { $in: fileIds } }, { filename: { $in: filenames } }],+ });+ });+}++async function openExistingFilePicker(page: Page): Promise<Locator> {+ await page.getByRole('button', { name: 'Add files', exact: true }).click();+ await page.getByRole('menuitem', { name: 'Choose from your files', exact: true }).click();+ const picker = page.getByRole('dialog');+ await expect(picker).toBeVisible();+ return picker;+}++async function enableProjectFiles(page: Page): Promise<void> {+ await page.route(+ (url) => url.pathname === '/api/config',+ async (route) => {+ const response = await route.fetch();+ await route.fulfill({+ response,+ json: { ...(await response.json()), ragEnabled: true },+ });+ },+ );+}++async function uploadFromDevice(page: Page, files: Array<{ name: string; content: string }>) {+ await page.getByRole('button', { name: 'Add files', exact: true }).click();+ const uploadOption = page.getByRole('menuitem', { name: 'Upload from device', exact: true });+ const uploadResponse = page.waitForResponse(isFileUpload, { timeout: 30000 });+ const [fileChooser] = await Promise.all([page.waitForEvent('filechooser'), uploadOption.click()]);+ await fileChooser.setFiles(+ files.map((file) => ({+ name: file.name,+ mimeType: 'text/plain',+ buffer: Buffer.from(file.content, 'utf8'),+ })),+ );+ return uploadResponse;+}++test.describe('project file workspace UI', () => {+ test('selecting several files at once queues every file up to the project limit and reports the excess @scenario:multi-file-upload-queues-to-capacity-and-reports-excess', async ({+ page,+ request,+ }) => {+ test.setTimeout(120000);+ const token = await loginAdmin(request);+ const userId = await getPrimaryUserId();+ const headers = { Authorization: `Bearer ${token}` };+ let projectId: string | undefined;+ const fileIds: string[] = [];+ const filenames: string[] = [];+ try {+ const override = await request.put(`/api/admin/config/user/${encodeURIComponent(userId)}`, {+ headers,+ data: { overrides: { projects: { maxFiles: CONFIGURED_PROJECT_FILE_LIMIT } } },+ });+ const overrideText = await override.text();+ expect(override.ok(), overrideText).toBe(true);+ await expect+ .poll(+ async () => {+ const configResponse = await request.get('/api/config', {+ headers,+ failOnStatusCode: false,+ });+ const config = (await configResponse.json()) as {+ projects?: { maxFiles?: number };+ };+ return config.projects?.maxFiles;+ },+ { timeout: 30000, intervals: [250, 500, 1000] },+ )+ .toBe(CONFIGURED_PROJECT_FILE_LIMIT);++ await enableProjectFiles(page);+ projectId = await createProject(page, uniqueName('Multi-file project'));+ const seeded = await seedProjectFiles(+ projectId,+ CONFIGURED_PROJECT_FILE_LIMIT - 1,+ uniqueName('capacity-seed'),+ );+ fileIds.push(...seeded.fileIds);+ filenames.push(...seeded.filenames);+ await page.reload({ waitUntil: 'domcontentloaded' });++ const acceptedName = `${uniqueName('accepted')}.txt`;+ const excessName = `${uniqueName('excess')}.txt`;+ const uploadResponse = await uploadFromDevice(page, [+ { name: acceptedName, content: 'accepted project file' },+ { name: excessName, content: 'excess project file' },+ ]);+ expect(uploadResponse.ok()).toBeTruthy();+ const uploaded = (await uploadResponse.json()) as UploadedFile;+ if (uploaded.file_id) {+ fileIds.push(uploaded.file_id);+ }+ filenames.push(acceptedName, excessName);++ await expect(+ page.getByRole('status').filter({+ hasText: 'Could not add 1 selected file(s) because the project is at its file limit.',+ }),+ ).toBeVisible();+ const filesRegion = page.getByRole('region', { name: 'Files', exact: true });+ await expect(+ filesRegion.getByRole('listitem').filter({ hasText: acceptedName }),+ ).toContainText('Ready', { timeout: 30000 });+ await expect(filesRegion.getByRole('listitem').filter({ hasText: excessName })).toHaveCount(+ 0,+ );+ await expect(filesRegion.getByRole('note')).toContainText(+ `up to ${CONFIGURED_PROJECT_FILE_LIMIT} reference files`,+ );++ const serverCheck = await seedProjectFiles(+ projectId,+ 1,+ uniqueName('server-capacity-check'),+ undefined,+ false,+ );+ fileIds.push(...serverCheck.fileIds);+ filenames.push(...serverCheck.filenames);+ const rejectedAssociation = await request.post(+ `/api/projects/${encodeURIComponent(projectId)}/files`,+ {+ headers,+ data: { file_id: serverCheck.fileIds[0] },+ failOnStatusCode: false,+ },+ );+ expect(rejectedAssociation.status()).toBe(409);+ expect(await rejectedAssociation.json()).toEqual({ error: 'Project file limit reached' });+ } finally {+ try {+ await cleanupProjectAndFiles(page, request, projectId, fileIds, filenames);+ } finally {+ const removed = await request.delete(+ `/api/admin/config/user/${encodeURIComponent(userId)}`,+ { headers, failOnStatusCode: false },+ );+ const removedText = await removed.text();+ expect([200, 404], removedText).toContain(removed.status());+ }+ }+ });++ test('the existing-file picker searches by filename and pages through a large history @scenario:file-picker-searches-and-pages-large-history', async ({+ page,+ request,+ }) => {+ test.setTimeout(120000);+ let projectId: string | undefined;+ const fileIds: string[] = [];+ const filenames: string[] = [];+ try {+ await enableProjectFiles(page);+ projectId = await createProject(page, uniqueName('File picker project'));+ const targetName = `${uniqueName('search-target')}.txt`;+ const seeded = await seedProjectFiles(+ projectId,+ 21,+ uniqueName('picker-history'),+ targetName,+ false,+ );+ fileIds.push(...seeded.fileIds);+ filenames.push(...seeded.filenames);+ await page.reload({ waitUntil: 'domcontentloaded' });++ const picker = await openExistingFilePicker(page);+ const results = picker.getByRole('region', { name: 'Choose from your files', exact: true });+ const recentName = seeded.filenames[20];+ if (!recentName) {+ throw new Error('Expected a recent seeded file for the picker page');+ }+ const recentRow = results.getByRole('listitem').filter({ hasText: recentName });+ await expect(recentRow).toBeVisible();+ await expect(recentRow.getByRole('button')).toHaveAccessibleName(+ new RegExp(`${escapeRegExp(recentName)}\\s+2\\.0 KB`),+ );++ const search = picker.getByRole('textbox', { name: 'Search files', exact: true });+ await search.fill(targetName.slice(0, -4));+ const targetRow = results.getByRole('listitem').filter({ hasText: targetName });+ await expect(targetRow).toHaveCount(1);+ await expect(targetRow.getByRole('button')).toHaveAccessibleName(+ new RegExp(escapeRegExp(targetName)),+ );+ await expect(results.getByRole('listitem').filter({ hasText: recentName })).toHaveCount(0);++ await search.fill('');+ const loadMore = picker.getByRole('button', { name: 'Load more', exact: true });+ await expect(loadMore).toBeVisible();+ await loadMore.click();+ await expect(results.getByRole('listitem').filter({ hasText: targetName })).toHaveCount(1);+ } finally {+ await cleanupProjectAndFiles(page, request, projectId, fileIds, filenames);+ }+ });++ test('a rejected file association shows a localized reason and a retry succeeds @scenario:rejected-file-association-shows-reason-and-retry-succeeds', async ({+ page,+ request,+ }) => {+ test.setTimeout(120000);+ let projectId: string | undefined;+ const fileIds: string[] = [];+ const filenames: string[] = [];+ try {+ await enableProjectFiles(page);+ projectId = await createProject(page, uniqueName('Retry project'));+ await page.reload({ waitUntil: 'domcontentloaded' });++ const fileName = `${uniqueName('retry-file')}.txt`;+ const uploadPath = `/api/projects/${encodeURIComponent(projectId)}/files`;+ const failureBody = { error: 'Project file limit reached' };+ const associationMatcher = (url: URL) => url.pathname === uploadPath;+ const failAssociation = async (route: Route) => {+ if (route.request().method() !== 'POST') {+ await route.continue();+ return;+ }+ await route.fulfill({+ status: 409,+ contentType: 'application/json',+ body: JSON.stringify(failureBody),+ });+ };+ await page.route(associationMatcher, failAssociation);++ const uploadResponse = await uploadFromDevice(page, [+ { name: fileName, content: 'retryable project file' },+ ]);+ expect(uploadResponse.ok()).toBeTruthy();+ const uploaded = (await uploadResponse.json()) as UploadedFile;+ if (uploaded.file_id) {+ fileIds.push(uploaded.file_id);+ }+ filenames.push(fileName);++ const row = page.getByRole('listitem').filter({ hasText: fileName });+ await expect(row.getByRole('alert')).toHaveText(+ /This project can use up to \d+ reference files\./,+ { timeout: 30000 },+ );+ await expect(row.getByText(failureBody.error)).toHaveCount(0);+ await expect(row.getByRole('button', { name: 'Retry', exact: true })).toBeVisible();+ await page.unroute(associationMatcher, failAssociation);++ await row.getByRole('button', { name: 'Retry', exact: true }).click();+ await expect(row.getByRole('alert')).toHaveCount(0);+ await expect(row).toContainText('Ready', { timeout: 30000 });+ } finally {+ await cleanupProjectAndFiles(page, request, projectId, fileIds, filenames);+ }+ });+});diff --git a/e2e/specs/mock/scenarios/project-policy.spec.ts b/e2e/specs/mock/scenarios/project-policy.spec.tsnew file mode 100644index 0000000000..492b818f60--- /dev/null+++ b/e2e/specs/mock/scenarios/project-policy.spec.ts@@ -0,0 +1,837 @@+import { ObjectId } from 'mongodb';+import { randomUUID } from 'crypto';+import { expect, test } from '@playwright/test';+import type { APIRequestContext } from '@playwright/test';+import type { FiltersConfig } from 'librechat-data-provider';+import { getPrimaryE2EUser } from '../../../setup/users.mock';+import { withMongo } from '../db';+import { MOCK_ENDPOINTS, RAG_API_BASE } from '../helpers';+import {+ expectContentFilterBlock,+ loginAdmin,+ requestResult,+ restoreRuntimeFilters,+ setRuntimeFilters,+} from '../content-filters.helpers';+import type { RequestResult } from '../content-filters.helpers';++const NO_PARENT = '00000000-0000-0000-0000-000000000000';+type JsonObject = Record<string, unknown>;++function asObject(value: unknown): JsonObject {+ return value != null && typeof value === 'object' && !Array.isArray(value)+ ? (value as JsonObject)+ : {};+}++function requireString(value: unknown, label: string): string {+ if (typeof value !== 'string' || value.length === 0) {+ throw new Error(`${label} must be a non-empty string`);+ }+ return value;+}++function expectSuccess(result: RequestResult, status?: number): void {+ expect(result.ok, result.text).toBe(true);+ if (status != null) {+ expect(result.status, result.text).toBe(status);+ }+}++function pii(id: string, field: string, marker: string) {+ return {+ fields: [field],+ starterPatterns: [],+ customPatterns: [{ id, label: 'E2E policy marker', regex: `^${marker}$` }],+ };+}++async function createAgent(+ request: APIRequestContext,+ token: string,+ suffix: string,+ tools: string[] = [],+): Promise<string> {+ const result = await requestResult(request, {+ path: '/api/agents',+ token,+ method: 'POST',+ data: {+ name: `E2E project policy agent ${suffix}`,+ description: 'Deterministic project policy scenario agent.',+ instructions: 'Use the project context and answer deterministically.',+ provider: MOCK_ENDPOINTS[0].label,+ model: MOCK_ENDPOINTS[0].model,+ model_parameters: {},+ tools,+ conversation_starters: ['Use the project context.'],+ },+ });+ expectSuccess(result, 201);+ return requireString(asObject(result.body).id, 'agent id');+}++async function expectNoProjectTurn(projectId: string, messageId: string): Promise<void> {+ await withMongo(async (db) => {+ const [message, conversation] = await Promise.all([+ db.collection('messages').findOne({ messageId }),+ db.collection('conversations').findOne({ chatProjectId: projectId }),+ ]);+ expect(message, 'blocked project turn must not persist a message').toBeNull();+ expect(conversation, 'blocked project turn must not persist a conversation').toBeNull();+ });+}++async function completeAgentStream(+ request: APIRequestContext,+ token: string,+ started: RequestResult,+): Promise<string> {+ expectSuccess(started, 200);+ const startBody = asObject(started.body);+ expect(startBody.status).toBe('started');+ const conversationId = requireString(startBody.conversationId, 'conversation id');+ const streamId = requireString(startBody.streamId, 'stream id');+ await expect+ .poll(+ async () => {+ const status = await requestResult(request, {+ path: `/api/agents/chat/status/${encodeURIComponent(conversationId)}`,+ token,+ });+ if (status.status === 503) {+ return { active: true, status: 'pending' };+ }+ expectSuccess(status, 200);+ const body = asObject(status.body);+ return { active: body.active, status: body.status };+ },+ { timeout: 30000, intervals: [100, 250, 500, 1000] },+ )+ .toEqual({ active: false, status: 'complete' });+ const stream = await requestResult(request, {+ path: `/api/agents/chat/stream/${encodeURIComponent(streamId)}?resume=true`,+ token,+ });+ expectSuccess(stream, 200);+ expect(stream.text).toContain('E2E file_search complete');+ return conversationId;+}+function findContentFilterPayload(value: unknown): JsonObject | undefined {+ if (typeof value === 'string') {+ try {+ return findContentFilterPayload(JSON.parse(value));+ } catch {+ for (const line of value.split('\n')) {+ const data = line.startsWith('data:') ? line.slice('data:'.length).trim() : '';+ if (!data || data === '[DONE]') {+ continue;+ }+ try {+ const payload = findContentFilterPayload(JSON.parse(data));+ if (payload) {+ return payload;+ }+ } catch {+ // Ignore non-JSON SSE lines.+ }+ }+ return undefined;+ }+ }+ if (value == null || typeof value !== 'object') {+ return undefined;+ }+ if (!Array.isArray(value)) {+ const object = value as JsonObject;+ if (object.error === 'content_filter_block') {+ return object;+ }+ for (const nested of Object.values(object)) {+ const payload = findContentFilterPayload(nested);+ if (payload) {+ return payload;+ }+ }+ return undefined;+ }+ for (const nested of value) {+ const payload = findContentFilterPayload(nested);+ if (payload) {+ return payload;+ }+ }+ return undefined;+}++/**+ * Agent generation admission returns a `started` envelope before the background+ * initialization finishes. `ResumableAgentController` maps a content-filter+ * initialization failure to HTTP 400 only when headers have not been sent+ * (`api/server/controllers/agents/request.js:3381-3449`); after a job has+ * started, it finalizes the job error for the status and stream endpoints+ * (`api/server/controllers/agents/request.js:3465-3496`).+ *+ * The stream route wraps each event with `JSON.stringify` (`api/server/routes/agents/index.js:264-271`),+ * while `GenerationJobManager` publishes the terminal error string as the event's `error`+ * field (`packages/api/src/stream/GenerationJobManager.ts:4158-4167`). The structured+ * content-filter response is therefore JSON nested inside the SSE event JSON, and its+ * quotes are escaped in the raw body.+ */+async function expectBlockedAgentStream(+ request: APIRequestContext,+ token: string,+ started: RequestResult,+ marker: string,+): Promise<void> {+ if (started.status === 400) {+ expectContentFilterBlock(started, {+ source: 'file',+ field: 'extracted_text',+ marker,+ });+ return;+ }++ expectSuccess(started, 200);+ const startBody = asObject(started.body);+ expect(startBody.status).toBe('started');+ const conversationId = requireString(startBody.conversationId, 'blocked conversation id');+ const streamId = requireString(startBody.streamId, 'blocked stream id');++ let terminalStatus: RequestResult | undefined;+ await expect+ .poll(+ async () => {+ const status = await requestResult(request, {+ path: `/api/agents/chat/status/${encodeURIComponent(conversationId)}`,+ token,+ });+ if (status.status === 503) {+ return { active: true, status: 'pending' };+ }+ expectSuccess(status, 200);+ terminalStatus = status;+ const body = asObject(status.body);+ return { active: body.active, status: body.status };+ },+ { timeout: 30000, intervals: [100, 250, 500, 1000] },+ )+ .toEqual({ active: false, status: 'error' });++ // `/chat/status/:conversationId` intentionally exposes lifecycle state, not+ // `job.error` (`api/server/routes/agents/index.js:541-559`); retain the poll+ // to wait for terminal persistence, then inspect the client-visible SSE.+ const statusPayload = findContentFilterPayload(terminalStatus?.body ?? terminalStatus?.text);+ if (statusPayload) {+ expect(statusPayload).toEqual(+ expect.objectContaining({+ error: 'content_filter_block',+ source: 'file',+ field: 'extracted_text',+ }),+ );+ }+ expect(terminalStatus?.text).not.toContain(marker);++ const stream = await requestResult(request, {+ path: `/api/agents/chat/stream/${encodeURIComponent(streamId)}?resume=true`,+ token,+ });+ expectSuccess(stream, 200);+ expect(stream.text).toContain('event: error');+ const streamPayload = findContentFilterPayload(stream.text);+ expect(streamPayload).toEqual(+ expect.objectContaining({+ error: 'content_filter_block',+ source: 'file',+ field: 'extracted_text',+ }),+ );+ expect(stream.text).toContain('content_filter_block');+ expect(stream.text).not.toContain(marker);+}++async function deleteFiles(fileIds: string[]): Promise<void> {+ await withMongo(async (db) => {+ await db.collection('files').deleteMany({ file_id: { $in: fileIds } });+ });+}++async function deleteProjectConversations(projectId: string): Promise<void> {+ await withMongo(async (db) => {+ const conversations = await db+ .collection('conversations')+ .find({ chatProjectId: projectId }, { projection: { conversationId: 1 } })+ .toArray();+ const conversationIds = conversations+ .map((conversation) => conversation.conversationId)+ .filter((conversationId): conversationId is string => typeof conversationId === 'string');+ if (conversationIds.length > 0) {+ await db.collection('messages').deleteMany({ conversationId: { $in: conversationIds } });+ }+ await db.collection('conversations').deleteMany({ chatProjectId: projectId });+ });+}++async function getPrimaryUserId(): Promise<string> {+ const { email } = getPrimaryE2EUser();+ return withMongo(async (db) => {+ const user = await db.collection('users').findOne({ email }, { projection: { _id: 1 } });+ return requireString(user?._id?.toString(), 'primary user id');+ });+}++async function runCleanup(actions: Array<() => Promise<void>>): Promise<void> {+ const results = await Promise.allSettled(actions.map((action) => action()));+ const failure = results.find((result) => result.status === 'rejected');+ if (failure?.status === 'rejected') {+ throw failure.reason;+ }+}++test.describe.serial('project policy scenarios', () => {+ test('project instructions rejected by a content policy return a content-filter response, not a 500 @scenario:filtered-project-instructions-return-content-filter-not-500', async ({+ request,+ }) => {+ test.setTimeout(120000);+ const token = await loginAdmin(request);+ const suffix = randomUUID();+ const marker = `E2E-PROJECT-INSTRUCTIONS-${suffix}`;+ let projectId: string | undefined;+ let agentId: string | undefined;+ let assistantId: string | undefined;+ try {+ const project = await requestResult(request, {+ path: '/api/projects',+ token,+ method: 'POST',+ data: { name: `E2E filtered project ${suffix}`, instructions: marker },+ });+ expectSuccess(project, 201);+ projectId = requireString(asObject(project.body)._id, 'project id');+ const assistant = await requestResult(request, {+ path: '/api/assistants/v2',+ token,+ method: 'POST',+ data: {+ endpoint: 'assistants',+ model: 'gpt-4o-mini',+ name: `E2E filtered project assistant ${suffix}`,+ tools: [],+ },+ });+ expectSuccess(assistant, 201);+ assistantId = requireString(asObject(assistant.body).id, 'assistant id');+ agentId = await createAgent(request, token, suffix);++ await setRuntimeFilters(request, token, {+ agentInstructions: { pii: pii(`project-instructions-${suffix}`, 'instructions', marker) },+ } as FiltersConfig);++ const messageId = randomUUID();+ const blocked = await requestResult(request, {+ path: '/api/agents/chat/agents',+ token,+ method: 'POST',+ data: {+ text: 'Apply the project instructions.',+ sender: 'User',+ clientTimestamp: new Date().toISOString(),+ isCreatedByUser: true,+ parentMessageId: NO_PARENT,+ conversationId: 'new',+ clientRequestId: suffix,+ messageId,+ responseMessageId: `${messageId}_response`,+ endpoint: 'agents',+ endpointType: 'agents',+ agent_id: agentId,+ chatProjectId: projectId,+ files: [],+ isTemporary: false,+ isRegenerate: false,+ error: false,+ },+ });+ expectContentFilterBlock(blocked, {+ source: 'agent_instruction',+ field: 'instructions',+ marker,+ });+ await expectNoProjectTurn(projectId, messageId);+ const hostedMessageId = randomUUID();+ const hostedBlocked = await requestResult(request, {+ path: '/api/assistants/v2/chat',+ token,+ method: 'POST',+ data: {+ text: 'Apply the project instructions.',+ sender: 'User',+ clientTimestamp: new Date().toISOString(),+ isCreatedByUser: true,+ parentMessageId: NO_PARENT,+ conversationId: null,+ messageId: hostedMessageId,+ responseMessageId: `${hostedMessageId}_response`,+ endpoint: 'assistants',+ endpointType: 'assistants',+ model: 'gpt-4o-mini',+ assistant_id: assistantId,+ chatProjectId: projectId,+ files: [],+ isTemporary: false,+ isRegenerate: false,+ error: false,+ },+ });+ expectContentFilterBlock(hostedBlocked, {+ source: 'agent_instruction',+ field: 'instructions',+ marker,+ });++ const provider = `http://127.0.0.1:${process.env.E2E_ASSISTANTS_PORT || '8890'}`;+ const recorded = await request.get(`${provider}/__e2e/requests`);+ expect(recorded.ok()).toBeTruthy();+ const history = (await recorded.json()) as {+ requests: Array<{ path: string; body?: { assistant_id?: string } }>;+ };+ expect(+ history.requests.filter(+ (entry) => entry.path.endsWith('/runs') && entry.body?.assistant_id === assistantId,+ ),+ ).toHaveLength(0);+ } finally {+ await runCleanup([+ async () => {+ if (assistantId) {+ await requestResult(request, {+ path: `/api/assistants/v2/${encodeURIComponent(assistantId)}?endpoint=assistants&model=gpt-4o-mini`,+ token,+ method: 'DELETE',+ data: { endpoint: 'assistants' },+ });+ }+ },+ () => restoreRuntimeFilters(request, token),+ async () => {+ if (projectId) {+ await requestResult(request, {+ path: `/api/projects/${encodeURIComponent(projectId)}`,+ token,+ method: 'DELETE',+ });+ }+ },+ async () => {+ if (agentId) {+ await requestResult(request, {+ path: `/api/agents/${encodeURIComponent(agentId)}`,+ token,+ method: 'DELETE',+ });+ }+ },+ ]);+ }+ });+ test('a project file whose content violates an active policy is not searchable from the project @scenario:policy-violating-project-file-is-not-searchable', async ({+ request,+ }) => {+ test.setTimeout(180000);+ const token = await loginAdmin(request);+ const resetRag = await request.post(`${RAG_API_BASE}/__debug/reset`);+ expect(resetRag.ok()).toBeTruthy();+ const suffix = randomUUID();+ const marker = `E2E-PROJECT-FILE-${suffix}`;+ const fileIds: string[] = [];+ let projectId: string | undefined;+ let agentId: string | undefined;+ try {+ const upload = async (filename: string, content: string): Promise<{ fileId: string }> => {+ const result = await requestResult(request, {+ path: '/api/files',+ token,+ method: 'POST',+ multipart: {+ endpoint: MOCK_ENDPOINTS[0].label,+ endpointType: 'custom',+ message_file: 'true',+ tool_resource: 'context',+ file_id: randomUUID(),+ file: { name: filename, mimeType: 'text/plain', buffer: Buffer.from(content) },+ },+ });+ expectSuccess(result, 200);+ const body = asObject(result.body);+ const fileId = requireString(body.file_id, `${filename} file id`);+ fileIds.push(fileId);+ await withMongo(async (db) => {+ await db.collection('files').updateOne(+ { file_id: fileId },+ {+ $set: {+ embedded: true,+ context: 'message_attachment',+ // Keep the direct-upload fixture equivalent to a completed+ // text extraction, rather than relying on the upload worker's+ // asynchronous extraction state. The active policy resolves+ // the full record and inspects extracted_text.+ textFormat: 'text',+ status: 'ready',+ usage: 0,+ source: 'local',+ llmDeliveryPath: 'text',+ // resolveChatProjectPolicyFiles(..., includeContent: true)+ // returns this Mongo `text` field; extractFileContent maps+ // FileContentInput.text to the policy's extracted_text field+ // (packages/api/src/projects/resources.ts:172-181;+ // packages/api/src/protection/adapters/submissions.ts:1096-1127).+ extracted_text: content,+ text: content,+ },+ },+ );+ });+ return { fileId };+ };+ const benign = await upload(+ `project-benign-${suffix}.txt`,+ 'Safe project reference content.',+ );+ const violating = await upload(`project-violating-${suffix}.txt`, marker);+ const project = await requestResult(request, {+ path: '/api/projects',+ token,+ method: 'POST',+ data: { name: `E2E project file policy ${suffix}` },+ });+ expectSuccess(project, 201);+ projectId = requireString(asObject(project.body)._id, 'project id');+ for (const fileId of [benign.fileId, violating.fileId]) {+ const attached = await requestResult(request, {+ path: `/api/projects/${encodeURIComponent(projectId)}/files`,+ token,+ method: 'POST',+ data: { file_id: fileId },+ });+ expectSuccess(attached, 200);+ }+ agentId = await createAgent(request, token, suffix, ['file_search']);++ await setRuntimeFilters(request, token, {+ files: {+ pii: {+ fields: ['extracted_text'],+ starterPatterns: [],+ customPatterns: [+ {+ id: `project-file-${suffix}`,+ label: 'E2E violating file',+ regex: `^${marker}$`,+ },+ ],+ // No `uninspectable: 'block'` here: this scenario is about a file+ // whose extracted text matches the policy, not about fail-closing+ // on opaque inputs. Fail-close would reject the recovery turn for+ // unrelated opaque parts of the request envelope.+ },+ },+ } as FiltersConfig);++ const listed = await requestResult(request, {+ path: `/api/projects/${encodeURIComponent(projectId)}/files`,+ token,+ });+ expectSuccess(listed, 200);+ expect(listed.body).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ file_id: benign.fileId, availability: 'ready' }),+ expect.objectContaining({ file_id: violating.fileId }),+ ]),+ );+ const searchText = `E2E_FILE_SEARCH:${suffix}`;++ const blockedMessageId = randomUUID();+ const blocked = await requestResult(request, {+ path: '/api/agents/chat/agents',+ token,+ method: 'POST',+ data: {+ text: searchText,+ sender: 'User',+ clientTimestamp: new Date().toISOString(),+ isCreatedByUser: true,+ parentMessageId: NO_PARENT,+ conversationId: 'new',+ clientRequestId: `${suffix}-blocked`,+ messageId: blockedMessageId,+ responseMessageId: `${blockedMessageId}_response`,+ endpoint: 'agents',+ endpointType: 'agents',+ agent_id: agentId,+ chatProjectId: projectId,+ files: [],+ isTemporary: false,+ isRegenerate: false,+ error: false,+ },+ });+ await expectBlockedAgentStream(request, token, blocked, marker);+ // A late-bound file policy is deliberately persisted as an error turn after+ // the generation ACK; request.js:3478-3487 calls saveErrorTurn in that path.+ const blockedRagResponse = await request.get(`${RAG_API_BASE}/__debug/embedded`);+ expect(blockedRagResponse.ok()).toBeTruthy();+ const blockedRagBody = (await blockedRagResponse.json()) as {+ embedded?: Array<{ file_id?: string }>;+ queries?: Array<{ file_id?: string }>;+ };+ const blockedRagFileIds = [+ ...(blockedRagBody.embedded ?? []).map((record) => record.file_id),+ ...(blockedRagBody.queries ?? []).map((query) => query.file_id),+ ];+ expect(blockedRagFileIds).not.toContain(violating.fileId);++ const removed = await requestResult(request, {+ path: `/api/projects/${encodeURIComponent(projectId)}/files/${encodeURIComponent(violating.fileId)}`,+ token,+ method: 'DELETE',+ });+ expectSuccess(removed, 200);++ const resetAfterRemoval = await request.post(`${RAG_API_BASE}/__debug/reset`);+ expect(resetAfterRemoval.ok()).toBeTruthy();+ const messageId = randomUUID();+ const started = await requestResult(request, {+ path: '/api/agents/chat/agents',+ token,+ method: 'POST',+ data: {+ text: searchText,+ sender: 'User',+ clientTimestamp: new Date().toISOString(),+ isCreatedByUser: true,+ parentMessageId: NO_PARENT,+ conversationId: 'new',+ clientRequestId: `${suffix}-benign`,+ messageId,+ responseMessageId: `${messageId}_response`,+ endpoint: 'agents',+ endpointType: 'agents',+ agent_id: agentId,+ chatProjectId: projectId,+ files: [],+ isTemporary: false,+ isRegenerate: false,+ error: false,+ },+ });+ await completeAgentStream(request, token, started);++ const ragResponse = await request.get(`${RAG_API_BASE}/__debug/embedded`);+ expect(ragResponse.ok()).toBeTruthy();+ const ragBody = (await ragResponse.json()) as {+ embedded?: Array<{ file_id?: string }>;+ queries?: Array<{ file_id?: string }>;+ };+ const queriedFileIds = (ragBody.queries ?? []).map((query) => query.file_id);+ const embeddedFileIds = (ragBody.embedded ?? []).map((record) => record.file_id);+ expect(queriedFileIds).toContain(benign.fileId);+ expect(embeddedFileIds).not.toContain(violating.fileId);+ expect(queriedFileIds).not.toContain(violating.fileId);+ } finally {+ await runCleanup([+ () => restoreRuntimeFilters(request, token),+ async () => {+ if (projectId) {+ await deleteProjectConversations(projectId);+ await requestResult(request, {+ path: `/api/projects/${encodeURIComponent(projectId)}`,+ token,+ method: 'DELETE',+ });+ }+ },+ async () => {+ if (agentId) {+ await requestResult(request, {+ path: `/api/agents/${encodeURIComponent(agentId)}`,+ token,+ method: 'DELETE',+ });+ }+ },+ () => deleteFiles(fileIds),+ ]);+ }+ });++ test('a low-balance user is refused before the hosted Assistant provider runs @scenario:low-balance-refused-before-hosted-assistant-run', async ({+ request,+ }) => {+ test.setTimeout(180000);+ const token = await loginAdmin(request);+ const userId = await getPrimaryUserId();+ const suffix = randomUUID();+ const headers = { Authorization: `Bearer ${token}` };+ const longInstructions = `E2E balance project policy ${suffix} ${'inflate prompt '.repeat(200)}`;+ let projectId: string | undefined;+ let assistantId: string | undefined;+ let balanceSeeded = false;+ const balanceUserId = new ObjectId(userId);+ try {+ // The assistants router installs configMiddleware before /v2/chat+ // (api/server/routes/assistants/index.js:10-17); it resolves options from+ // req.user.id (`packages/api/src/app/service.ts:100-112`), and getBalanceConfig+ // overlays that per-user balance section (`packages/api/src/app/config.ts:20-32`).+ // Polling /api/config proves the override is visible before the chat request.+ const override = await request.put(`/api/admin/config/user/${encodeURIComponent(userId)}`, {+ headers,+ data: { overrides: { balance: { enabled: true } } },+ });+ expect(override.ok(), await override.text()).toBe(true);+ await expect+ .poll(+ async () => {+ const config = await requestResult(request, { path: '/api/config', token });+ const body = asObject(config.body);+ return asObject(body.balance).enabled;+ },+ { timeout: 30000, intervals: [250, 500, 1000] },+ )+ .toBe(true);++ // checkBalanceRecord reads balances by user and compares tokenCredits with+ // the calculated prompt cost (packages/api/src/middleware/checkBalance.ts:48-146).+ // The production Balance schema stores `user` as ObjectId and credits as Number+ // (packages/data-schemas/src/schema/balance.ts:5-16), matching this seeded document.+ balanceSeeded = true;+ await withMongo(async (db) => {+ await db.collection('balances').deleteMany({ user: balanceUserId });+ await db.collection('balances').insertOne({ user: balanceUserId, tokenCredits: 1 });+ });++ const project = await requestResult(request, {+ path: '/api/projects',+ token,+ method: 'POST',+ data: { name: `E2E low balance project ${suffix}`, instructions: longInstructions },+ });+ expectSuccess(project, 201);+ projectId = requireString(asObject(project.body)._id, 'project id');++ const assistant = await requestResult(request, {+ path: '/api/assistants/v2',+ token,+ method: 'POST',+ data: {+ endpoint: 'assistants',+ model: 'gpt-4o-mini',+ name: `E2E low balance assistant ${suffix}`,+ tools: [],+ },+ });+ expectSuccess(assistant, 201);+ assistantId = requireString(asObject(assistant.body).id, 'assistant id');++ const messageId = randomUUID();+ const refused = await requestResult(request, {+ path: '/api/assistants/v2/chat',+ token,+ method: 'POST',+ data: {+ text: 'Run the hosted assistant.',+ sender: 'User',+ clientTimestamp: new Date().toISOString(),+ isCreatedByUser: true,+ parentMessageId: NO_PARENT,+ conversationId: null,+ messageId,+ responseMessageId: `${messageId}_response`,+ endpoint: 'assistants',+ endpointType: 'assistants',+ model: 'gpt-4o-mini',+ assistant_id: assistantId,+ chatProjectId: projectId,+ files: [],+ isTemporary: false,+ isRegenerate: false,+ error: false,+ },+ });+ // chatV2 runs checkBalanceBeforeRun alongside thread initialization and+ // before the hosted run dispatch; its catch path sends the thrown balance+ // JSON through the Assistant error response (chatV2.js:191-236,436-437,631-637).+ // sendResponse serializes this branch as exactly HTTP 500 + `{ error }`+ // (`api/server/middleware/error.js:94-99`).+ expect(refused.status).toBe(500);+ expect(refused.body).toEqual({ error: expect.any(String) });+ const errorText = requireString(asObject(refused.body).error, 'balance error');+ const balanceError = JSON.parse(errorText) as {+ type?: string;+ balance?: number;+ tokenCost?: number;+ promptTokens?: number;+ };+ expect(balanceError).toEqual(expect.objectContaining({ type: 'token_balance', balance: 1 }));+ expect(balanceError.tokenCost).toBeGreaterThan(1);+ expect(balanceError.promptTokens).toBeGreaterThan(1);++ // The fake provider records every request; a balance refusal must happen+ // before the hosted Assistants POST /threads/:id/runs call.+ const provider = `http://127.0.0.1:${process.env.E2E_ASSISTANTS_PORT || '8890'}`;+ const recorded = await request.get(`${provider}/__e2e/requests`);+ expect(recorded.ok()).toBeTruthy();+ const history = (await recorded.json()) as {+ requests: Array<{ path: string; body?: { assistant_id?: string } }>;+ };+ expect(+ history.requests.filter(+ (entry) => entry.path.endsWith('/runs') && entry.body?.assistant_id === assistantId,+ ),+ ).toHaveLength(0);+ } finally {+ await runCleanup([+ async () => {+ if (assistantId) {+ await requestResult(request, {+ path: `/api/assistants/v2/${encodeURIComponent(assistantId)}?endpoint=assistants&model=gpt-4o-mini`,+ token,+ method: 'DELETE',+ data: { endpoint: 'assistants' },+ });+ }+ },+ async () => {+ if (projectId) {+ await deleteProjectConversations(projectId);+ await requestResult(request, {+ path: `/api/projects/${encodeURIComponent(projectId)}`,+ token,+ method: 'DELETE',+ });+ }+ },+ async () => {+ if (balanceSeeded) {+ await withMongo(async (db) => {+ await db.collection('balances').deleteMany({ user: balanceUserId });+ });+ }+ },+ async () => {+ const removed = await request.delete(+ `/api/admin/config/user/${encodeURIComponent(userId)}`,+ {+ headers,+ failOnStatusCode: false,+ },+ );+ expect([200, 404], await removed.text()).toContain(removed.status());+ },+ () => restoreRuntimeFilters(request, token),+ ]);+ }+ });+});diff --git a/e2e/specs/mock/scenarios/project-resume.spec.ts b/e2e/specs/mock/scenarios/project-resume.spec.tsnew file mode 100644index 0000000000..e13394cd73--- /dev/null+++ b/e2e/specs/mock/scenarios/project-resume.spec.ts@@ -0,0 +1,639 @@+import { randomUUID } from 'crypto';+import { ObjectId } from 'mongodb';+import { expect, test } from '@playwright/test';+import type { APIRequestContext } from '@playwright/test';+import { FileContext } from 'librechat-data-provider';+import { getE2EUser } from '../../../setup/user';+import { MOCK_ENDPOINTS, RAG_API_BASE } from '../helpers';+import { deleteConversations, deleteMessagesByConversation, withMongo } from '../db';+import { loginAdmin, requestResult } from '../content-filters.helpers';+import type { RequestResult } from '../content-filters.helpers';++const NO_PARENT = '00000000-0000-0000-0000-000000000000';+const MCP_SERVER_NAME = 'e2e-memory';+const MCP_SERVER_TOOL_ID = `sys__server__sys_mcp_${MCP_SERVER_NAME}`;+const APPROVAL_TOOL_ID = `approval_probe_mcp_${MCP_SERVER_NAME}`;+const APPROVAL_MARKER = 'E2E_TOOL_APPROVAL:';+const PROJECT_CONTEXT_CHANGED = 'Project context changed; start a new turn.';++interface JsonObject {+ [key: string]: unknown;+}++interface ProjectFileFixture {+ projectId: string;+ fileId: string;+}++interface AgentFixture {+ id: string;+ tools?: string[];+}++interface SkillResponse {+ _id: string;+}++interface PendingAction {+ actionId?: string;+ conversationId?: string;+ streamId?: string;+ payload?: {+ type?: string;+ action_requests?: Array<{ tool_call_id?: string }>;+ };+}++interface StatusResponse {+ active?: boolean;+ status?: string;+ streamId?: string;+ pendingAction?: PendingAction;+}++function asObject(value: unknown): JsonObject {+ return value != null && typeof value === 'object' && !Array.isArray(value)+ ? (value as JsonObject)+ : {};+}++function requireString(value: unknown, label: string): string {+ if (typeof value !== 'string' || value.length === 0) {+ throw new Error(`${label} must be a non-empty string`);+ }+ return value;+}++function expectSuccess(result: RequestResult, status: number): void {+ expect(result.ok, result.text).toBe(true);+ expect(result.status, result.text).toBe(status);+}++async function seedProjectFile(+ request: APIRequestContext,+ token: string,+ suffix: string,+): Promise<ProjectFileFixture> {+ const project = await requestResult(request, {+ path: '/api/projects',+ token,+ method: 'POST',+ data: { name: `E2E Resume Project ${suffix}` },+ });+ // api/server/routes/projects.js:22 and createProjectHandlers return 201.+ expectSuccess(project, 201);+ const projectId = requireString(+ asObject(project.body)._id ?? asObject(project.body).id,+ 'project id',+ );+ const fileId = randomUUID();+ const filename = `project-resume-${suffix}.txt`;+ const fileText = `Project corpus fixture ${suffix}`;++ try {+ // This direct fixture matches project-files-ui.spec.ts:53-89; these scenarios+ // exercise project fingerprinting and file_search, not multipart parsing.+ await withMongo(async (db) => {+ const owner = await db.collection('users').findOne({ email: getE2EUser().email });+ if (!owner) {+ throw new Error('The authenticated e2e user was not found while seeding files');+ }+ const now = new Date();+ await db.collection('files').insertOne({+ _id: new ObjectId(),+ user: owner._id,+ ...(owner.tenantId ? { tenantId: owner.tenantId } : {}),+ file_id: fileId,+ bytes: Buffer.byteLength(fileText),+ filename,+ filepath: `/tmp/${fileId}.txt`,+ object: 'file',+ embedded: true,+ type: 'text/plain',+ text: fileText,+ extracted_text: fileText,+ textFormat: 'text',+ status: 'ready',+ usage: 0,+ source: 'local',+ context: FileContext.message_attachment,+ createdAt: now,+ updatedAt: now,+ });+ });++ const attached = await requestResult(request, {+ path: `/api/projects/${encodeURIComponent(projectId)}/files`,+ token,+ method: 'POST',+ data: { file_id: fileId },+ });+ // api/server/routes/projects.js:26 and addProjectFile return 2xx for an owned file.+ expectSuccess(attached, 200);+ return { projectId, fileId };+ } catch (error) {+ await requestResult(request, {+ path: `/api/projects/${encodeURIComponent(projectId)}`,+ token,+ method: 'DELETE',+ }).catch(() => undefined);+ await deleteProjectFile(fileId);+ throw error;+ }+}++async function deleteProjectFile(fileId: string): Promise<void> {+ await withMongo(async (db) => {+ await db.collection('files').deleteMany({ file_id: fileId });+ });+}++async function updateProjectFile(fileId: string, update: Record<string, unknown>): Promise<void> {+ await withMongo(async (db) => {+ await db.collection('files').updateOne({ file_id: fileId }, { $set: update });+ });+}++async function createApprovalAgent(+ request: APIRequestContext,+ token: string,+ suffix: string,+): Promise<AgentFixture> {+ const result = await requestResult(request, {+ path: '/api/agents',+ token,+ method: 'POST',+ data: {+ name: `E2E Project Approval Agent ${suffix}`,+ description: 'Project context approval resume fixture.',+ instructions: 'Use the approval probe and report the result.',+ provider: MOCK_ENDPOINTS[0].label,+ model: MOCK_ENDPOINTS[0].model,+ /** `file_search` is what admits the project corpus into a run, and these+ * scenarios pause a run whose context references a project file; an agent+ * that cannot search never resolves those files, so their change would not+ * be material to its resume. */+ tools: ['file_search', MCP_SERVER_TOOL_ID, APPROVAL_TOOL_ID],+ },+ });+ // api/server/routes/agents/management.js:153 and createAgentManagementCreateHandler return 201.+ expectSuccess(result, 201);+ return { id: requireString(asObject(result.body).id, 'agent id') };+}++function startBody({+ messageId,+ text,+ agentId,+ projectId,+ clientRequestId,+}: {+ messageId: string;+ text: string;+ agentId: string;+ projectId: string;+ clientRequestId: string;+}): JsonObject {+ return {+ text,+ sender: 'User',+ clientTimestamp: new Date().toISOString(),+ isCreatedByUser: true,+ parentMessageId: NO_PARENT,+ conversationId: 'new',+ clientRequestId,+ messageId,+ responseMessageId: `${messageId}_response`,+ endpoint: 'agents',+ endpointType: 'agents',+ agent_id: agentId,+ chatProjectId: projectId,+ files: [],+ isTemporary: false,+ isRegenerate: false,+ error: false,+ };+}++async function startAgentTurn(+ request: APIRequestContext,+ token: string,+ body: JsonObject,+): Promise<{ conversationId: string; streamId: string }> {+ const result = await requestResult(request, {+ path: '/api/agents/chat/agents',+ token,+ method: 'POST',+ data: body,+ });+ // api/server/controllers/agents/request.js:1880 sends the started envelope with HTTP 200.+ expectSuccess(result, 200);+ const response = asObject(result.body);+ return {+ conversationId: requireString(response.conversationId, 'conversation id'),+ streamId: requireString(response.streamId, 'stream id'),+ };+}++async function waitForPendingAction(+ request: APIRequestContext,+ token: string,+ conversationId: string,+): Promise<{ status: StatusResponse; streamId: string }> {+ let latest: StatusResponse | undefined;+ await expect+ .poll(+ async () => {+ const result = await requestResult(request, {+ path: `/api/agents/chat/status/${encodeURIComponent(conversationId)}`,+ token,+ });+ if (result.status === 503) {+ return 'pending';+ }+ // api/server/routes/agents/index.js:541-559 publishes lifecycle status and pendingAction.+ expectSuccess(result, 200);+ latest = asObject(result.body) as StatusResponse;+ if (latest.status === 'requires_action' && latest.pendingAction) {+ return 'requires_action';+ }+ return latest.status ?? 'pending';+ },+ { timeout: 30000, intervals: [100, 250, 500, 1000] },+ )+ .toBe('requires_action');++ if (!latest?.pendingAction) {+ throw new Error('The generation became requires_action without publishing pendingAction');+ }+ return { status: latest, streamId: requireString(latest.streamId, 'status stream id') };+}++function resumeBody(pending: PendingAction, agentId: string, projectId: string): JsonObject {+ const actionId = requireString(pending.actionId, 'pending action id');+ const conversationId = requireString(pending.conversationId, 'pending conversation id');+ const actionRequests = pending.payload?.action_requests ?? [];+ const decisions = actionRequests.map((action) => ({+ // The status projection is the source of truth for the paused tool-call ids.+ tool_call_id: requireString(action.tool_call_id, 'pending tool call id'),+ decision: 'approve',+ }));+ if (decisions.length === 0) {+ throw new Error('The pending approval did not publish any tool calls');+ }+ return {+ actionId,+ agent_id: agentId,+ conversationId,+ endpoint: 'agents',+ endpointType: 'agents',+ chatProjectId: projectId,+ decisions,+ };+}+async function resumeApproval(+ request: APIRequestContext,+ token: string,+ pending: PendingAction,+ agentId: string,+ projectId: string,+): Promise<RequestResult> {+ const result = await requestResult(request, {+ path: '/api/agents/chat/resume',+ token,+ method: 'POST',+ data: resumeBody(pending, agentId, projectId),+ });+ return result;+}++async function completeStream(+ request: APIRequestContext,+ token: string,+ conversationId: string,+ streamId: string,+ expectedText?: string,+): Promise<RequestResult> {+ await expect+ .poll(+ async () => {+ const result = await requestResult(request, {+ path: `/api/agents/chat/status/${encodeURIComponent(conversationId)}`,+ token,+ });+ if (result.status === 503) {+ return { active: true, status: 'pending' };+ }+ // api/server/routes/agents/index.js:541-549 exposes terminal status after persistence.+ expectSuccess(result, 200);+ const body = asObject(result.body);+ return { active: body.active, status: body.status };+ },+ { timeout: 30000, intervals: [100, 250, 500, 1000] },+ )+ .toEqual({ active: false, status: 'complete' });++ const stream = await requestResult(request, {+ path: `/api/agents/chat/stream/${encodeURIComponent(streamId)}?resume=true`,+ token,+ });+ // api/server/routes/agents/index.js:264-271 serializes the completed SSE stream with HTTP 200.+ expectSuccess(stream, 200);+ // Callers assert fake-model.js:1573-1610 approval outcomes or 2414-2431 file_search completion.+ if (expectedText) {+ expect(stream.text).toContain(expectedText);+ }+ return stream;+}++async function createSearchSkill(+ request: APIRequestContext,+ token: string,+ suffix: string,+): Promise<SkillResponse> {+ const result = await requestResult(request, {+ path: '/api/skills',+ token,+ method: 'POST',+ data: {+ // packages/api/src/skills/handlers.ts validates kebab-case skill names.+ name: `e2e-project-search-skill-${suffix.toLowerCase()}`,+ description: 'Contributes project file search to an agent.',+ body: '# Search project files\n\nUse file_search for project corpus questions.',+ frontmatter: { 'allowed-tools': ['file_search'] },+ alwaysApply: true,+ },+ });+ // api/server/routes/skills.js:280-281 and handlers.ts:411-488 return the created skill.+ expectSuccess(result, 201);+ return { _id: requireString(asObject(result.body)._id, 'skill id') };+}++async function createSkillAgent(+ request: APIRequestContext,+ token: string,+ skill: SkillResponse,+ suffix: string,+): Promise<AgentFixture> {+ const result = await requestResult(request, {+ path: '/api/agents',+ token,+ method: 'POST',+ data: {+ name: `E2E Skill Project Search Agent ${suffix}`,+ description: 'Project search skill fixture.',+ instructions: 'Search the project corpus and report the result.',+ provider: MOCK_ENDPOINTS[0].label,+ model: MOCK_ENDPOINTS[0].model,+ tools: [],+ skills: [skill._id],+ skills_enabled: true,+ skills_scope: 'selected',+ },+ });+ // api/server/routes/agents/management.js:153 and createAgentManagementCreateHandler return 201.+ expectSuccess(result, 201);+ const body = asObject(result.body);+ const tools = Array.isArray(body.tools)+ ? body.tools.filter((tool): tool is string => typeof tool === 'string')+ : [];+ // initialize.ts:1211-1261 retains configured agent tools before skill augmentation.+ expect(tools).not.toContain('file_search');+ return { id: requireString(body.id, 'agent id'), tools };+}++async function cleanup(+ request: APIRequestContext,+ token: string,+ resources: {+ agentId?: string;+ projectId?: string;+ fileId?: string;+ skillId?: string;+ conversationId?: string;+ },+): Promise<void> {+ if (resources.conversationId) {+ await deleteMessagesByConversation([resources.conversationId]);+ await deleteConversations([resources.conversationId]);+ }+ if (resources.agentId) {+ await requestResult(request, {+ path: `/api/agents/${encodeURIComponent(resources.agentId)}`,+ token,+ method: 'DELETE',+ }).catch(() => undefined);+ }+ if (resources.skillId) {+ await requestResult(request, {+ path: `/api/skills/${encodeURIComponent(resources.skillId)}`,+ token,+ method: 'DELETE',+ }).catch(() => undefined);+ }+ if (resources.projectId) {+ await requestResult(request, {+ path: `/api/projects/${encodeURIComponent(resources.projectId)}`,+ token,+ method: 'DELETE',+ }).catch(() => undefined);+ }+ if (resources.fileId) {+ await requestResult(request, {+ path: '/api/files',+ token,+ method: 'DELETE',+ data: { files: [{ file_id: resources.fileId }] },+ }).catch(() => undefined);+ await deleteProjectFile(resources.fileId);+ }+}++test.describe.serial('project-scoped approval resume', () => {+ test('resuming a paused approval after a project file changed is refused as changed context @scenario:resume-rejected-after-project-file-changes', async ({+ request,+ }) => {+ test.setTimeout(120000);+ const token = await loginAdmin(request);+ const suffix = randomUUID();+ const resources: {+ agentId?: string;+ projectId?: string;+ fileId?: string;+ conversationId?: string;+ } = {};++ try {+ const fixture = await seedProjectFile(request, token, suffix);+ resources.projectId = fixture.projectId;+ resources.fileId = fixture.fileId;+ const agent = await createApprovalAgent(request, token, suffix);+ resources.agentId = agent.id;+ const messageId = randomUUID();+ const started = await startAgentTurn(+ request,+ token,+ startBody({+ messageId,+ text: `${APPROVAL_MARKER}${suffix}`,+ agentId: agent.id,+ projectId: fixture.projectId,+ clientRequestId: suffix,+ }),+ );+ resources.conversationId = started.conversationId;+ const paused = await waitForPendingAction(request, token, started.conversationId);++ // packages/api/src/projects/context.ts:138-150 fingerprints availability/version;+ // packages/api/src/projects/resources.ts:43-58 and 118-141 make expiredAt unavailable.+ await updateProjectFile(fixture.fileId, { expiredAt: new Date(Date.now() - 1000) });+ const resumed = await resumeApproval(+ request,+ token,+ paused.status.pendingAction!,+ agent.id,+ fixture.projectId,+ );+ // api/server/controllers/agents/resume.js:292-300 sends this 409 body.+ expect(resumed.status).toBe(409);+ expect(resumed.body).toEqual(+ expect.objectContaining({+ code: 'PROJECT_CONTEXT_CHANGED',+ error: PROJECT_CONTEXT_CHANGED,+ }),+ );+ } finally {+ await cleanup(request, token, resources);+ }+ });++ test("resuming a paused approval still works after a file's signed URL rotates @scenario:resume-succeeds-after-signed-url-rotation", async ({+ request,+ }) => {+ test.setTimeout(120000);+ const token = await loginAdmin(request);+ const suffix = randomUUID();+ const resources: {+ agentId?: string;+ projectId?: string;+ fileId?: string;+ conversationId?: string;+ } = {};++ try {+ const fixture = await seedProjectFile(request, token, suffix);+ resources.projectId = fixture.projectId;+ resources.fileId = fixture.fileId;+ const agent = await createApprovalAgent(request, token, suffix);+ resources.agentId = agent.id;+ const messageId = randomUUID();+ const started = await startAgentTurn(+ request,+ token,+ startBody({+ messageId,+ text: `${APPROVAL_MARKER}${suffix}`,+ agentId: agent.id,+ projectId: fixture.projectId,+ clientRequestId: suffix,+ }),+ );+ resources.conversationId = started.conversationId;+ const paused = await waitForPendingAction(request, token, started.conversationId);++ // packages/api/src/projects/context.ts:138-150 keys resource identity/availability/version;+ // packages/api/src/projects/resources.ts:118-141 omits filepath from the canonical version.+ await updateProjectFile(fixture.fileId, {+ filepath: `https://signed.example/${fixture.fileId}?signature=${suffix}`,+ });+ const resumed = await resumeApproval(+ request,+ token,+ paused.status.pendingAction!,+ agent.id,+ fixture.projectId,+ );+ // api/server/controllers/agents/resume.js:1941-1943 sends the successful resume body.+ expect(resumed.status).toBe(200);+ expect(resumed.body).toEqual(+ expect.objectContaining({+ status: 'resuming',+ conversationId: started.conversationId,+ streamId: started.conversationId,+ }),+ );+ await completeStream(+ request,+ token,+ started.conversationId,+ started.streamId,+ 'E2E approval outcomes:',+ );+ } finally {+ await cleanup(request, token, resources);+ }+ });++ test('a skill-contributed file_search tool searches the project corpus @scenario:skill-file-search-searches-project-files', async ({+ request,+ }) => {+ test.setTimeout(120000);+ const token = await loginAdmin(request);+ const suffix = randomUUID();+ const resources: {+ agentId?: string;+ projectId?: string;+ fileId?: string;+ skillId?: string;+ conversationId?: string;+ } = {};++ try {+ const resetRag = await request.post(`${RAG_API_BASE}/__debug/reset`);+ // e2e/setup/fake-rag-server.js:123-128 resets the query recorder for this scenario.+ expect(resetRag.ok()).toBeTruthy();+ const fixture = await seedProjectFile(request, token, suffix);+ resources.projectId = fixture.projectId;+ resources.fileId = fixture.fileId;+ const skill = await createSearchSkill(request, token, suffix);+ resources.skillId = skill._id;+ const agent = await createSkillAgent(request, token, skill, suffix);+ resources.agentId = agent.id;+ const marker = `corpus-${suffix}`;+ const messageId = randomUUID();+ const started = await startAgentTurn(+ request,+ token,+ startBody({+ messageId,+ text: `E2E_FILE_SEARCH:${marker}`,+ agentId: agent.id,+ projectId: fixture.projectId,+ clientRequestId: suffix,+ }),+ );+ resources.conversationId = started.conversationId;+ const stream = await completeStream(+ request,+ token,+ started.conversationId,+ started.streamId,+ `E2E file_search complete: ${marker}`,+ );+ // fake-model.js:2414-2431 emits completion only after file_search is advertised;+ // initialize.ts:1214-1261 unions skill allowed-tools into the runtime tool set.+ expect(stream.text).not.toContain('E2E file_search unavailable');++ const ragResponse = await request.get(`${RAG_API_BASE}/__debug/embedded`);+ // e2e/setup/fake-rag-server.js:118-120 publishes recorded queries.+ expect(ragResponse.ok()).toBeTruthy();+ const ragBody = (await ragResponse.json()) as {+ queries?: Array<{ file_id?: string }>;+ };+ const queriedFileIds = (ragBody.queries ?? []).map((query) => query.file_id);+ expect(queriedFileIds).toContain(fixture.fileId);+ } finally {+ await cleanup(request, token, resources);+ }+ });+});diff --git a/eslint-suppressions.json b/eslint-suppressions.jsonindex 7c8a050a87..68f6bc8def 100644--- a/eslint-suppressions.json+++ b/eslint-suppressions.json@@ -1349,9 +1349,6 @@"client/src/components/Projects/ProjectChatList.tsx": {"shadcn/no-inline-styles": {"count": 1- },- "shadcn/no-restyle": {- "count": 2}},"client/src/components/Projects/ProjectChatOptions.tsx": {@@ -1364,25 +1361,9 @@"count": 3}},- "client/src/components/Projects/ProjectEditDialog.tsx": {- "shadcn/no-restyle": {- "count": 3- }- },- "client/src/components/Projects/ProjectWorkspace.tsx": {- "shadcn/no-restyle": {- "count": 7- }- },"client/src/components/Projects/ProjectsView.tsx": {- "shadcn/no-inline-styles": {- "count": 1- },- "shadcn/no-raw-colors": {- "count": 1- },"shadcn/no-restyle": {- "count": 4+ "count": 1}},"client/src/components/Prompts/buttons/AutoSendPrompt.tsx": {diff --git a/librechat.example.yaml b/librechat.example.yamlindex 3911861392..e837a17a08 100644--- a/librechat.example.yaml+++ b/librechat.example.yaml@@ -7,6 +7,16 @@ version: 1.3.17# Cache settings: Set to true to enable cachingcache: true+# Chat Projects: the ceilings a single project may reach. Every field is optional and+# defaults to the value shown, which is the behavior when the block is absent.+projects:+ # Reference files that may be attached to one project (maximum 500).+ maxFiles: 50+ # Characters of project instructions stored and sent as guidance (maximum 200000).+ maxInstructionsLength: 16000+ # Characters of the project description shown in the workspace and sidebar (maximum 10000).+ maxDescriptionLength: 1000+# Langfuse connections are managed through Settings > Langfuse when available.# That flow verifies the credentials and stores the secret key encrypted; do not# place a plaintext langfuse.secretKey in this file. Environment-managed centraldiff --git a/packages/api/src/agents/__tests__/initialize.test.ts b/packages/api/src/agents/__tests__/initialize.test.tsindex 488c68007e..184868aedd 100644--- a/packages/api/src/agents/__tests__/initialize.test.ts+++ b/packages/api/src/agents/__tests__/initialize.test.ts@@ -49,11 +49,15 @@ import {configSchema,} from 'librechat-data-provider';import type { IMongoFile } from '@librechat/data-schemas';-import type { Agent, TFile } from 'librechat-data-provider';+import type { Agent, TFile, FiltersConfig } from 'librechat-data-provider';import type { ServerRequest, InitializeResultBase, EndpointTokenConfig } from '~/types';import type { InitializeAgentDbMethods } from '../initialize';import type { CodeExecutionContext } from '../execution';+import type { GraphSubagentHostConfig } from '../discovery';+import type { ProjectFileRecord } from '../../projects/resources';+import { toCanonicalProjectResource } from '../../projects/resources';import { DEFAULT_MAX_CONTEXT_TOKENS } from '../initialize';+import { discoverConnectedAgents, resolveSubagentGraphs } from '../discovery';// Mock logger — `format` must be a callable factory so @librechat/data-schemas// dist module-load completes cleanly; see api/test/__mocks__/logger.js.@@ -236,6 +240,7 @@ function createMocks(overrides?: {});const db: InitializeAgentDbMethods = {+ getProjectFiles: jest.fn().mockResolvedValue([]),getFiles: jest.fn().mockResolvedValue([]),getConvoFiles: jest.fn().mockResolvedValue([]),updateFilesUsage: jest.fn().mockResolvedValue([]),@@ -461,6 +466,450 @@ describe('initializeAgent — execution context', () => {});});+describe('initializeAgent: ChatProject context', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ const projectFile: TFile = {+ file_id: 'project-file',+ filename: 'project.txt',+ filepath: '/uploads/project.txt',+ type: 'text/plain',+ object: 'file',+ bytes: 12,+ usage: 0,+ user: 'user-1',+ embedded: true,+ context: FileContext.message_attachment,+ };+ const canonicalFile: ProjectFileRecord = {+ ...projectFile,+ _id: '507f1f77bcf86cd799439012',+ user: projectFile.user,+ expiredAt: undefined,+ createdAt: new Date('2020-01-01'),+ updatedAt: new Date('2020-01-01'),+ text: 'Safe canonical Project content.',+ };+ const projectContext = {+ projectId: 'project-1',+ contextRevision: 3,+ instructions: 'Prefer concise project answers.',+ file_ids: ['project-file'],+ resources: [toCanonicalProjectResource(canonicalFile)],+ };+ const projectFilePolicy: FiltersConfig = {+ files: {+ pii: {+ fields: ['extracted_text'],+ starterPatterns: [],+ customPatterns: [{ id: 'project-policy', label: 'Project policy', regex: 'BLOCKED' }],+ },+ },+ };++ function projectRuntime() {+ return {+ user: createMocks().req.user,+ appConfig: {+ endpoints: {+ [EModelEndpoint.agents]: {+ capabilities: [AgentCapabilities.file_search],+ },+ },+ } as NonNullable<ServerRequest['config']>,+ requestBody: {},+ turnStartedAt: 1,+ chatProjectContext: projectContext,+ };+ }++ it('keeps Agent and Project guidance exactly once in initialized output without mutating the definition', async () => {+ const { agent, loadTools, db } = createMocks();+ agent.instructions = 'Follow the Agent instructions.';+ agent.additional_instructions = 'Agent dynamic guidance.';+ const originalAdditionalInstructions = agent.additional_instructions;++ const result = await initializeAgent(+ {+ runtime: projectRuntime(),+ agent,+ loadTools,+ endpointOption: { endpoint: EModelEndpoint.agents },+ allowedProviders: new Set([Providers.OPENAI]),+ useChatProjectContext: true,+ },+ db,+ );++ expect(result.instructions).toBe('Follow the Agent instructions.');+ expect(result.additional_instructions).toContain('Agent dynamic guidance.');+ expect(result.additional_instructions).toContain(projectContext.instructions);+ const additionalInstructions = result.additional_instructions ?? '';+ expect(additionalInstructions.split('Agent dynamic guidance.').length - 1).toBe(1);+ expect(additionalInstructions.split(projectContext.instructions).length - 1).toBe(1);+ expect(additionalInstructions.split('Project guidance (user-provided context').length - 1).toBe(+ 1,+ );+ expect(agent.additional_instructions).toBe(originalAdditionalInstructions);+ });+ it('propagates Project guidance and files to a discovered child through real initialization', async () => {+ const { agent, req, res, loadTools, db } = createMocks();+ agent.id = 'child-agent';+ agent._id = 'mongo-child-agent';+ agent.instructions = 'Child Agent instructions.';+ agent.tools = [Tools.file_search];+ req.config = projectRuntime().appConfig;+ req.chatProjectContext = projectContext;+ const getProjectFiles = jest.fn().mockResolvedValue([canonicalFile]);+ const projectDb = { ...db, getProjectFiles };+ const primaryConfig = await initializeAgent(+ {+ runtime: projectRuntime(),+ agent: {+ ...agent,+ id: 'primary-agent',+ edges: [{ from: 'primary-agent', to: 'child-agent', edgeType: 'handoff' }],+ tools: [],+ },+ loadTools,+ allowedProviders: new Set([Providers.OPENAI]),+ useChatProjectContext: true,+ },+ projectDb,+ );++ const result = await discoverConnectedAgents(+ {+ req,+ res,+ primaryConfig,+ allowedProviders: new Set([Providers.OPENAI]),+ modelsConfig: { openai: ['test-model'] },+ loadTools,+ useChatProjectContext: true,+ },+ {+ getAgent: jest.fn().mockResolvedValue(agent),+ checkPermission: jest.fn().mockResolvedValue(true),+ logViolation: jest.fn(),+ db: projectDb,+ validateAgentModel: jest.fn().mockResolvedValue({ isValid: true }),+ },+ );++ const childConfig = result.agentConfigs.get('child-agent');+ expect(childConfig?.additional_instructions).toContain(projectContext.instructions);+ expect(childConfig?.tool_resources?.[EToolResources.file_search]?.files).toEqual([projectFile]);+ });+ it('propagates Project guidance and files to a saved graph member through real initialization', async () => {+ const { agent, req, res, loadTools, db } = createMocks();+ agent.id = 'graph-agent';+ agent._id = 'mongo-graph-agent';+ agent.instructions = 'Graph Agent instructions.';+ agent.tools = [Tools.file_search];+ req.config = projectRuntime().appConfig;+ req.chatProjectContext = projectContext;+ const getProjectFiles = jest.fn().mockResolvedValue([canonicalFile]);+ const projectDb = { ...db, getProjectFiles };+ const primaryConfig: GraphSubagentHostConfig = await initializeAgent(+ {+ runtime: projectRuntime(),+ agent: {+ ...agent,+ id: 'primary-agent',+ tools: [],+ subagents: {+ enabled: true,+ graphs: [+ {+ type: 'team',+ name: 'Project team',+ description: 'Project-aware graph',+ agent_ids: ['graph-agent'],+ edges: [],+ entry_agent_id: 'graph-agent',+ result_agent_id: 'graph-agent',+ },+ ],+ },+ },+ loadTools,+ allowedProviders: new Set([Providers.OPENAI]),+ useChatProjectContext: true,+ },+ projectDb,+ );++ await resolveSubagentGraphs(+ {+ req,+ res,+ primaryConfig,+ rootConfigs: [primaryConfig],+ allowedProviders: new Set([Providers.OPENAI]),+ modelsConfig: { openai: ['test-model'] },+ loadTools,+ useChatProjectContext: true,+ },+ {+ getAgent: jest.fn().mockResolvedValue(agent),+ checkPermission: jest.fn().mockResolvedValue(true),+ logViolation: jest.fn(),+ db: projectDb,+ validateAgentModel: jest.fn().mockResolvedValue({ isValid: true }),+ },+ );++ const graphMember = primaryConfig.subagentGraphConfigs?.[0]?.memberConfigs[0];+ expect(graphMember?.additional_instructions).toContain(projectContext.instructions);+ expect(graphMember?.tool_resources?.[EToolResources.file_search]?.files).toEqual([projectFile]);+ });++ it('adds ready Project files only to enabled File Search resources', async () => {+ const { agent, loadTools, db } = createMocks();+ agent.tools = [Tools.file_search];+ const originalTools = [...agent.tools];++ const result = await initializeAgent(+ {+ runtime: projectRuntime(),+ agent,+ loadTools,+ endpointOption: { endpoint: EModelEndpoint.agents },+ allowedProviders: new Set([Providers.OPENAI]),+ useChatProjectContext: true,+ },+ db,+ );++ expect(result.tool_resources).toEqual({+ [EToolResources.file_search]: { files: [projectFile] },+ });+ expect(result.tool_resources?.[EToolResources.file_search]).not.toHaveProperty('file_ids');+ expect(agent.tools).toEqual(originalTools);+ expect(agent).not.toHaveProperty('tool_resources');+ expect(db.getFiles).not.toHaveBeenCalled();+ });+ it('adds Project files for file_search supplied by a manual Skill', async () => {+ const { agent, req, loadTools, db } = createMocks();+ const { Types } = await import('mongoose');+ const skillId = new Types.ObjectId();+ agent.tools = [];+ loadTools.mockImplementation(async ({ tools }: { tools: string[] }) => ({+ tools: [],+ toolContextMap: {},+ toolDefinitions: tools.map((name) => ({ name, description: '', parameters: {} })),+ hasDeferredTools: false,+ }));+ const getSkillByName: InitializeAgentDbMethods['getSkillByName'] = jest.fn().mockResolvedValue({+ _id: skillId,+ name: 'project-file-search',+ body: 'Search project files.',+ author: { toString: () => req.user!.id } as unknown as import('mongoose').Types.ObjectId,+ allowedTools: [Tools.file_search],+ });++ const result = await initializeAgent(+ {+ runtime: projectRuntime(),+ agent,+ loadTools,+ endpointOption: { endpoint: EModelEndpoint.agents },+ allowedProviders: new Set([Providers.OPENAI]),+ useChatProjectContext: true,+ accessibleSkillIds: [skillId],+ manualSkills: ['project-file-search'],+ },+ {+ ...db,+ listSkillsByAccess: async () => ({ skills: [], has_more: false, after: null }),+ getSkillByName,+ },+ );++ expect(loadTools).toHaveBeenCalledWith(expect.objectContaining({ tools: [Tools.file_search] }));+ expect(result.tool_resources?.[EToolResources.file_search]?.files).toEqual([projectFile]);+ });++ it('does not hydrate or inject Project files when file_search is role-disabled', async () => {+ const { agent, loadTools, db } = createMocks();+ const { Types } = await import('mongoose');+ const skillId = new Types.ObjectId();+ const getSkillByName: InitializeAgentDbMethods['getSkillByName'] = jest.fn().mockResolvedValue({+ _id: skillId,+ name: 'denied-project-file-search',+ body: 'Search project files.',+ author: { toString: () => 'user-1' } as unknown as import('mongoose').Types.ObjectId,+ allowedTools: [Tools.file_search],+ });+ const projectDb = {+ ...db,+ getProjectFiles: jest+ .fn()+ .mockRejectedValue(new Error('Project resource lookup unavailable')),+ listSkillsByAccess: async () => ({ skills: [], has_more: false, after: null }),+ getSkillByName,+ };++ const result = await initializeAgent(+ {+ runtime: {+ ...projectRuntime(),+ chatProjectContext: { ...projectContext, resources: [] },+ chatProjectFiles: undefined,+ },+ agent,+ loadTools,+ endpointOption: { endpoint: EModelEndpoint.agents },+ allowedProviders: new Set([Providers.OPENAI]),+ useChatProjectContext: true,+ accessibleSkillIds: [skillId],+ manualSkills: ['denied-project-file-search'],+ fileSearchAvailable: false,+ },+ projectDb,+ );++ expect(projectDb.getProjectFiles).not.toHaveBeenCalled();+ expect(db.getFiles).not.toHaveBeenCalled();+ expect(result.tool_resources).toBeUndefined();+ });++ it('shares policy hydration across concurrent graph agents without injecting file text', async () => {+ const { agent, loadTools, db } = createMocks();+ agent.tools = [Tools.file_search];+ const getProjectFiles = jest.fn().mockResolvedValue([canonicalFile]);+ const projectDb = { ...db, getProjectFiles };+ const runtime = { ...projectRuntime(), chatProjectFiles: undefined };+ runtime.appConfig.filters = projectFilePolicy;+ const params = {+ runtime,+ agent,+ loadTools,+ endpointOption: { endpoint: EModelEndpoint.agents },+ allowedProviders: new Set([Providers.OPENAI]),+ useChatProjectContext: true,+ };+ const results = await Promise.all([+ initializeAgent(params, projectDb),+ initializeAgent(params, projectDb),+ ]);+ for (const result of results) {+ expect(result.tool_resources?.[EToolResources.file_search]?.files).toEqual([+ expect.objectContaining({ file_id: 'project-file', filepath: '/uploads/project.txt' }),+ ]);+ expect(result.tool_resources?.[EToolResources.file_search]?.files?.[0]).not.toHaveProperty(+ 'text',+ );+ expect(result.attachments).not.toEqual(+ expect.arrayContaining([expect.objectContaining({ file_id: projectFile.file_id })]),+ );+ }+ expect(getProjectFiles).toHaveBeenCalledTimes(1);+ });++ it('rejects prohibited Project content before tool setup or usage mutation', async () => {+ const { agent, loadTools, db } = createMocks();+ agent.tools = [Tools.file_search];+ const runtime = projectRuntime();+ runtime.appConfig.filters = projectFilePolicy;+ const getProjectFiles = jest.fn().mockResolvedValue([{ ...canonicalFile, text: 'BLOCKED' }]);+ await expect(+ initializeAgent(+ {+ runtime,+ agent,+ loadTools,+ endpointOption: { endpoint: EModelEndpoint.agents },+ allowedProviders: new Set([Providers.OPENAI]),+ useChatProjectContext: true,+ },+ { ...db, getProjectFiles },+ ),+ ).rejects.toMatchObject({ code: 'content_filter_block' });+ expect(loadTools).not.toHaveBeenCalled();+ expect(db.updateFilesUsage).not.toHaveBeenCalled();+ });++ it.each(['expired', 'changed-version'])(+ 'rejects a %s resource during policy hydration instead of replacing the admitted snapshot',+ async (change) => {+ const { agent, loadTools, db } = createMocks();+ agent.tools = [Tools.file_search];+ const runtime = projectRuntime();+ runtime.appConfig.filters = projectFilePolicy;+ const changedFile =+ change === 'expired'+ ? { ...canonicalFile, expiredAt: new Date(0) }+ : { ...canonicalFile, updatedAt: new Date('2030-01-01') };+ await expect(+ initializeAgent(+ {+ runtime,+ agent,+ loadTools,+ endpointOption: { endpoint: EModelEndpoint.agents },+ allowedProviders: new Set([Providers.OPENAI]),+ useChatProjectContext: true,+ },+ { ...db, getProjectFiles: jest.fn().mockResolvedValue([changedFile]) },+ ),+ ).rejects.toMatchObject({+ code: 'PROJECT_RESOURCES_CHANGED',+ status: 409,+ retryable: true,+ });+ expect(loadTools).not.toHaveBeenCalled();+ expect(db.updateFilesUsage).not.toHaveBeenCalled();+ },+ );++ it('does not inject Project guidance or resources into an auxiliary opt-out', async () => {+ const { agent, loadTools, db } = createMocks();+ agent.tools = [Tools.file_search];+ agent.additional_instructions = 'Auxiliary Agent guidance.';++ const result = await initializeAgent(+ {+ runtime: projectRuntime(),+ agent,+ loadTools,+ endpointOption: { endpoint: EModelEndpoint.agents },+ allowedProviders: new Set([Providers.OPENAI]),+ useChatProjectContext: false,+ },+ db,+ );++ expect(result.additional_instructions).toBe('Auxiliary Agent guidance.');+ expect(result.additional_instructions).not.toContain('Project guidance');+ expect(result.tool_resources).toBeUndefined();+ });++ it('never enables disabled File Search for Project files', async () => {+ const { agent, loadTools, db } = createMocks();++ const result = await initializeAgent(+ {+ runtime: { ...projectRuntime(), chatProjectFiles: undefined },+ agent,+ loadTools,+ endpointOption: { endpoint: EModelEndpoint.agents },+ allowedProviders: new Set([Providers.OPENAI]),+ useChatProjectContext: true,+ },+ db,+ );++ expect(result.tools).toEqual([]);+ expect(result.toolDefinitions).toEqual([]);+ expect(result.tool_resources).toBeUndefined();+ expect(db.getFiles).not.toHaveBeenCalled();+ });+});+describe('initializeAgent — current content policy preflight', () => {beforeEach(() => {jest.clearAllMocks();@@ -2442,6 +2891,88 @@ describe('initializeAgent — skill `allowed-tools` union (Phase 6)', () => {expect(definedNames).toContain('web_search');expect(definedNames).not.toContain('mcp__broken__tool');});+ it('removes skill-added Project resources before retrying without denied tools', async () => {+ const { agent, req, loadTools, db } = createMocks();+ const { Types } = await import('mongoose');+ const skillId = new Types.ObjectId();+ const projectFile = {+ file_id: 'project-file',+ filename: 'project.txt',+ type: 'text/plain',+ embedded: true,+ } as TFile;+ agent.tools = [];++ let call = 0;+ loadTools.mockImplementation(async ({ tools }: { tools: string[] }) => {+ call += 1;+ if (call === 1) {+ return undefined;+ }+ return {+ tools: [],+ toolContextMap: {},+ toolDefinitions: tools.map((name) => ({ name, description: '', parameters: {} })),+ hasDeferredTools: false,+ };+ });++ const getSkillByName = buildGetSkillByName(+ 'project-file-search-fallback',+ [Tools.file_search],+ skillId,+ req.user!.id,+ );++ const result = await initializeAgent(+ {+ runtime: {+ user: req.user,+ appConfig: {+ endpoints: {+ [EModelEndpoint.agents]: {+ capabilities: [AgentCapabilities.file_search],+ },+ },+ } as NonNullable<ServerRequest['config']>,+ requestBody: {},+ turnStartedAt: 1,+ chatProjectContext: {+ projectId: 'project-1',+ contextRevision: 1,+ instructions: '',+ file_ids: [projectFile.file_id],+ resources: [+ {+ file_id: projectFile.file_id,+ identity: 'canonical-project-file',+ availability: 'ready',+ version: 'fixture-version',+ file: projectFile,+ },+ ],+ },+ },+ req,+ agent,+ loadTools,+ endpointOption: { endpoint: EModelEndpoint.agents },+ allowedProviders: new Set([Providers.OPENAI]),+ useChatProjectContext: true,+ accessibleSkillIds: [skillId],+ manualSkills: ['project-file-search-fallback'],+ },+ { ...db, listSkillsByAccess: emptyListSkillsByAccess, getSkillByName },+ );++ expect(loadTools).toHaveBeenCalledTimes(2);+ expect(loadTools.mock.calls[0][0].tool_resources).toEqual({+ [EToolResources.file_search]: { files: [projectFile] },+ });+ expect(loadTools.mock.calls[1][0].tools).toEqual([]);+ expect(loadTools.mock.calls[1][0].tool_resources).toBeUndefined();+ expect(result.tool_resources).toBeUndefined();+ });it('retries loadTools without extras when the union call throws (agent tools must still load)', async () => {const { agent, req, res, loadTools, db } = createMocks();diff --git a/packages/api/src/agents/compatibility.spec.ts b/packages/api/src/agents/compatibility.spec.tsindex e36b680fe0..d961765aa6 100644--- a/packages/api/src/agents/compatibility.spec.ts+++ b/packages/api/src/agents/compatibility.spec.ts@@ -7,6 +7,7 @@ import {normalizeAgentEventActorSummary,type AgentTurnSemanticContext,} from './compatibility';+import { getChatProjectContextKey } from '../projects/context';const context = (): AgentTurnSemanticContext => ({checkpointerType: 'mongodb',@@ -77,6 +78,26 @@ describe('agent context compatibility', () => {createAgentContextFingerprint(original).digest,);});+ it('invalidates warm context when the project identity or revision changes', () => {+ const original = createAgentContextFingerprint({+ ...context(),+ projectContextKey: 'project:p1:r1',+ });+ const changed = createAgentContextFingerprint({+ ...context(),+ projectContextKey: 'project:p1:r2',+ });+ expect(changed.digest).not.toBe(original.digest);+ });++ it('keeps a no-project fingerprint equal to one written before projects carried a key', () => {+ const legacy = createAgentContextFingerprint(context());+ const current = createAgentContextFingerprint({+ ...context(),+ projectContextKey: getChatProjectContextKey(null),+ });+ expect(agentContextFingerprintsMatch(legacy, current)).toBe(true);+ });it('excludes credential values from compatibility', () => {const left = context();diff --git a/packages/api/src/agents/compatibility.ts b/packages/api/src/agents/compatibility.tsindex 48e58de70e..fd4f2f2950 100644--- a/packages/api/src/agents/compatibility.ts+++ b/packages/api/src/agents/compatibility.ts@@ -6,6 +6,7 @@ import {MAX_AGENT_EVENT_ACTOR_TOOL_NAME_LENGTH,} from '@librechat/data-schemas';import type { IAgentEventActorSummary } from '@librechat/data-schemas';+import { NO_CHAT_PROJECT_CONTEXT_KEY } from '../projects/context';export const AGENT_CONTEXT_FINGERPRINT_VERSION = 1;export const AGENT_GRAPH_SCHEMA_VERSION = 1;@@ -52,6 +53,8 @@ export interface AgentTurnSemanticContext {memory?: readonly AgentContextMemorySnapshot[];checkpointerType?: string;discoveredToolNames?: readonly string[];+ /** Server-owned ChatProject identity/revision; instruction text is hashed on agents. */+ projectContextKey?: string;checkpointFormatVersion?: number;graphSchemaVersion?: number;}@@ -253,6 +256,10 @@ export function createAgentContextFingerprint(discoveredToolNames: normalizeAgentEventActorDiscoveredTools(input.discoveredToolNames),approvalPolicy: input.approvalPolicy,retainedAnswers: input.retainedAnswers,+ /* A turn outside any project hashes as it did before projects carried context,+ * so checkpoints written without the key keep matching. */+ projectContextKey:+ input.projectContextKey === NO_CHAT_PROJECT_CONTEXT_KEY ? undefined : input.projectContextKey,agents: input.agents.map((agent) => ({...agent,modelParameters: redactModelParameterCredentials(agent.modelParameters),@@ -306,6 +313,8 @@ export function createInitializedAgentContextFingerprint(input: {memory?: readonly AgentContextMemorySnapshot[];checkpointerType?: string;discoveredToolNames?: readonly string[];+ /** Server-owned ChatProject identity/revision; instruction text is hashed on agents. */+ projectContextKey?: string;}): AgentContextFingerprint {return createAgentContextFingerprint({checkpointerType: input.checkpointerType,@@ -313,6 +322,7 @@ export function createInitializedAgentContextFingerprint(input: {retainedAnswers: input.retainedAnswers,memory: input.memory,discoveredToolNames: input.discoveredToolNames,+ projectContextKey: input.projectContextKey,agents: input.agents.map((agent, index) => ({id: agent.id,version: agent.version,diff --git a/packages/api/src/agents/conversationSymbols.ts b/packages/api/src/agents/conversationSymbols.tsnew file mode 100644index 0000000000..4d79ac3b5e--- /dev/null+++ b/packages/api/src/agents/conversationSymbols.ts@@ -0,0 +1,6 @@+/**+ * Brands lineage-only conversation snapshots so consumers do not treat them as authoritative.+ */+export const PARTIAL_RESOLVED_CONVERSATION: unique symbol = Symbol.for(+ 'librechat.resolvedConversation.partial',+);diff --git a/packages/api/src/agents/discovery.ts b/packages/api/src/agents/discovery.tsindex 5ef00a003f..bbe5f85def 100644--- a/packages/api/src/agents/discovery.ts+++ b/packages/api/src/agents/discovery.ts@@ -125,12 +125,14 @@ export interface DiscoverConnectedAgentsParams {statefulSessionsAvailable?: InitializeAgentParams['statefulSessionsAvailable'];/** Deployment policy for stateful workspace scopes, forwarded unchanged to every referenced agent. */allowedStatefulCodeEnvironments?: InitializeAgentParams['allowedStatefulCodeEnvironments'];+ memoryAvailable?: InitializeAgentParams['memoryAvailable'];/**- * Run-level inline memory availability gate. Forwarded verbatim to every- * handoff agent so sub-agents that list the `memory` capability expand the- * `set_memory` + `delete_memory` pair only when the parent run permits it.+ * Explicitly enables the authoritative ChatProject guidance/resources for+ * every discovered handoff and saved graph member. This is intentionally+ * independent of the request marker so remote callers can opt in without+ * broadening unrelated agent initialization.*/- memoryAvailable?: InitializeAgentParams['memoryAvailable'];+ useChatProjectContext?: InitializeAgentParams['useChatProjectContext'];/*** Run-level `run_in_background` capability gate. Forwarded verbatim so a* handoff/connected agent's own event-driven tools with@@ -261,6 +263,7 @@ async function initializeReferencedAgent(endpoint: EModelEndpoint.agents,},allowedProviders: params.allowedProviders,+ useChatProjectContext: params.useChatProjectContext,accessibleSkillIds: scopedSkillIds,skillAuthoringAvailable: params.computeSkillAuthoringAvailable?.(agent, scopedSkillIds),skillStates: params.skillStates,diff --git a/packages/api/src/agents/guard.ts b/packages/api/src/agents/guard.tsindex 480b67c882..41e53d4114 100644--- a/packages/api/src/agents/guard.ts+++ b/packages/api/src/agents/guard.ts@@ -2,6 +2,7 @@ import { Constants } from 'librechat-data-provider';import type { ConversationMethods, IConversation } from '@librechat/data-schemas';import type { NextFunction, Request, RequestHandler, Response } from 'express';import type { SubagentThreadTaskStore } from './subagentThreads';+import { PARTIAL_RESOLVED_CONVERSATION } from './conversationSymbols';import { isReservedSubagentThreadId } from './subagentThreadIds';import { isAgentEventRetentionActive } from './eventRetention';@@ -52,15 +53,6 @@ interface ResolvedConversationRequest extends Request {_agentEventBindingTenantId?: string;}-/**- * Brands the lineage-only conversation `isBoundEventContinuation` synthesizes: it stands in- * for binding checks but carries none of the stored document's optional fields, so readers- * of `req.resolvedConversation` must not treat its absent fields as authoritative.- */-export const PARTIAL_RESOLVED_CONVERSATION: unique symbol = Symbol.for(- 'librechat.resolvedConversation.partial',-);-function applyEventBindingContext(request: ResolvedConversationRequest,conversation: IConversation,diff --git a/packages/api/src/agents/hitl/policy.spec.ts b/packages/api/src/agents/hitl/policy.spec.tsindex 7d4b913b42..c6f3ce69a8 100644--- a/packages/api/src/agents/hitl/policy.spec.ts+++ b/packages/api/src/agents/hitl/policy.spec.ts@@ -426,10 +426,11 @@ describe('toClientPendingAction', () => {],};- test('omits server-only replay state, keeping the fields the client renders from', () => {+ test('omits server-only replay and project context state', () => {const full = buildPendingAction(payload, {streamId: 'stream-1',conversationId: 'conv-1',+ projectContextKey: 'project:p1:r2',requestFingerprint: 'fp-hash',requestFingerprintV2: 'fp-v2-hash',resumeContext: {@@ -448,6 +449,7 @@ describe('toClientPendingAction', () => {expect(clientSafe?.requestFingerprint).toBeUndefined();expect(clientSafe?.requestFingerprintV2).toBeUndefined();expect(clientSafe?.codeExecutionBinding).toBeUndefined();+ expect(clientSafe?.projectContextKey).toBeUndefined();expect(clientSafe?.actionId).toBe(full.actionId);expect(clientSafe?.streamId).toBe('stream-1');expect(clientSafe?.payload).toBe(full.payload);@@ -459,6 +461,7 @@ describe('toClientPendingAction', () => {version: 1,targets: [{ agentId: 'agent-1', targetHash: 'a'.repeat(64) }],});+ expect(full.projectContextKey).toBe('project:p1:r2');});test('passes through nullish input', () => {diff --git a/packages/api/src/agents/hitl/policy.ts b/packages/api/src/agents/hitl/policy.tsindex 092d6e2b23..121a97528f 100644--- a/packages/api/src/agents/hitl/policy.ts+++ b/packages/api/src/agents/hitl/policy.ts@@ -383,6 +383,8 @@ export interface PendingActionContext {interruptId?: string;/** LangGraph `thread_id` (`RunInterruptResult.threadId`) for cross-process resume. */threadId?: string;+ /** Server-only project context key captured at pause time. */+ projectContextKey?: string;/** Fingerprint of the graph-determining request fields; see {@link computeAgentRequestFingerprint}. */requestFingerprint?: string;/** Current fingerprint; the legacy field remains populated for rolling-deploy compatibility. */@@ -921,6 +923,7 @@ export function buildPendingAction(expiresAt,interruptId: ctx.interruptId,threadId: ctx.threadId,+ projectContextKey: ctx.projectContextKey,requestFingerprint: ctx.requestFingerprint,requestFingerprintV2: ctx.requestFingerprintV2,resumeContext: ctx.resumeContext,@@ -929,11 +932,10 @@ export function buildPendingAction(}/**- * Client-facing projection of a pending action. `requestFingerprint`, `resumeContext`, and- * `codeExecutionBinding`- * are server-only replay state — `resumeContext` in particular carries the resolved- * model parameters — so every copy that leaves the server (SSE, status, resume state)- * must go through this. The full record stays in the job store for the resume route.+ * Client-facing projection of a pending action. `projectContextKey`, `requestFingerprint`,+ * `resumeContext`, and `codeExecutionBinding` are server-only replay state. `resumeContext`+ * carries resolved model parameters, so every copy that leaves the server (SSE, status,+ * resume state) must go through this. The full record stays in the job store for resume.*/export function toClientPendingAction(pendingAction: Agents.PendingAction | undefined | null,@@ -942,6 +944,7 @@ export function toClientPendingAction(return undefined;}const {+ projectContextKey: _projectContextKey,requestFingerprint: _requestFingerprint,requestFingerprintV2: _requestFingerprintV2,resumeContext: _resumeContext,diff --git a/packages/api/src/agents/initialize.files.spec.ts b/packages/api/src/agents/initialize.files.spec.tsindex c2875779dc..bbb57f2c44 100644--- a/packages/api/src/agents/initialize.files.spec.ts+++ b/packages/api/src/agents/initialize.files.spec.ts@@ -5,7 +5,7 @@ import {readResolvedConversationFiles,resolveResendToolResources,} from './initialize';-import { PARTIAL_RESOLVED_CONVERSATION } from './guard';+import { PARTIAL_RESOLVED_CONVERSATION } from './conversationSymbols';describe('readResolvedConversationFiles', () => {const conversationId = 'conversation-1';diff --git a/packages/api/src/agents/initialize.ts b/packages/api/src/agents/initialize.tsindex cd192e7e06..9f277241cb 100644--- a/packages/api/src/agents/initialize.ts+++ b/packages/api/src/agents/initialize.ts@@ -29,7 +29,7 @@ import type {TurnFileConsumers,} from 'librechat-data-provider';import type { GenericTool, LCToolRegistry, ToolMap, LCTool } from '@librechat/agents';-import type { IMongoFile, FileOwnerScope } from '@librechat/data-schemas';+import type { AppConfig, IMongoFile, FileOwnerScope } from '@librechat/data-schemas';import type { Request, Response as ServerResponse } from 'express';import type {TFileUpdate,@@ -58,8 +58,10 @@ import type { LCAvailableTools, RequestScopedMCPConnectionStore } from '../mcp/timport type { ContentTraversalLimitError } from '../protection/adapters/nested';import type { SkillContentInput } from '../protection/adapters/submissions';import type { RepositoryInstructionSource } from '../code/instructions';+import type { ResolvedChatProjectContext } from '../projects/context';import type { TextContentFragment } from '../protection/types';import type { CheckAccessParams } from '../middleware/access';+import type { GetProjectFiles } from '../projects/resources';import type { MCPToolAlias } from '~/tools/classification';import type { AgentExecutionContext } from './runtime';import {@@ -77,6 +79,12 @@ import {type CodeEnvironmentConfig,type CodeExecutionContext,} from './execution';+import {+ resolveChatProjectFiles,+ resolveChatProjectPolicyFiles,+ toCanonicalProjectResource,+ toRuntimeFile,+} from '../projects/resources';import {getContentTraversalFragments,isContentTraversalProtected,@@ -101,16 +109,22 @@ import {splitMCPToolKey,normalizeAgentToolKeys,} from '~/mcp/utils';+import {+ formatChatProjectInstructions,+ hydrateChatProjectContextResources,+} from '../projects/context';import {createStatefulCodeEnvironmentPolicyError,isFatalAgentInitializationError,} from './errors';+import { assertChatProjectInstructions, ChatProjectResourcesChangedError } from '../projects/turn';import { extractAgentContent, extractSkillContent } from '../protection/adapters/submissions';import { createConfiguredContentInspector, inspectContent } from '../protection/runtime';import { assertAgentAttachmentLimits, isModelBoundAttachmentFile } from './attachments';import { resolveAttachedWorkspaceCommandTimeoutMax } from '~/code/command';import { assertModelBoundContent } from '../middleware/modelBoundContent';import { isImplicitStatefulCodeRouteAvailable } from '../code/config';+import { PARTIAL_RESOLVED_CONVERSATION } from './conversationSymbols';import { registerMemoryTools, memoryToolUsageGuard } from './memory';import { applyIntentLabels, sanitizeIntentLabels } from './intent';import { ContentFilterError } from '../middleware/contentFilter';@@ -118,8 +132,8 @@ import { resolveToolRoleGrants } from '~/tools/rolePermissions';import { createRequestAgentExecutionContext } from './runtime';import { resolveTurnDeliveryRouting } from './files/delivery';import { filterFilesByEndpointRuntimeConfig } from '~/files';+import { hasActiveFilePolicy } from '../protection/files';import { hasActiveFileFieldPolicy } from '~/protection';-import { PARTIAL_RESOLVED_CONVERSATION } from './guard';import { applyBackgroundToolCalls } from './background';import { applyTurnDelivery } from './files/delivery';import { generateArtifactsPrompt } from '~/prompts';@@ -269,6 +283,99 @@ function appendAdditionalInstructions(agent: Agent, text?: string | null): void.join('\n\n');}+function appendProjectContextInstructions(+ agent: Agent,+ context: ResolvedChatProjectContext | null | undefined,+): void {+ const instruction = formatChatProjectInstructions(context);+ if (instruction === '' || agent.additional_instructions?.includes(instruction)) {+ return;+ }+ appendAdditionalInstructions(agent, instruction);+}+function addProjectFilesToFileSearch(+ resources: AgentToolResources | undefined,+ files: readonly TFile[] | undefined,+ effectiveToolNames: readonly string[],+ appConfig: AppConfig | undefined,+ fileSearchAvailable?: boolean,+): AgentToolResources | undefined {+ if (files == null || files.length === 0) {+ return resources;+ }+ const capabilities = appConfig?.endpoints?.[EModelEndpoint.agents]?.capabilities ?? [];+ if (!capabilities.includes(AgentCapabilities.file_search)) {+ return resources;+ }+ if (fileSearchAvailable === false) {+ return resources;+ }+ if (!effectiveToolNames.includes(Tools.file_search)) {+ return resources;+ }+ const current = resources?.[EToolResources.file_search] ?? {};+ const currentFiles = current.files ?? [];+ const seen = new Set(currentFiles.map((file) => file.file_id));+ const projectFiles = files.filter((file) => !seen.has(file.file_id));+ if (projectFiles.length === 0) {+ return resources;+ }+ return {+ ...(resources ?? {}),+ [EToolResources.file_search]: {+ ...current,+ files: currentFiles.concat(projectFiles),+ },+ };+}++async function resolveRuntimeProjectFiles({+ context,+ scope,+ getProjectFiles,+ filters,+}: {+ context: ResolvedChatProjectContext;+ scope: FileOwnerScope;+ getProjectFiles: GetProjectFiles;+ filters?: AppConfig['filters'];+}): Promise<TFile[]> {+ const files = await resolveChatProjectFiles({+ project: context,+ resources: context.resources,+ userId: scope.userId,+ tenantId: scope.tenantId ?? undefined,+ getProjectFiles,+ });+ if (!hasActiveFilePolicy(filters) || files.length === 0) {+ return files;+ }+ const policyFiles = await resolveChatProjectPolicyFiles({+ project: { file_ids: files.map((file) => file.file_id) },+ userId: scope.userId,+ tenantId: scope.tenantId ?? undefined,+ getProjectFiles,+ });+ const admittedById = new Map(context.resources.map((resource) => [resource.file_id, resource]));+ if (policyFiles.length !== files.length) {+ throw new ChatProjectResourcesChangedError();+ }+ for (const file of policyFiles) {+ const admitted = admittedById.get(file.file_id);+ const current = toCanonicalProjectResource(file);+ if (+ admitted?.availability !== 'ready' ||+ current.availability !== 'ready' ||+ current.identity !== admitted.identity ||+ current.version !== admitted.version+ ) {+ throw new ChatProjectResourcesChangedError();+ }+ }+ assertModelBoundContent({ filters, files: policyFiles });+ return policyFiles.map(toRuntimeFile);+}+/*** The request middleware already read this conversation once (`null` = looked up, absent).* A stored document without `files` genuinely has none; only the branded lineage-only@@ -776,7 +883,6 @@ export type InitializedAgent = Agent & {};export const DEFAULT_MAX_CONTEXT_TOKENS = 32000;-/** Returns true when a conversation-level choice disables an attached environment. */export function optsOutOfAttachedCodeEnvironment(agent: Agent,@@ -870,6 +976,8 @@ export interface InitializeAgentParams {allowedProviders: Set<string>;/** Whether this is the initial agent */isInitialAgent?: boolean;+ /** Enables authoritative ChatProject guidance/resources for conversation graph agents. */+ useChatProjectContext?: boolean;/** Accessible skill IDs for this user (pre-computed by the caller via ACL query) */accessibleSkillIds?: import('mongoose').Types.ObjectId[];/** Whether skill file authoring should be exposed even before a user has viewable skills. */@@ -951,6 +1059,8 @@ export interface InitializeAgentDbMethods extends EndpointDbMethods {fileIds?: string[],options?: { user?: string; tenantId?: string | null },) => Promise<unknown[]>;+ /** Get owner-scoped project files with optional content. */+ getProjectFiles: GetProjectFiles;/** Get files from database */getFiles: (filter: unknown, sort: unknown, select: unknown) => Promise<unknown[]>;/** Filter files by agent access permissions (ownership or agent attachment) */@@ -1053,7 +1163,7 @@ export async function initializeAgent(db?: InitializeAgentDbMethods,): Promise<InitializedAgent> {const {- agent,+ agent: inputAgent,loadTools,requestFiles = [],authorizedRunFiles,@@ -1063,18 +1173,30 @@ export async function initializeAgent(requestBody,allowedProviders,isInitialAgent = false,+ useChatProjectContext,} = params;const runtime =params.runtime ?? (params.req ? createRequestAgentExecutionContext(params.req) : null);if (runtime == null) {throw new Error('initializeAgent requires an explicit execution context');}+ const shouldUseChatProjectContext =+ useChatProjectContext ?? params.req?.chatProjectContextEnabled === true;+ const agent = shouldUseChatProjectContext ? { ...inputAgent } : inputAgent;const { user, appConfig } = runtime;const requestFileOwnerId = user?.id;const requestFileOwnerScope: FileOwnerScope | undefined = requestFileOwnerId? { userId: requestFileOwnerId, tenantId: user?.tenantId }: undefined;+ if (shouldUseChatProjectContext && runtime.chatProjectContext?.instructions.trim()) {+ assertChatProjectInstructions({+ context: runtime.chatProjectContext,+ filters: appConfig?.filters,+ });+ appendProjectContextInstructions(agent, runtime.chatProjectContext);+ }+if (!db) {throw new Error('initializeAgent requires db methods to be passed');}@@ -1276,7 +1398,56 @@ export async function initializeAgent(}let currentFiles: Array<IMongoFile | TFile> | undefined;+ const baseToolNames = agent.tools ?? [];+ /**+ * Pre-resolve manually-invoked + always-apply skill primes so their+ * `allowed-tools` can be unioned into the agent's effective tool set+ * BEFORE project resource hydration and `loadTools` run. Project files+ * must follow this same effective set, otherwise a skill-added+ * `file_search` tool cannot see its eligible Project files.+ */+ if (hasSkillAccess) {+ /** Skill `allowed-tools` are legacy-heal candidates too: a raw MCP key+ * declared before the normalized-key convention would neither dedupe+ * against the healed agent tools nor match the normalized-keyed tool+ * map, silently dropping the skill-contributed tool. Same lazy audit+ * and skip-on-unavailable semantics as the agent-key heal. */+ const combinedPrimes = [...(manualSkillPrimes ?? []), ...(alwaysApplySkillPrimes ?? [])];+ const primesNeedHeal = combinedPrimes.some((prime) =>+ prime.allowedTools?.some((name) => name.includes(Constants.mcp_delimiter)),+ );+ const primeHealNames = primesNeedHeal ? await resolveHealNames() : null;+ if (primeHealNames != null) {+ resolvedAuditNames = primeHealNames;+ }+ const primesForUnion =+ primeHealNames != null+ ? combinedPrimes.map((prime) =>+ prime.allowedTools?.length+ ? {+ ...prime,+ allowedTools: normalizeAgentToolKeys({+ tools: prime.allowedTools,+ toolOptions: undefined,+ rawServerNames: primeHealNames,+ }).tools,+ }+ : prime,+ )+ : combinedPrimes;+ if (primesForUnion.length > 0) {+ const union = unionPrimeAllowedTools({+ primes: primesForUnion,+ agentToolNames: baseToolNames,+ });+ extraAllowedToolNames = union.extraToolNames;+ perSkillExtras = union.perSkillExtras;+ }+ }+ const effectiveToolNames =+ extraAllowedToolNames.length > 0 ? [...baseToolNames, ...extraAllowedToolNames] : baseToolNames;+ const requestedToolNames = effectiveToolNames;const _modelOptions = structuredClone(Object.assign({ model: agent.model },@@ -1445,11 +1616,6 @@ export async function initializeAgent(codeEnvAvailable: params.codeEnvAvailable === true && !attachedEnvironmentOptOut,fileSearchAvailable: params.fileSearchAvailable,});- let runtimeToolResources = agent.tool_resources;- if (attachedEnvironmentOptOut && runtimeToolResources != null) {- runtimeToolResources = { ...runtimeToolResources };- delete runtimeToolResources[EToolResources.execute_code];- }/*** Load conversation files for ALL agents, not just the initial agent.@@ -1748,6 +1914,48 @@ export async function initializeAgent(});}+ const canUseProjectFileSearch =+ shouldUseChatProjectContext &&+ runtime.chatProjectContext != null &&+ effectiveToolNames.includes(Tools.file_search) &&+ params.fileSearchAvailable !== false &&+ (appConfig?.endpoints?.[EModelEndpoint.agents]?.capabilities ?? []).includes(+ AgentCapabilities.file_search,+ );+ let projectRuntimeFiles: TFile[] = [];+ if (canUseProjectFileSearch && runtime.chatProjectContext != null && requestFileOwnerScope) {+ runtime.chatProjectContextResourcesPromise ??=+ params.req?.chatProjectContextResourcesPromise ??+ hydrateChatProjectContextResources(runtime.chatProjectContext, {+ userId: requestFileOwnerScope.userId,+ tenantId: requestFileOwnerScope.tenantId,+ getProjectFiles: db.getProjectFiles,+ });+ if (params.req) {+ params.req.chatProjectContextResourcesPromise = runtime.chatProjectContextResourcesPromise;+ }+ runtime.chatProjectContext = await runtime.chatProjectContextResourcesPromise;+ if (params.req) {+ params.req.chatProjectContext = runtime.chatProjectContext;+ }+ runtime.chatProjectFilesPromise ??=+ params.req?.chatProjectFilesPromise ??+ resolveRuntimeProjectFiles({+ context: runtime.chatProjectContext,+ getProjectFiles: db.getProjectFiles,+ scope: requestFileOwnerScope,+ filters: appConfig?.filters,+ });+ if (params.req) {+ params.req.chatProjectFilesPromise = runtime.chatProjectFilesPromise;+ }+ projectRuntimeFiles = await runtime.chatProjectFilesPromise;+ runtime.chatProjectFiles = projectRuntimeFiles;+ if (params.req) {+ params.req.chatProjectFiles = projectRuntimeFiles;+ }+ }+/*** Usage accounting is the first file mutation. It runs only after every* hydrated file in the exact snapshot above has passed endpoint filtering@@ -1767,6 +1975,11 @@ export async function initializeAgent(});}+ let runtimeToolResources = agent.tool_resources;+ if (attachedEnvironmentOptOut && runtimeToolResources != null) {+ runtimeToolResources = { ...runtimeToolResources };+ delete runtimeToolResources[EToolResources.execute_code];+ }const {attachments: primedAttachments,requestAttachments: primedRequestAttachments,@@ -1775,7 +1988,6 @@ export async function initializeAgent(provisionState,warnings: provisionWarnings,} = await primeResources({- req: params.req,principal: user,getFiles: db.getFiles as never,filterFiles: db.filterFilesByAgentAccess,@@ -1827,71 +2039,23 @@ export async function initializeAgent(});},});-- /**- * Pre-resolve manually-invoked + always-apply skill primes so their- * `allowed-tools` can be unioned into the agent's effective tool set- * BEFORE `loadTools` runs. Single load is correctness-critical: a- * second `loadTools` pass would compute its own `userMCPAuthMap` /- * `toolContextMap` / OAuth flow state that the InitializedAgent never- * sees, so an MCP tool added via `allowed-tools` would be visible to- * the model but fail at execution time without its per-user auth- * context.- *- * Resolution uses `params.accessibleSkillIds` (not the active-filtered- * subset that `injectSkillCatalog` will produce later) — see- * `resolveManualSkills` doc for why a skill outside the catalog cap can- * still be authorizable for direct manual invocation.- *- * Manual + always-apply primes feed the same `unionPrimeAllowedTools`- * call — the helper is pure / set-based, so concatenating the two- * lists gives the right union with no double-counting. Manual primes- * go first so their names win on dedup (primes earlier in the list- * contribute before the same name gets deduped on a later prime).- */- if (hasSkillAccess) {- /** Skill `allowed-tools` are legacy-heal candidates too: a raw MCP key- * declared before the normalized-key convention would neither dedupe- * against the healed agent tools nor match the normalized-keyed tool- * map, silently dropping the skill-contributed tool. Same lazy audit- * and skip-on-unavailable semantics as the agent-key heal. */- const combinedPrimes = [...(manualSkillPrimes ?? []), ...(alwaysApplySkillPrimes ?? [])];- const primesNeedHeal = combinedPrimes.some((prime) =>- prime.allowedTools?.some((name) => name.includes(Constants.mcp_delimiter)),- );- const primeHealNames = primesNeedHeal ? await resolveHealNames() : null;- if (primeHealNames != null) {- resolvedAuditNames = primeHealNames;- }- const primesForUnion =- primeHealNames != null- ? combinedPrimes.map((prime) =>- prime.allowedTools?.length- ? {- ...prime,- allowedTools: normalizeAgentToolKeys({- tools: prime.allowedTools,- toolOptions: undefined,- rawServerNames: primeHealNames,- }).tools,- }- : prime,- )- : combinedPrimes;- if (primesForUnion.length > 0) {- const union = unionPrimeAllowedTools({- primes: primesForUnion,- agentToolNames: agent.tools ?? [],- });- extraAllowedToolNames = union.extraToolNames;- perSkillExtras = union.perSkillExtras;+ runtimeToolResources = addProjectFilesToFileSearch(+ tool_resources,+ projectRuntimeFiles,+ effectiveToolNames,+ appConfig,+ params.fileSearchAvailable,+ );+ const dropFileSearchResources = (): void => {+ if (runtimeToolResources?.[EToolResources.file_search] == null) {+ return;}+ const { [EToolResources.file_search]: _fileSearch, ...remaining } = runtimeToolResources;+ runtimeToolResources = Object.keys(remaining).length > 0 ? remaining : undefined;+ };+ if (params.fileSearchAvailable === false || !effectiveToolNames.includes(Tools.file_search)) {+ dropFileSearchResources();}-- const baseToolNames = agent.tools ?? [];- const requestedToolNames =- extraAllowedToolNames.length > 0 ? [...baseToolNames, ...extraAllowedToolNames] : baseToolNames;-/*** `loadTools` failures take two forms:* 1. The wrapper throws — rare; only when something around the@@ -1917,7 +2081,7 @@ export async function initializeAgent(tools,model: agent.model,tool_options: agent.tool_options,- tool_resources,+ tool_resources: runtimeToolResources,requestBody,codeExecutionContext,accessibleMcpServerNames: resolvedAuditNames,@@ -1942,6 +2106,9 @@ export async function initializeAgent(`[allowedTools] loadTools threw with ${extraAllowedToolNames.length} skill-added extra(s); retrying without them`,{ errorName: err instanceof Error ? err.name : 'UnknownError' },);+ if (!baseToolNames.includes(Tools.file_search)) {+ dropFileSearchResources();+ }loadToolsResult = await callLoadTools(baseToolNames);} else {throw err;@@ -1954,6 +2121,9 @@ export async function initializeAgent(logger.warn(`[allowedTools] loadTools returned no result with ${extraAllowedToolNames.length} skill-added extra(s); retrying without them.`,);+ if (!baseToolNames.includes(Tools.file_search)) {+ dropFileSearchResources();+ }loadToolsResult = await callLoadTools(baseToolNames);}@@ -2499,7 +2669,7 @@ export async function initializeAgent(toolRegistry,mcpAvailableTools,requestScopedConnections,- tool_resources,+ tool_resources: runtimeToolResources,userMCPAuthMap,toolDefinitions,hasDeferredTools,diff --git a/packages/api/src/agents/runtime.ts b/packages/api/src/agents/runtime.tsindex 527ffa7c47..358e7947de 100644--- a/packages/api/src/agents/runtime.ts+++ b/packages/api/src/agents/runtime.ts@@ -1,4 +1,6 @@import type { AppConfig, IConversation, IUser } from '@librechat/data-schemas';+import type { TFile } from 'librechat-data-provider';+import type { ResolvedChatProjectContext } from '../projects/context';import type { RequestBody, ServerRequest } from '~/types';/**@@ -18,6 +20,14 @@ export interface AgentExecutionContext {conversationCreatedAt?: string;/** Conversation already resolved by ingress. Presence distinguishes "not read" from absent. */resolvedConversation?: Partial<IConversation> | null;+ /** Authoritative per-turn project context; server-only and never request body data. */+ chatProjectContext?: ResolvedChatProjectContext | null;+ /** Metadata-only project files hydrated once per request for enabled file search tools. */+ chatProjectFiles?: TFile[];+ /** Shares in-flight project-context resource hydration across graph agents. */+ chatProjectContextResourcesPromise?: Promise<ResolvedChatProjectContext>;+ /** Shares in-flight hydration across concurrently initialized graph agents. */+ chatProjectFilesPromise?: Promise<TFile[]>;}/** Creates the transport-free context at the existing HTTP adapter seam. */@@ -29,6 +39,10 @@ export function createAgentExecutionContext({conversationCreatedAt,resolvedConversation,hasResolvedConversation = false,+ chatProjectContext,+ chatProjectFiles,+ chatProjectContextResourcesPromise,+ chatProjectFilesPromise,}: {user?: IUser;appConfig?: AppConfig;@@ -37,6 +51,10 @@ export function createAgentExecutionContext({conversationCreatedAt?: string;resolvedConversation?: Partial<IConversation> | null;hasResolvedConversation?: boolean;+ chatProjectContext?: ResolvedChatProjectContext | null;+ chatProjectFiles?: TFile[];+ chatProjectContextResourcesPromise?: Promise<ResolvedChatProjectContext>;+ chatProjectFilesPromise?: Promise<TFile[]>;}): AgentExecutionContext {const context: AgentExecutionContext = {user,@@ -44,6 +62,12 @@ export function createAgentExecutionContext({requestBody,turnStartedAt,conversationCreatedAt,+ ...(chatProjectContext !== undefined ? { chatProjectContext } : {}),+ ...(chatProjectContextResourcesPromise !== undefined+ ? { chatProjectContextResourcesPromise }+ : {}),+ ...(chatProjectFiles !== undefined ? { chatProjectFiles } : {}),+ ...(chatProjectFilesPromise !== undefined ? { chatProjectFilesPromise } : {}),};if (hasResolvedConversation) {context.resolvedConversation = resolvedConversation ?? null;@@ -66,5 +90,9 @@ export function createRequestAgentExecutionContext(conversationCreatedAt: req.conversationCreatedAt,resolvedConversation: req.resolvedConversation,hasResolvedConversation: Object.prototype.hasOwnProperty.call(req, 'resolvedConversation'),+ chatProjectContext: req.chatProjectContext,+ chatProjectFiles: req.chatProjectFiles,+ chatProjectContextResourcesPromise: req.chatProjectContextResourcesPromise,+ chatProjectFilesPromise: req.chatProjectFilesPromise,});}diff --git a/packages/api/src/conversations/save.ts b/packages/api/src/conversations/save.tsindex e2bd3d6a21..6ba8cde2cb 100644--- a/packages/api/src/conversations/save.ts+++ b/packages/api/src/conversations/save.ts@@ -169,12 +169,15 @@ async function writeConversation(): Promise<TurnConversationResult> {const { req, ctx, conversationId, endpoint, endpointType, endpointOptions = {} } = write;const agentOwned = isAgentOwned(write);+ const inserting = write.initialized !== true && existing == null;+ const { chatProjectId, ...storedOptions } = endpointOptions;const conversation = await deps.saveConvo(ctx,{endpoint,endpointType,- ...endpointOptions,+ ...storedOptions,+ ...(inserting && chatProjectId !== undefined ? { chatProjectId } : {}),conversationId: endpointOptions.conversationId ?? conversationId,},{@@ -182,8 +185,7 @@ async function writeConversation(unsetFields: existing != null ? getUnsetFields(existing, endpointOptions, agentOwned) : {},noUpsert: req?._agentEventBindingParentConversationId != null,initialAgentId: agentOwned ? (write.agentId ?? null) : null,- createdAtOnInsert:- write.initialized !== true && existing == null ? getCreatedAtOnInsert(req) : undefined,+ createdAtOnInsert: inserting ? getCreatedAtOnInsert(req) : undefined,...(appendMessageIds != null ? { appendMessageIds } : {}),...getReplyStamp(write),},diff --git a/packages/api/src/middleware/code.spec.ts b/packages/api/src/middleware/code.spec.tsindex 25947f8448..16e3310cb4 100644--- a/packages/api/src/middleware/code.spec.ts+++ b/packages/api/src/middleware/code.spec.ts@@ -1,61 +1,106 @@-import { rateLimit, ipKeyGenerator } from 'express-rate-limit';-import type { NextFunction, Request, Response } from 'express';-import {- codeEnvironmentPairingLimiter,- codeEnvironmentStatusIpLimiter,- codeEnvironmentStatusLimiter,-} from './code';-import { limiterCache } from '~/cache/cacheFactory';--jest.mock('express-rate-limit', () => ({- rateLimit: jest.fn(() => jest.fn((_req: Request, _res: Response, next: NextFunction) => next())),- ipKeyGenerator: jest.fn((ip: string | undefined) => ip ?? ''),-}));-jest.mock('~/cache/cacheFactory', () => ({ limiterCache: jest.fn(() => undefined) }));--const mockRateLimit = jest.mocked(rateLimit);-const mockIpKeyGenerator = jest.mocked(ipKeyGenerator);-const mockLimiterCache = jest.mocked(limiterCache);--type LimiterOptions = {- max: number;- windowMs: number;- keyGenerator: (req: Request) => string;-};+import express from 'express';+import request from 'supertest';+import type { RequestHandler } from 'express';+import type * as CodeMiddleware from './code';-describe('code environment limiters', () => {- test('uses a bounded per-user pairing bucket', () => {- const req = { user: { id: 'user-1' } } as unknown as Request;+jest.mock('~/cache/cacheFactory', () => ({ limiterCache: () => undefined }));- codeEnvironmentPairingLimiter(req, {} as Response, jest.fn());+function createApp(limiter: RequestHandler) {+ const app = express();+ app.set('trust proxy', 1);+ app.use((req, _res, next) => {+ Object.assign(req, { user: { id: req.get('x-test-user') } });+ next();+ });+ app.get('/', limiter, (_req, res) => {+ res.sendStatus(200);+ });+ return app;+}- const options = mockRateLimit.mock.calls[0]?.[0] as LimiterOptions;- expect(options).toEqual(expect.objectContaining({ max: 5, windowMs: 3_600_000 }));- expect(options.keyGenerator(req)).toBe('user-1');- expect(mockLimiterCache).toHaveBeenCalledWith('code_environment_pairing_user_limiter');+describe('code environment limiters', () => {+ let codeEnvironmentPairingLimiter: RequestHandler;+ let codeEnvironmentStatusIpLimiter: RequestHandler;+ let codeEnvironmentStatusLimiter: RequestHandler;++ beforeEach(() => {+ jest.replaceProperty(process, 'env', {+ ...process.env,+ CODE_ENVIRONMENT_PAIRING_USER_MAX: '2',+ CODE_ENVIRONMENT_PAIRING_USER_WINDOW: '2',+ CODE_ENVIRONMENT_STATUS_USER_MAX: '2',+ CODE_ENVIRONMENT_STATUS_IP_MAX: '2',+ });+ jest.isolateModules(() => {+ ({+ codeEnvironmentPairingLimiter,+ codeEnvironmentStatusIpLimiter,+ codeEnvironmentStatusLimiter,+ } = jest.requireActual<typeof CodeMiddleware>('./code'));+ });});- test('keys status user limits by immutable user ID', () => {- const req = { user: { id: 'user-1' }, ip: '2001:db8::1' } as unknown as Request;+ afterEach(() => jest.restoreAllMocks());- codeEnvironmentStatusLimiter(req, {} as Response, jest.fn());+ test('limits pairing per user and returns a bounded retry delay', async () => {+ const app = createApp(codeEnvironmentPairingLimiter);+ await request(app).get('/').set('x-test-user', 'pairing-user').expect(200);+ await request(app).get('/').set('x-test-user', 'pairing-user').expect(200);- const options = mockRateLimit.mock.calls[1]?.[0] as LimiterOptions;- expect(options).toEqual(expect.objectContaining({ max: 120, windowMs: 60_000 }));- expect(options.keyGenerator(req)).toBe('user-1');- expect(mockIpKeyGenerator).not.toHaveBeenCalled();- expect(mockLimiterCache).toHaveBeenCalledWith('code_environment_status_user_limiter');+ const limited = await request(app).get('/').set('x-test-user', 'pairing-user').expect(429);+ expect(limited.body.error.code).toBe('code_environment_pairing_rate_limited');+ expect(Number(limited.headers['retry-after'])).toBeGreaterThan(0);+ expect(Number(limited.headers['retry-after'])).toBeLessThanOrEqual(120);+ await request(app).get('/').set('x-test-user', 'other-pairing-user').expect(200);});- test('applies an independent normalized IP status limit', () => {- const req = { user: { id: 'user-1' }, ip: '2001:db8::1' } as unknown as Request;-- codeEnvironmentStatusIpLimiter(req, {} as Response, jest.fn());+ test('keeps the user status bucket across IP changes without limiting other users', async () => {+ const app = createApp(codeEnvironmentStatusLimiter);+ await request(app)+ .get('/')+ .set('x-test-user', 'status-user')+ .set('X-Forwarded-For', '192.0.2.1')+ .expect(200);+ await request(app)+ .get('/')+ .set('x-test-user', 'status-user')+ .set('X-Forwarded-For', '192.0.2.2')+ .expect(200);+ const limited = await request(app)+ .get('/')+ .set('x-test-user', 'status-user')+ .set('X-Forwarded-For', '192.0.2.3')+ .expect(429);+ expect(limited.body.error.code).toBe('code_environment_status_rate_limited');+ await request(app)+ .get('/')+ .set('x-test-user', 'other-status-user')+ .set('X-Forwarded-For', '192.0.2.1')+ .expect(200);+ });- const options = mockRateLimit.mock.calls[2]?.[0] as LimiterOptions;- expect(options).toEqual(expect.objectContaining({ max: 300, windowMs: 60_000 }));- expect(options.keyGenerator(req)).toBe('2001:db8::1');- expect(mockIpKeyGenerator).toHaveBeenCalledWith('2001:db8::1');- expect(mockLimiterCache).toHaveBeenCalledWith('code_environment_status_ip_limiter');+ test('shares the IP status bucket across users and normalized IPv6 addresses', async () => {+ const app = createApp(codeEnvironmentStatusIpLimiter);+ await request(app)+ .get('/')+ .set('x-test-user', 'ip-user-1')+ .set('X-Forwarded-For', '2001:db8:1::1')+ .expect(200);+ await request(app)+ .get('/')+ .set('x-test-user', 'ip-user-2')+ .set('X-Forwarded-For', '2001:db8:1::2')+ .expect(200);+ const limited = await request(app)+ .get('/')+ .set('x-test-user', 'ip-user-3')+ .set('X-Forwarded-For', '2001:db8:1::3')+ .expect(429);+ expect(limited.body.error.code).toBe('code_environment_status_rate_limited');+ await request(app)+ .get('/')+ .set('x-test-user', 'ip-user-1')+ .set('X-Forwarded-For', '2001:db8:2::1')+ .expect(200);});});diff --git a/packages/api/src/projects/context.spec.ts b/packages/api/src/projects/context.spec.tsnew file mode 100644index 0000000000..815b51a7cc--- /dev/null+++ b/packages/api/src/projects/context.spec.ts@@ -0,0 +1,256 @@+import type { CanonicalProjectResource, ProjectFileRecord } from './resources';+import { getChatProjectContextKey, resolveChatProjectContext } from './context';+import { PARTIAL_RESOLVED_CONVERSATION } from '../agents/conversationSymbols';+import { toCanonicalProjectResource } from './resources';++const project = {+ _id: 'project-a',+ instructions: 'Use the project policy.',+ contextRevision: 3,+ file_ids: ['file-a'],+};+const getProjectFiles = jest.fn().mockResolvedValue([]);++const missingResources = (fileIds: string[]): CanonicalProjectResource[] =>+ fileIds.map((file_id) => ({+ file_id,+ identity: 'missing',+ availability: 'unavailable',+ version: 'missing',+ }));++describe('resolveChatProjectContext', () => {+ it('uses existing conversation membership over a request project override', async () => {+ const getChatProject = jest.fn().mockResolvedValue(project);+ const context = await resolveChatProjectContext(+ {+ userId: 'user-a',+ conversationId: 'conversation-a',+ requestedProjectId: 'project-b',+ resolvedConversation: { conversationId: 'conversation-a', chatProjectId: 'project-a' },+ },+ { getConvo: jest.fn(), getChatProject, getProjectFiles },+ );++ expect(context?.projectId).toBe('project-a');+ expect(getChatProject).toHaveBeenCalledWith('user-a', 'project-a');+ expect(getChatProject).toHaveBeenCalledTimes(1);+ });+ it('keeps authorized guidance available when the unused resource lookup would fail', async () => {+ const getChatProject = jest.fn().mockResolvedValue(project);+ const getProjectFiles = jest+ .fn()+ .mockRejectedValue(new Error('Project resource lookup unavailable'));++ const guidanceOnly = await resolveChatProjectContext(+ { userId: 'user-a', requestedProjectId: 'project-a', includeResources: false },+ { getConvo: jest.fn(), getChatProject, getProjectFiles },+ );+ expect(guidanceOnly).toEqual(+ expect.objectContaining({+ projectId: 'project-a',+ instructions: 'Use the project policy.',+ file_ids: ['file-a'],+ resources: [],+ }),+ );+ expect(getProjectFiles).not.toHaveBeenCalled();++ await expect(+ resolveChatProjectContext(+ { userId: 'user-a', requestedProjectId: 'project-a' },+ { getConvo: jest.fn(), getChatProject, getProjectFiles },+ ),+ ).rejects.toThrow('Project resource lookup unavailable');+ expect(getProjectFiles).toHaveBeenCalledTimes(1);+ });++ it('preserves an authoritative unscoped conversation', async () => {+ const getChatProject = jest.fn();+ await expect(+ resolveChatProjectContext(+ {+ userId: 'user-a',+ conversationId: 'conversation-a',+ requestedProjectId: 'project-a',+ resolvedConversation: { conversationId: 'conversation-a', chatProjectId: null },+ },+ { getConvo: jest.fn(), getChatProject, getProjectFiles },+ ),+ ).resolves.toBeNull();+ expect(getChatProject).not.toHaveBeenCalled();+ });++ it('does not reassign legacy conversations that have no membership field', async () => {+ await expect(+ resolveChatProjectContext(+ {+ userId: 'user-a',+ conversationId: 'conversation-a',+ requestedProjectId: 'project-a',+ resolvedConversation: { conversationId: 'conversation-a' },+ },+ {+ getConvo: jest.fn(),+ getChatProject: jest.fn().mockResolvedValue(project),+ getProjectFiles,+ },+ ),+ ).resolves.toBeNull();+ });++ it('reloads partial event snapshots instead of inheriting their stale Project', async () => {+ const partial = {+ conversationId: 'conversation-a',+ chatProjectId: 'stale-project',+ [PARTIAL_RESOLVED_CONVERSATION]: true,+ };+ const context = await resolveChatProjectContext(+ {+ userId: 'user-a',+ conversationId: 'conversation-a',+ resolvedConversation: partial,+ },+ {+ getConvo: jest.fn().mockResolvedValue({+ conversationId: 'conversation-a',+ chatProjectId: 'project-a',+ }),+ getChatProject: jest.fn().mockResolvedValue(project),+ getProjectFiles,+ },+ );+ expect(context?.projectId).toBe('project-a');+ });++ it('rejects a Project from a different or missing tenant scope', async () => {+ for (const projectTenant of ['tenant-b', undefined]) {+ await expect(+ resolveChatProjectContext(+ { userId: 'user-a', tenantId: 'tenant-a', requestedProjectId: 'project-a' },+ {+ getConvo: jest.fn(),+ getChatProject: jest.fn().mockResolvedValue({ ...project, tenantId: projectTenant }),+ getProjectFiles,+ },+ ),+ ).rejects.toThrow('Project context unavailable');+ }+ });++ it('degrades to no project context when the stored membership project is unavailable', async () => {+ for (const storedProject of [null, { ...project, tenantId: 'tenant-b' }]) {+ await expect(+ resolveChatProjectContext(+ {+ userId: 'user-a',+ tenantId: 'tenant-a',+ conversationId: 'conversation-a',+ requestedProjectId: 'project-b',+ resolvedConversation: {+ conversationId: 'conversation-a',+ chatProjectId: 'project-a',+ tenantId: 'tenant-a',+ },+ },+ {+ getConvo: jest.fn(),+ getChatProject: jest.fn().mockResolvedValue(storedProject),+ getProjectFiles,+ },+ ),+ ).resolves.toBeNull();+ }+ });++ it('degrades when a loaded conversation references an unavailable project', async () => {+ const getConvo = jest+ .fn()+ .mockResolvedValue({ conversationId: 'conversation-a', chatProjectId: 'project-a' });+ const getChatProject = jest.fn().mockResolvedValue(null);+ await expect(+ resolveChatProjectContext(+ { userId: 'user-a', conversationId: 'conversation-a' },+ { getConvo, getChatProject, getProjectFiles },+ ),+ ).resolves.toBeNull();+ expect(getChatProject).toHaveBeenCalledWith('user-a', 'project-a');+ });++ it('rejects an unauthorized requested project for a new conversation', async () => {+ await expect(+ resolveChatProjectContext(+ { userId: 'user-a', requestedProjectId: 'project-a' },+ { getConvo: jest.fn(), getChatProject: jest.fn().mockResolvedValue(null), getProjectFiles },+ ),+ ).rejects.toThrow('Project context unavailable');+ });+ it('keeps the resume key stable for normalized file identities', () => {+ const file: ProjectFileRecord = {+ _id: '507f1f77bcf86cd799439011',+ file_id: 'file-a',+ filename: 'file-a.txt',+ filepath: '/uploads/file-a.txt',+ object: 'file',+ type: 'text/plain',+ bytes: 12,+ usage: 0,+ embedded: true,+ context: 'message_attachment',+ user: 'user-a',+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),+ };+ const makeContext = () => ({+ projectId: 'project-a',+ contextRevision: 1,+ instructions: '',+ file_ids: ['file-a'],+ resources: [toCanonicalProjectResource({ ...file })],+ });++ const first = makeContext();+ const second = makeContext();+ expect(first.resources[0]?.identity).toBe(file._id);+ expect(getChatProjectContextKey(first)).toBe(getChatProjectContextKey(second));+ });++ it('changes its stable key when revision or resources change without exposing instructions', () => {+ const first = getChatProjectContextKey({+ projectId: 'project-a',+ contextRevision: 1,+ instructions: 'secret one',+ file_ids: ['file-a'],+ resources: missingResources(['file-a']),+ });+ const second = getChatProjectContextKey({+ projectId: 'project-a',+ contextRevision: 2,+ instructions: 'secret two',+ file_ids: ['file-b'],+ resources: missingResources(['file-b']),+ });++ expect(first).not.toContain('secret');+ expect(first).not.toBe(second);+ });++ it('keeps distinct file ID sequences distinct in the resume key', () => {+ const first = getChatProjectContextKey({+ projectId: 'project-a',+ contextRevision: 1,+ instructions: '',+ file_ids: ['a', 'b,c'],+ resources: missingResources(['a', 'b,c']),+ });+ const second = getChatProjectContextKey({+ projectId: 'project-a',+ contextRevision: 1,+ instructions: '',+ file_ids: ['a,b', 'c'],+ resources: missingResources(['a,b', 'c']),+ });++ expect(first).not.toBe(second);+ });+});diff --git a/packages/api/src/projects/context.ts b/packages/api/src/projects/context.tsnew file mode 100644index 0000000000..e35a797b28--- /dev/null+++ b/packages/api/src/projects/context.ts@@ -0,0 +1,295 @@+import type { IChatProject, IConversation } from '@librechat/data-schemas';+import type { TEndpointOption } from 'librechat-data-provider';+import type { CanonicalProjectResource, GetProjectFiles } from './resources';+import { PARTIAL_RESOLVED_CONVERSATION } from '../agents/conversationSymbols';+import { resolveChatProjectResources } from './resources';++export interface ResolvedChatProjectContext {+ projectId: string;+ contextRevision: number;+ instructions: string;+ file_ids: string[];+ /** Owner-scoped canonical file metadata, with no extracted content. */+ resources: readonly CanonicalProjectResource[];+}+export type ConversationSnapshot = Partial<IConversation> & {+ conversationId?: string;+ chatProjectId?: string | null;+ user?: string;+ tenantId?: string | null;+};++type ProjectSnapshot = Pick<IChatProject, 'instructions' | 'contextRevision' | 'file_ids'> & {+ _id?: { toString(): string } | string;+ tenantId?: string | null;+};++export interface ResolveChatProjectContextInput {+ userId: string;+ tenantId?: string | null;+ conversationId?: string | null;+ requestedProjectId?: string | null;+ resolvedConversation?: ConversationSnapshot | null;+ /** Trusted server-side control for callers that only need project guidance. */+ includeResources?: boolean;+}+export interface ResolveChatProjectContextDeps {+ getConvo: (userId: string, conversationId: string) => Promise<ConversationSnapshot | null>;+ getChatProject: (userId: string, projectId: string) => Promise<ProjectSnapshot | null>;+ getProjectFiles: GetProjectFiles;+}++export const CHAT_PROJECT_CONTEXT_UNAVAILABLE = 'Project context unavailable';++/** The context key of a turn outside any project. */+export const NO_CHAT_PROJECT_CONTEXT_KEY = 'chat-project:none';++export interface ChatProjectTenantSource {+ user: { id: string; tenantId?: string | null };+ _agentEventBindingParentConversationId?: string | null;+ _agentEventBindingTenantId?: string | null;+}++/** An empty tenant id is no tenant, as the project file queries already treat it. */+export function isSameChatProjectTenant(+ actual: string | null | undefined,+ expected: string | null | undefined,+): boolean {+ return (actual || null) === (expected || null);+}++/** Bound child conversations resolve project context in the event binding's tenant. */+export function getChatProjectTenantId(req: ChatProjectTenantSource): string | null | undefined {+ return req._agentEventBindingParentConversationId != null+ ? req._agentEventBindingTenantId+ : req.user.tenantId || undefined;+}++export interface AgentProjectContextRequest extends ChatProjectTenantSource {+ body?: { chatProjectId?: string | null };+ chatProjectContext?: ResolvedChatProjectContext | null;+ chatProjectContextPromise?: Promise<ResolvedChatProjectContext | null>;+ chatProjectContextResourcesPromise?: Promise<ResolvedChatProjectContext>;+ chatProjectContextEnabled?: boolean;+ resolvedConversation?: ConversationSnapshot | null;+}++export async function hydrateChatProjectContextResources(+ context: ResolvedChatProjectContext,+ {+ userId,+ tenantId,+ getProjectFiles,+ }: {+ userId: string;+ tenantId?: string | null;+ getProjectFiles: GetProjectFiles;+ },+): Promise<ResolvedChatProjectContext> {+ if (context.resources.length === new Set(context.file_ids).size) {+ return context;+ }+ return {+ ...context,+ resources: await resolveChatProjectResources({+ project: { file_ids: context.file_ids },+ userId,+ tenantId: tenantId ?? undefined,+ getProjectFiles,+ }),+ };+}+export function startAgentProjectContextResolution({+ req,+ endpointOption,+ conversationId,+ isNewConvo,+ conversationAnchorPromise,+ getConvo,+ getChatProject,+ getProjectFiles,+}: {+ req: AgentProjectContextRequest;+ endpointOption?: Partial<TEndpointOption>;+ conversationId: string;+ isNewConvo: boolean;+ conversationAnchorPromise: Promise<{+ conversation: ConversationSnapshot | null | undefined;+ }>;+ getConvo: ResolveChatProjectContextDeps['getConvo'];+ getChatProject: ResolveChatProjectContextDeps['getChatProject'];+ getProjectFiles: GetProjectFiles;+}): Promise<ResolvedChatProjectContext | null> {+ if (req.chatProjectContext !== undefined) {+ return Promise.resolve(req.chatProjectContext);+ }+ if (req.chatProjectContextPromise !== undefined) {+ return req.chatProjectContextPromise;+ }++ const requestedProjectId =+ endpointOption?.chatProjectId !== undefined+ ? endpointOption.chatProjectId+ : req.body?.chatProjectId;+ const contextPromise = conversationAnchorPromise+ .then(({ conversation }) => {+ // An existing chat's undefined anchor is a failed read, not confirmed absence.+ if (conversation !== undefined || isNewConvo) {+ req.resolvedConversation = conversation ?? null;+ }+ return resolveChatProjectContext(+ {+ userId: req.user.id,+ tenantId: getChatProjectTenantId(req),+ conversationId,+ requestedProjectId,+ resolvedConversation: isNewConvo ? (conversation ?? null) : conversation,+ includeResources: false,+ },+ {+ getConvo: async (...args) => {+ const loaded = await getConvo(...args);+ if (!isNewConvo) {+ req.resolvedConversation = loaded;+ }+ return loaded;+ },+ getChatProject,+ getProjectFiles,+ },+ );+ })+ .then((context) => {+ req.chatProjectContext = context;+ req.chatProjectContextEnabled = true;+ return context;+ });+ req.chatProjectContextPromise = contextPromise;+ // Admission/idempotency may return before this promise is awaited. Attach a+ // rejection handler to avoid an unhandled rejection while preserving the+ // original promise for the eventual preflight await.+ contextPromise.catch(() => {});+ return contextPromise;+}+/**+ * Resolves the project bound to a turn. A full conversation read, including an explicit+ * absence of membership, is authoritative over all request-carried project fields.+ */+export async function resolveChatProjectContext(+ input: ResolveChatProjectContextInput,+ deps: ResolveChatProjectContextDeps,+): Promise<ResolvedChatProjectContext | null> {+ const {+ userId,+ tenantId,+ conversationId,+ requestedProjectId,+ resolvedConversation: suppliedConversation,+ includeResources = true,+ } = input;++ let conversation: ConversationSnapshot | null | undefined = suppliedConversation;+ if (+ suppliedConversation != null &&+ (suppliedConversation as Record<symbol, boolean | undefined>)[PARTIAL_RESOLVED_CONVERSATION] !==+ true+ ) {+ const suppliedUserId = suppliedConversation.user;+ if (+ (suppliedUserId != null && suppliedUserId !== userId) ||+ !isSameChatProjectTenant(suppliedConversation.tenantId, tenantId)+ ) {+ throw new Error(CHAT_PROJECT_CONTEXT_UNAVAILABLE);+ }+ }+ if (+ conversation != null &&+ (conversationId == null || conversation.conversationId === conversationId) &&+ (conversation as Record<symbol, boolean | undefined>)[PARTIAL_RESOLVED_CONVERSATION] !== true+ ) {+ // Reuse the complete ingress snapshot without another conversation query.+ } else if (+ Object.prototype.hasOwnProperty.call(input, 'resolvedConversation') &&+ suppliedConversation === null+ ) {+ conversation = null;+ } else if (typeof conversationId === 'string' && conversationId !== '') {+ conversation = await deps.getConvo(userId, conversationId);+ } else {+ conversation = undefined;+ }++ const conversationIsAuthoritative =+ conversation != null &&+ (conversationId == null || conversation.conversationId === conversationId) &&+ (conversation as Record<symbol, boolean | undefined>)[PARTIAL_RESOLVED_CONVERSATION] !== true;+ const rawProjectId = conversationIsAuthoritative+ ? conversation?.chatProjectId+ : requestedProjectId;+ const projectId =+ typeof rawProjectId === 'string' && rawProjectId.trim() !== '' ? rawProjectId : null;++ if (projectId == null) {+ return null;+ }++ const project = await deps.getChatProject(userId, projectId);+ if (project == null || !isSameChatProjectTenant(project.tenantId, tenantId)) {+ if (conversationIsAuthoritative) {+ return null;+ }+ throw new Error(CHAT_PROJECT_CONTEXT_UNAVAILABLE);+ }++ const projectIdFromRecord =+ typeof project._id === 'string' && project._id !== ''+ ? project._id+ : (project._id?.toString() ?? projectId);+ const file_ids = Array.isArray(project.file_ids)+ ? project.file_ids.filter((fileId): fileId is string => typeof fileId === 'string')+ : [];+ const resources =+ includeResources === false+ ? []+ : await resolveChatProjectResources({+ project: { file_ids },+ userId,+ tenantId: tenantId ?? undefined,+ getProjectFiles: deps.getProjectFiles,+ });+ return {+ projectId: projectIdFromRecord,+ contextRevision:+ typeof project.contextRevision === 'number' && Number.isSafeInteger(project.contextRevision)+ ? project.contextRevision+ : 0,+ instructions: typeof project.instructions === 'string' ? project.instructions : '',+ file_ids,+ resources,+ };+}++export function getChatProjectContextKey(+ context: ResolvedChatProjectContext | null | undefined,+): string {+ if (context == null) {+ return NO_CHAT_PROJECT_CONTEXT_KEY;+ }+ const resourceKey = context.resources.map((resource) => [+ resource.file_id,+ resource.identity,+ resource.availability,+ resource.version,+ ]);+ return `chat-project:${context.projectId}:${context.contextRevision}:${JSON.stringify(context.file_ids)}:${JSON.stringify(resourceKey)}`;+}++export function formatChatProjectInstructions(+ context: ResolvedChatProjectContext | null | undefined,+): string {+ if (context == null || context.instructions.trim() === '') {+ return '';+ }+ return `Project guidance (user-provided context; subordinate to system, platform, agent, and tool policies):+${context.instructions}`;+}diff --git a/packages/api/src/projects/handlers.spec.ts b/packages/api/src/projects/handlers.spec.tsnew file mode 100644index 0000000000..03965545f8--- /dev/null+++ b/packages/api/src/projects/handlers.spec.ts@@ -0,0 +1,265 @@+import { MAX_CHAT_PROJECT_INSTRUCTIONS_LENGTH } from 'librechat-data-provider';+import type { Response } from 'express';+import { createProjectHandlers } from './handlers';++const projectId = '507f1f77bcf86cd799439011';++function request(overrides: Record<string, unknown> = {}) {+ return {+ user: { id: 'owner', tenantId: 'tenant-a' },+ params: {},+ query: {},+ body: {},+ ...overrides,+ } as never;+}++function response() {+ const result = { statusCode: 200, body: undefined as unknown };+ const res = {+ status: jest.fn((statusCode: number) => {+ result.statusCode = statusCode;+ return res;+ }),+ json: jest.fn((body: unknown) => {+ result.body = body;+ return res;+ }),+ } as unknown as Response;+ return { res, result };+}++function setup(overrides: Partial<Parameters<typeof createProjectHandlers>[0]> = {}) {+ const deps = {+ listChatProjects: jest.fn(),+ createChatProject: jest.fn().mockResolvedValue({ _id: projectId }),+ getChatProject: jest.fn().mockResolvedValue({ _id: projectId, file_ids: [] }),+ updateChatProject: jest.fn().mockResolvedValue({ _id: projectId }),+ deleteChatProject: jest.fn().mockResolvedValue({ deletedCount: 1, modifiedCount: 1 }),+ assignConversationToProject: jest.fn(),+ addChatProjectFile: jest.fn(),+ removeChatProjectFile: jest.fn(),+ getProjectFiles: jest.fn().mockResolvedValue([]),+ getAvailableProjectFiles: jest.fn().mockResolvedValue({ files: [], nextCursor: null }),+ ...overrides,+ };+ return { handlers: createProjectHandlers(deps), deps };+}++describe('ChatProject handlers', () => {+ it.each([+ ['non-string', 42],+ ['oversized', 'x'.repeat(MAX_CHAT_PROJECT_INSTRUCTIONS_LENGTH + 1)],+ ])('rejects %s instructions on create before persistence', async (_label, instructions) => {+ const { handlers, deps } = setup();+ const { res, result } = response();+ await handlers.createProject(request({ body: { name: 'Project', instructions } }), res);+ expect(result.statusCode).toBe(400);+ expect(deps.createChatProject).not.toHaveBeenCalled();+ });++ it('rejects invalid update instructions before persistence', async () => {+ const { handlers, deps } = setup();+ const { res, result } = response();+ await handlers.updateProject(+ request({ params: { projectId }, body: { instructions: null } }),+ res,+ );+ expect(result.statusCode).toBe(400);+ expect(deps.updateChatProject).not.toHaveBeenCalled();+ });++ it('passes a contextRevision through and maps a stale one to a 409 conflict', async () => {+ const { handlers, deps } = setup({+ updateChatProject: jest.fn().mockRejectedValue(new Error('Project revision conflict')),+ });+ const { res, result } = response();+ await handlers.updateProject(+ request({ params: { projectId }, body: { name: 'Renamed', contextRevision: 3 } }),+ res,+ );+ expect(deps.updateChatProject).toHaveBeenCalledWith(+ 'owner',+ projectId,+ { name: 'Renamed', contextRevision: 3 },+ undefined,+ );+ expect(result.statusCode).toBe(409);+ expect(result.body).toEqual({+ message: 'Project was changed by another session',+ code: 'CHAT_PROJECT_CONFLICT',+ });+ });++ it('keeps last-writer behavior when contextRevision is absent and rejects invalid values', async () => {+ const updateChatProject = jest.fn().mockResolvedValue({ _id: projectId });+ const { handlers } = setup({ updateChatProject });+ const ok = response();+ await handlers.updateProject(request({ params: { projectId }, body: { name: 'A' } }), ok.res);+ expect(ok.result.statusCode).toBe(200);+ expect(updateChatProject.mock.calls[0][2]).toEqual({ name: 'A' });++ const bad = response();+ await handlers.updateProject(+ request({ params: { projectId }, body: { name: 'A', contextRevision: -1 } }),+ bad.res,+ );+ expect(bad.result.statusCode).toBe(400);+ expect(updateChatProject).toHaveBeenCalledTimes(1);+ });++ it('refuses an over-long description instead of storing a shortened one', async () => {+ const { handlers, deps } = setup();+ const description = 'd'.repeat(41);+ const config = { config: { projects: { maxDescriptionLength: 40 } } };++ const created = response();+ await handlers.createProject(+ request({ body: { name: 'Project', description }, ...config }),+ created.res,+ );+ expect(created.result.statusCode).toBe(400);+ expect(created.result.body).toEqual({ error: 'description must be at most 40 characters' });+ expect(deps.createChatProject).not.toHaveBeenCalled();++ const updated = response();+ await handlers.updateProject(+ request({ params: { projectId }, body: { description }, ...config }),+ updated.res,+ );+ expect(updated.result.statusCode).toBe(400);+ expect(deps.updateChatProject).not.toHaveBeenCalled();+ });++ it('surfaces atomic resource errors without pretending the attach succeeded', async () => {+ const { handlers } = setup({+ addChatProjectFile: jest.fn().mockRejectedValue(new Error('Project file limit reached')),+ });+ const { res, result } = response();+ await handlers.addProjectFile(+ request({ params: { projectId }, body: { file_id: 'file-1' } }),+ res,+ );+ expect(result.statusCode).toBe(409);+ expect(result.body).toEqual({ error: 'Project file limit reached' });+ });++ it('keeps missing resource references as unavailable placeholders', async () => {+ const { handlers } = setup({+ getChatProject: jest.fn().mockResolvedValue({+ _id: projectId,+ tenantId: 'tenant-a',+ file_ids: ['gone'],+ }),+ });+ const { res, result } = response();+ await handlers.listProjectFiles(request({ params: { projectId } }), res);+ expect(result.statusCode).toBe(200);+ expect(result.body).toEqual([{ file_id: 'gone', availability: 'unavailable' }]);+ });++ it.each(['listProjectFiles', 'listAvailableProjectFiles'] as const)(+ '%s treats an empty caller tenant as no tenant for a tenantless project',+ async (handler) => {+ const { handlers } = setup({+ getChatProject: jest.fn().mockResolvedValue({ _id: projectId, file_ids: [] }),+ });+ const { res, result } = response();+ await handlers[handler](+ request({ user: { id: 'owner', tenantId: '' }, params: { projectId } }),+ res,+ );+ expect(result.statusCode).toBe(200);+ },+ );++ it('denies attached-file metadata for a foreign tenant', async () => {+ const { handlers, deps } = setup({+ getChatProject: jest.fn().mockResolvedValue({+ _id: projectId,+ tenantId: 'tenant-b',+ file_ids: ['attached'],+ }),+ });+ const { res, result } = response();+ await handlers.listProjectFiles(request({ params: { projectId } }), res);+ expect(result.statusCode).toBe(404);+ expect(deps.getProjectFiles).not.toHaveBeenCalled();+ });++ it('excludes extracted text from available-file metadata', async () => {+ const file = {+ file_id: 'candidate',+ filename: 'candidate.txt',+ filepath: '/uploads/candidate.txt',+ object: 'file',+ type: 'text/plain',+ bytes: 10,+ usage: 0,+ embedded: true,+ context: 'message_attachment',+ user: 'owner',+ tenantId: 'tenant-a',+ text: 'must not be returned',+ };+ const { handlers } = setup({+ getChatProject: jest.fn().mockResolvedValue({+ _id: projectId,+ tenantId: 'tenant-a',+ file_ids: ['attached'],+ }),+ getAvailableProjectFiles: jest.fn().mockResolvedValue({+ files: [file],+ nextCursor: 'next',+ }),+ });+ const { res, result } = response();++ await handlers.listAvailableProjectFiles(+ request({+ params: { projectId },+ query: { limit: '2', cursor: projectId, search: 'candidate' },+ }),+ res,+ );++ expect(result.statusCode).toBe(200);+ expect(result.body).toMatchObject({ files: [{ file_id: 'candidate' }] });+ expect(result.body).not.toHaveProperty('files.0.text');+ });++ it.each([{ limit: '0' }, { limit: '51' }, { limit: '1.5' }, { limit: 'nope' }])(+ 'rejects invalid available-file limit %# before project access',+ async (query) => {+ const { handlers, deps } = setup();+ const { res, result } = response();+ await handlers.listAvailableProjectFiles(request({ params: { projectId }, query }), res);+ expect(result.statusCode).toBe(400);+ expect(deps.getChatProject).not.toHaveBeenCalled();+ },+ );++ it('rejects malformed available-file cursors before project access', async () => {+ const { handlers, deps } = setup();+ const { res, result } = response();+ await handlers.listAvailableProjectFiles(+ request({ params: { projectId }, query: { cursor: 'malformed' } }),+ res,+ );+ expect(result.statusCode).toBe(400);+ expect(deps.getChatProject).not.toHaveBeenCalled();+ });+ it('denies available-file metadata for a foreign tenant', async () => {+ const { handlers, deps } = setup({+ getChatProject: jest.fn().mockResolvedValue({+ _id: projectId,+ tenantId: 'tenant-b',+ file_ids: [],+ }),+ });+ const { res, result } = response();+ await handlers.listAvailableProjectFiles(request({ params: { projectId } }), res);+ expect(result.statusCode).toBe(404);+ expect(deps.getAvailableProjectFiles).not.toHaveBeenCalled();+ });+});diff --git a/packages/api/src/projects/handlers.ts b/packages/api/src/projects/handlers.tsindex 8ef4f72456..80a716d20b 100644--- a/packages/api/src/projects/handlers.ts+++ b/packages/api/src/projects/handlers.ts@@ -1,6 +1,19 @@-import { isValidObjectIdString, logger } from '@librechat/data-schemas';-+import {+ MAX_CHAT_PROJECT_DESCRIPTION_LENGTH,+ MAX_CHAT_PROJECT_INSTRUCTIONS_LENGTH,+} from 'librechat-data-provider';+import {+ DEFAULT_AVAILABLE_PROJECT_FILES_LIMIT,+ InvalidAvailableProjectFilesCursorError,+ MAX_AVAILABLE_PROJECT_FILES_LIMIT,+ parseAvailableProjectFilesCursor,+ logger,+ isValidObjectIdString,+} from '@librechat/data-schemas';import type {+ AppConfig,+ AvailableProjectFilesOptions,+ AvailableProjectFilesResult,ChatProjectMethods,ChatProjectSortBy,ChatProjectSortDirection,@@ -8,23 +21,29 @@ import type {UpdateChatProjectInput,} from '@librechat/data-schemas';import type { Request, Response } from 'express';-+import type { GetProjectFiles } from './resources';+import { toRuntimeFile, listChatProjectFileViews } from './resources';import { normalizeLimit, queryString } from '~/utils';+import { isSameChatProjectTenant } from './context';+const CHAT_PROJECT_CONFLICT = 'Project revision conflict';const PROJECT_NOT_FOUND = 'Project not found';const CONVERSATION_NOT_FOUND = 'Conversation not found';+const PROJECT_FILE_UNAVAILABLE = 'Project file unavailable';+const PROJECT_FILE_LIMIT_REACHED = 'Project file limit reached';const PROJECT_SORT_FIELDS = new Set<ChatProjectSortBy>(['name', 'createdAt', 'lastConversationAt']);interface ProjectUser {id: string;+ tenantId?: string;_id?: {toString(): string;};}-interface ProjectRequest extends Request {user?: ProjectUser;+ config?: AppConfig;}type ProjectHandlerDependencies = Pick<@@ -35,13 +54,32 @@ type ProjectHandlerDependencies = Pick<| 'updateChatProject'| 'deleteChatProject'| 'assignConversationToProject'->;+ | 'addChatProjectFile'+ | 'removeChatProjectFile'+> & {+ getProjectFiles: GetProjectFiles;+ getAvailableProjectFiles: (+ options: AvailableProjectFilesOptions,+ ) => Promise<AvailableProjectFilesResult>;+};const getUserId = (req: ProjectRequest): string => req.user?.id ?? req.user?._id?.toString() ?? '';const normalizeString = (value: string | null | undefined): string =>typeof value === 'string' ? value.trim() : '';+const parseAvailableProjectFilesLimit = (value: Request['query'][string]): number | null => {+ const raw = queryString(value);+ if (raw === undefined) {+ return DEFAULT_AVAILABLE_PROJECT_FILES_LIMIT;+ }+ if (!/^[1-9]\d*$/.test(raw)) {+ return null;+ }+ const limit = Number(raw);+ return Number.isSafeInteger(limit) && limit <= MAX_AVAILABLE_PROJECT_FILES_LIMIT ? limit : null;+};+const normalizeSortBy = (value: Request['query'][string]): ChatProjectSortBy | undefined => {const sortBy = queryString(value);return PROJECT_SORT_FIELDS.has(sortBy as ChatProjectSortBy)@@ -55,16 +93,46 @@ const normalizeSortDirection = (const sortDirection = queryString(value);return sortDirection === 'asc' || sortDirection === 'desc' ? sortDirection : undefined;};--const createProjectInput = (req: ProjectRequest): CreateChatProjectInput | null => {+const instructionValidationError = (+ value: unknown,+ maxInstructionsLength: number = MAX_CHAT_PROJECT_INSTRUCTIONS_LENGTH,+): string | null => {+ if (typeof value !== 'string') {+ return 'instructions must be a string';+ }+ if (value.length > maxInstructionsLength) {+ return `instructions must be at most ${maxInstructionsLength} characters`;+ }+ return null;+};+const createProjectInput = (+ req: ProjectRequest,+ maxInstructionsLength?: number,+ maxDescriptionLength: number = MAX_CHAT_PROJECT_DESCRIPTION_LENGTH,+): { input: CreateChatProjectInput; error?: never } | { input?: never; error: string } => {const name = normalizeString(req.body?.name);if (!name) {- return null;+ return { error: 'name is required' };+ }+ if (req.body?.instructions !== undefined) {+ const error = instructionValidationError(req.body.instructions, maxInstructionsLength);+ if (error) {+ return { error };+ }+ }+ const description = typeof req.body?.description === 'string' ? req.body.description : '';+ /* Refuse an over-long description rather than storing a silently shortened one, the way+ * instructions already answer. */+ if (description.trim().length > maxDescriptionLength) {+ return { error: `description must be at most ${maxDescriptionLength} characters` };}return {- name,- description: typeof req.body?.description === 'string' ? req.body.description : '',+ input: {+ name,+ description,+ ...(req.body?.instructions !== undefined && { instructions: req.body.instructions }),+ },};};@@ -75,6 +143,10 @@ export function createProjectHandlers(deps: ProjectHandlerDependencies): {getProject: (req: ProjectRequest, res: Response) => Promise<Response>;updateProject: (req: ProjectRequest, res: Response) => Promise<Response>;deleteProject: (req: ProjectRequest, res: Response) => Promise<Response>;+ listProjectFiles: (req: ProjectRequest, res: Response) => Promise<Response>;+ listAvailableProjectFiles: (req: ProjectRequest, res: Response) => Promise<Response>;+ addProjectFile: (req: ProjectRequest, res: Response) => Promise<Response>;+ removeProjectFile: (req: ProjectRequest, res: Response) => Promise<Response>;} {async function listProjects(req: ProjectRequest, res: Response): Promise<Response> {try {@@ -93,13 +165,21 @@ export function createProjectHandlers(deps: ProjectHandlerDependencies): {}async function createProject(req: ProjectRequest, res: Response): Promise<Response> {- const input = createProjectInput(req);- if (!input) {- return res.status(400).json({ error: 'name is required' });+ const parsed = createProjectInput(+ req,+ req.config?.projects?.maxInstructionsLength,+ req.config?.projects?.maxDescriptionLength,+ );+ if ('error' in parsed) {+ return res.status(400).json({ error: parsed.error });}try {- const project = await deps.createChatProject(getUserId(req), input);+ const project = await deps.createChatProject(+ getUserId(req),+ parsed.input,+ req.config?.projects,+ );return res.status(201).json(project);} catch (error) {logger.error('[projects] Error creating project', error);@@ -170,20 +250,173 @@ export function createProjectHandlers(deps: ProjectHandlerDependencies): {input.name = name;}if (req.body?.description !== undefined) {- input.description = typeof req.body.description === 'string' ? req.body.description : '';+ const description = typeof req.body.description === 'string' ? req.body.description : '';+ const maxDescriptionLength =+ req.config?.projects?.maxDescriptionLength ?? MAX_CHAT_PROJECT_DESCRIPTION_LENGTH;+ if (description.trim().length > maxDescriptionLength) {+ return res+ .status(400)+ .json({ error: `description must be at most ${maxDescriptionLength} characters` });+ }+ input.description = description;+ }+ if (req.body?.instructions !== undefined) {+ const error = instructionValidationError(+ req.body.instructions,+ req.config?.projects?.maxInstructionsLength,+ );+ if (error) {+ return res.status(400).json({ error });+ }+ input.instructions = req.body.instructions;+ }+ if (req.body?.contextRevision !== undefined) {+ const revision = req.body.contextRevision;+ if (!Number.isInteger(revision) || revision < 0) {+ return res.status(400).json({ error: 'contextRevision must be a non-negative integer' });+ }+ input.contextRevision = revision;}try {- const project = await deps.updateChatProject(getUserId(req), projectId, input);+ const project = await deps.updateChatProject(+ getUserId(req),+ projectId,+ input,+ req.config?.projects,+ );if (!project) {return res.status(404).json({ error: PROJECT_NOT_FOUND });}return res.status(200).json(project);} catch (error) {+ if (error instanceof Error && error.message === CHAT_PROJECT_CONFLICT) {+ return res.status(409).json({+ message: 'Project was changed by another session',+ code: 'CHAT_PROJECT_CONFLICT',+ });+ }logger.error('[projects] Error updating project', error);return res.status(500).json({ error: 'Error updating project' });}}+ async function listProjectFiles(req: ProjectRequest, res: Response): Promise<Response> {+ const { projectId } = req.params;+ if (!isValidObjectIdString(projectId)) {+ return res.status(404).json({ error: PROJECT_NOT_FOUND });+ }++ try {+ const project = await deps.getChatProject(getUserId(req), projectId);+ if (!project || !isSameChatProjectTenant(project.tenantId, req.user?.tenantId)) {+ return res.status(404).json({ error: PROJECT_NOT_FOUND });+ }+ const files = await listChatProjectFileViews({+ project,+ userId: getUserId(req),+ tenantId: project.tenantId,+ getProjectFiles: deps.getProjectFiles,+ });+ return res.status(200).json(files);+ } catch (error) {+ logger.error('[projects] Error listing project files', error);+ return res.status(500).json({ error: 'Error listing project files' });+ }+ }++ async function listAvailableProjectFiles(req: ProjectRequest, res: Response): Promise<Response> {+ const { projectId } = req.params;+ if (!isValidObjectIdString(projectId)) {+ return res.status(404).json({ error: PROJECT_NOT_FOUND });+ }++ const limit = parseAvailableProjectFilesLimit(req.query.limit);+ const cursor = queryString(req.query.cursor);+ if (limit == null || cursor === '') {+ return res.status(400).json({ error: 'Invalid project file pagination' });+ }++ try {+ parseAvailableProjectFilesCursor(cursor);+ const userId = getUserId(req);+ const project = await deps.getChatProject(userId, projectId);+ if (!project || !isSameChatProjectTenant(project.tenantId, req.user?.tenantId)) {+ return res.status(404).json({ error: PROJECT_NOT_FOUND });+ }+ const result = await deps.getAvailableProjectFiles({+ userId,+ tenantId: project.tenantId ?? null,+ excludedFileIds: project.file_ids ?? [],+ limit,+ cursor: cursor ?? null,+ search: queryString(req.query.search),+ });+ return res.status(200).json({+ files: result.files.map(toRuntimeFile),+ nextCursor: result.nextCursor,+ });+ } catch (error) {+ if (error instanceof InvalidAvailableProjectFilesCursorError || error instanceof RangeError) {+ return res.status(400).json({ error: 'Invalid project file pagination' });+ }+ logger.error('[projects] Error listing available project files', error);+ return res.status(500).json({ error: 'Error listing available project files' });+ }+ }++ async function addProjectFile(req: ProjectRequest, res: Response): Promise<Response> {+ const { projectId } = req.params;+ if (!isValidObjectIdString(projectId)) {+ return res.status(404).json({ error: PROJECT_NOT_FOUND });+ }+ const fileId = req.body?.file_id;+ if (typeof fileId !== 'string' || fileId.length === 0) {+ return res.status(400).json({ error: 'file_id must be a string' });+ }++ try {+ const project = await deps.addChatProjectFile(+ getUserId(req),+ projectId,+ fileId,+ req.config?.projects,+ );+ if (!project) {+ return res.status(404).json({ error: PROJECT_NOT_FOUND });+ }+ return res.status(200).json(project);+ } catch (error) {+ if (error instanceof Error && error.message === PROJECT_FILE_UNAVAILABLE) {+ return res.status(400).json({ error: PROJECT_FILE_UNAVAILABLE });+ }+ if (error instanceof Error && error.message === PROJECT_FILE_LIMIT_REACHED) {+ return res.status(409).json({ error: PROJECT_FILE_LIMIT_REACHED });+ }+ logger.error('[projects] Error adding project file', error);+ return res.status(500).json({ error: 'Error adding project file' });+ }+ }++ async function removeProjectFile(req: ProjectRequest, res: Response): Promise<Response> {+ const { projectId, fileId } = req.params;+ if (!isValidObjectIdString(projectId)) {+ return res.status(404).json({ error: PROJECT_NOT_FOUND });+ }+ if (typeof fileId !== 'string' || fileId.length === 0) {+ return res.status(400).json({ error: 'fileId must be a string' });+ }++ try {+ const project = await deps.removeChatProjectFile(getUserId(req), projectId, fileId);+ if (!project) {+ return res.status(404).json({ error: PROJECT_NOT_FOUND });+ }+ return res.status(200).json(project);+ } catch (error) {+ logger.error('[projects] Error removing project file', error);+ return res.status(500).json({ error: 'Error removing project file' });+ }+ }async function deleteProject(req: ProjectRequest, res: Response): Promise<Response> {const { projectId } = req.params;@@ -210,5 +443,9 @@ export function createProjectHandlers(deps: ProjectHandlerDependencies): {getProject,updateProject,deleteProject,+ listProjectFiles,+ listAvailableProjectFiles,+ addProjectFile,+ removeProjectFile,};}diff --git a/packages/api/src/projects/index.ts b/packages/api/src/projects/index.tsindex 6c6f862d01..d73b6e7e40 100644--- a/packages/api/src/projects/index.ts+++ b/packages/api/src/projects/index.ts@@ -1 +1,5 @@export * from './handlers';+export * from './resources';+export * from './context';+export * from './turn';+export * from './resume';diff --git a/packages/api/src/projects/resources.spec.ts b/packages/api/src/projects/resources.spec.tsnew file mode 100644index 0000000000..0eaf4f431e--- /dev/null+++ b/packages/api/src/projects/resources.spec.ts@@ -0,0 +1,240 @@+import mongoose from 'mongoose';+import { FileContext } from 'librechat-data-provider';+import { MongoMemoryServer } from 'mongodb-memory-server';+import { createModels, createMethods } from '@librechat/data-schemas';+import type { IChatProject, IMongoFile, ProjectFileRecord } from '@librechat/data-schemas';+import {+ getChatProjectFileAvailability,+ listChatProjectFileViews,+ resolveChatProjectFiles,+} from './resources';+import { getChatProjectContextKey, resolveChatProjectContext } from './context';++let mongoServer: InstanceType<typeof MongoMemoryServer>;+let File: mongoose.Model<IMongoFile>;+let modelsToCleanup: string[] = [];++beforeAll(async () => {+ mongoServer = await MongoMemoryServer.create();+ const models = createModels(mongoose);+ modelsToCleanup = Object.keys(models);+ Object.assign(mongoose.models, models);+ File = mongoose.models.File as mongoose.Model<IMongoFile>;+ await mongoose.connect(mongoServer.getUri());+});++afterAll(async () => {+ await mongoose.disconnect();+ await mongoServer.stop();+ for (const modelName of modelsToCleanup) {+ if (mongoose.models[modelName]) {+ delete mongoose.models[modelName];+ }+ }+});++afterEach(async () => {+ await File.deleteMany({});+ await mongoose.models.ChatProject.deleteMany({});+});++const file = (+ file_id: string,+ user: string,+ overrides: Partial<IMongoFile> = {},+): Partial<IMongoFile> => ({+ file_id,+ user: new mongoose.Types.ObjectId(user),+ filename: `${file_id}.txt`,+ filepath: `/tmp/${file_id}`,+ bytes: 12,+ object: 'file',+ type: 'text/plain',+ usage: 0,+ source: 'local',+ embedded: true,+ context: FileContext.message_attachment,+ text: 'must never be loaded',+ ...overrides,+});++const getProjectFiles = async ({+ fileIds,+ userId,+ tenantId,+ includeContent = false,+}: {+ fileIds: string[];+ userId: string;+ tenantId?: string | null;+ includeContent?: boolean;+}): Promise<ProjectFileRecord[]> => {+ const files = await File.find({+ file_id: { $in: fileIds },+ user: userId,+ embedded: true,+ context: FileContext.message_attachment,+ tenantId: tenantId != null && tenantId !== '' ? tenantId : null,+ })+ .select(includeContent ? {} : { text: 0 })+ .lean<IMongoFile[]>();+ return files.map((file) => ({+ _id: file._id.toString(),+ file_id: file.file_id,+ filename: file.filename,+ filepath: file.filepath,+ object: file.object,+ type: file.type,+ bytes: file.bytes,+ usage: file.usage,+ ...(file.embedded !== undefined ? { embedded: file.embedded } : {}),+ ...(file.context !== undefined ? { context: file.context } : {}),+ ...(file.expiredAt !== undefined ? { expiredAt: file.expiredAt } : {}),+ user: file.user.toString(),+ ...(file.tenantId !== undefined ? { tenantId: file.tenantId } : {}),+ ...(file.createdAt !== undefined ? { createdAt: file.createdAt } : {}),+ ...(file.updatedAt !== undefined ? { updatedAt: file.updatedAt } : {}),+ ...(file.previewRevision !== undefined ? { previewRevision: file.previewRevision } : {}),+ ...(file.status !== undefined ? { status: file.status } : {}),+ ...(file.text !== undefined ? { text: file.text } : {}),+ }));+};++describe('ChatProject resource hydration', () => {+ it('preserves Project compatibility when signed file URLs are refreshed', async () => {+ const owner = new mongoose.Types.ObjectId().toString();+ const methods = { ...createMethods(mongoose), getProjectFiles };+ const fileId = 'signed-reference';+ const originalUrl = 'https://bucket.s3.amazonaws.com/reference.txt?X-Amz-Signature=original';+ const refreshedUrl = 'https://bucket.s3.amazonaws.com/reference.txt?X-Amz-Signature=refreshed';+ await File.create(file(fileId, owner, { source: 's3', filepath: originalUrl }));+ await File.updateOne(+ { file_id: fileId },+ { $set: { updatedAt: new Date('2020-01-01') } },+ { timestamps: false },+ );+ const project = await methods.createChatProject(owner, { name: 'Signed reference' });+ const projectId = project._id!.toString();+ await methods.addChatProjectFile(owner, projectId, fileId);+ const input = { userId: owner, requestedProjectId: projectId };+ const before = await resolveChatProjectContext(input, methods);++ await methods.batchUpdateFiles([{ file_id: fileId, filepath: refreshedUrl }]);+ const after = await resolveChatProjectContext(input, methods);++ expect(after?.resources).toEqual([+ expect.objectContaining({+ availability: 'ready',+ file: expect.objectContaining({ filepath: refreshedUrl }),+ }),+ ]);+ expect(getChatProjectContextKey(after)).toBe(getChatProjectContextKey(before));+ });++ it('preserves Project compatibility when a referenced image is reused', async () => {+ const owner = new mongoose.Types.ObjectId().toString();+ const methods = { ...createMethods(mongoose), getProjectFiles };+ const fileId = 'reused-image';+ await File.create(+ file(fileId, owner, { type: 'image/png', filename: 'reference.png', source: 'local' }),+ );+ await File.updateOne(+ { file_id: fileId },+ { $set: { updatedAt: new Date('2020-01-01') } },+ { timestamps: false },+ );+ const project = await methods.createChatProject(owner, { name: 'Reused image' });+ const projectId = project._id!.toString();+ await methods.addChatProjectFile(owner, projectId, fileId);+ const input = { userId: owner, requestedProjectId: projectId };+ const before = await resolveChatProjectContext(input, methods);++ /* `prepareImageURL` promotes the upload with nothing but the id on every reuse. */+ await methods.updateFile({ file_id: fileId });+ const after = await resolveChatProjectContext(input, methods);++ expect(after?.resources).toEqual([expect.objectContaining({ availability: 'ready' })]);+ expect(getChatProjectContextKey(after)).toBe(getChatProjectContextKey(before));+ });++ it('only marks canonical unscoped message attachments ready', () => {+ expect(+ getChatProjectFileAvailability(+ file('ready', new mongoose.Types.ObjectId().toString()) as IMongoFile,+ ),+ ).toBe('ready');+ expect(+ getChatProjectFileAvailability(+ file('agent', new mongoose.Types.ObjectId().toString(), {+ context: FileContext.agents,+ }) as IMongoFile,+ ),+ ).toBe('unavailable');+ expect(+ getChatProjectFileAvailability(+ file('not-indexed', new mongoose.Types.ObjectId().toString(), {+ embedded: false,+ }) as IMongoFile,+ ),+ ).toBe('unavailable');+ expect(+ getChatProjectFileAvailability(+ file('expired', new mongoose.Types.ObjectId().toString(), {+ expiredAt: new Date(Date.now() - 1),+ }) as IMongoFile,+ ),+ ).toBe('unavailable');+ });++ it('hydrates ready runtime files and safe unavailable views from canonical Mongo records', async () => {+ const owner = new mongoose.Types.ObjectId().toString();+ const tenantId = 'tenant-a';+ await File.create(file('ready', owner, { tenantId }));+ await File.create(file('expired', owner, { tenantId, expiredAt: new Date(Date.now() - 1) }));+ await File.create(file('agent-scoped', owner, { tenantId, context: FileContext.agents }));+ await File.create(file('foreign', new mongoose.Types.ObjectId().toString(), { tenantId }));++ const project = {+ file_ids: ['ready', 'expired', 'agent-scoped', 'foreign', 'missing'],+ tenantId,+ } as Pick<IChatProject, 'file_ids' | 'tenantId'>;++ const runtimeFiles = await resolveChatProjectFiles({+ project,+ userId: owner,+ tenantId,+ getProjectFiles,+ });+ expect(runtimeFiles.map((runtimeFile) => runtimeFile.file_id)).toEqual(['ready']);+ expect(runtimeFiles[0]).not.toHaveProperty('text');++ const views = await listChatProjectFileViews({+ project,+ userId: owner,+ tenantId,+ getProjectFiles,+ });+ expect(views).toEqual([+ {+ file_id: 'ready',+ filename: 'ready.txt',+ type: 'text/plain',+ bytes: 12,+ availability: 'ready',+ },+ {+ file_id: 'expired',+ filename: 'expired.txt',+ type: 'text/plain',+ bytes: 12,+ availability: 'unavailable',+ },+ {+ file_id: 'agent-scoped',+ availability: 'unavailable',+ },+ { file_id: 'foreign', availability: 'unavailable' },+ { file_id: 'missing', availability: 'unavailable' },+ ]);+ });+});diff --git a/packages/api/src/projects/resources.ts b/packages/api/src/projects/resources.tsnew file mode 100644index 0000000000..a86ca00764--- /dev/null+++ b/packages/api/src/projects/resources.ts@@ -0,0 +1,226 @@+import { createHash } from 'crypto';+import { FileContext } from 'librechat-data-provider';+import type { TChatProject, TChatProjectFile, TFile } from 'librechat-data-provider';+import type { IChatProject, ProjectFileRecord } from '@librechat/data-schemas';+export type { ProjectFileRecord } from '@librechat/data-schemas';++export type CanonicalProjectResource = {+ file_id: string;+ identity: string;+ version: string;+} & ({ availability: 'ready'; file: TFile } | { availability: 'unavailable' });++/** Canonical lookup; metadata snapshots omit bodies, while active policy selects full records. */+export type GetProjectFiles = (options: {+ fileIds: string[];+ userId: string;+ tenantId?: string | null;+ includeContent?: boolean;+}) => Promise<ReadonlyArray<ProjectFileRecord> | null>;++/** Project resources are restricted to owner-scoped, unscoped message attachments. */+export function getChatProjectFileAvailability(+ file:+ | {+ embedded?: boolean;+ context?: string;+ expiredAt?: Date | number | string | null;+ }+ | null+ | undefined,+): 'ready' | 'unavailable' {+ if (!file || file.embedded !== true || file.context !== FileContext.message_attachment) {+ return 'unavailable';+ }++ if (file.expiredAt != null) {+ const expiry =+ file.expiredAt instanceof Date ? file.expiredAt.getTime() : Number(file.expiredAt);+ if (!Number.isFinite(expiry) || expiry <= Date.now()) {+ return 'unavailable';+ }+ }++ return 'ready';+}++async function loadProjectFiles({+ project,+ userId,+ tenantId,+ getProjectFiles,+ includeContent = false,+}: {+ project: Pick<IChatProject, 'file_ids'> | Pick<TChatProject, 'file_ids'>;+ userId: string;+ tenantId?: string;+ getProjectFiles: GetProjectFiles;+ includeContent?: boolean;+}): Promise<{ fileIds: string[]; byId: Map<string, ProjectFileRecord> }> {+ const fileIds = [+ ...new Set(+ (project.file_ids ?? []).filter((fileId): fileId is string => typeof fileId === 'string'),+ ),+ ];+ if (fileIds.length === 0) {+ return { fileIds, byId: new Map() };+ }+ const files = await getProjectFiles({+ fileIds,+ userId,+ tenantId,+ includeContent,+ });+ return { fileIds, byId: new Map((files ?? []).map((file) => [file.file_id, file])) };+}++function canonicalResourceVersion(+ file: ProjectFileRecord,+ identity: string,+ availability: 'ready' | 'unavailable',+): string {+ return createHash('sha256')+ .update(+ JSON.stringify({+ identity,+ file_id: file.file_id,+ availability,+ embedded: file.embedded ?? null,+ context: file.context ?? null,+ expiredAt: file.expiredAt?.toISOString() ?? null,+ createdAt: file.createdAt?.toISOString() ?? null,+ updatedAt: file.updatedAt?.toISOString() ?? null,+ previewRevision: file.previewRevision ?? null,+ status: file.status ?? null,+ bytes: file.bytes,+ filename: file.filename,+ type: file.type,+ }),+ )+ .digest('hex');+}++export function toCanonicalProjectResource(file: ProjectFileRecord): CanonicalProjectResource {+ if (file._id == null) {+ throw new Error('Project file identity unavailable');+ }+ const identity = file._id.toString();+ const availability = getChatProjectFileAvailability(file);+ const version = canonicalResourceVersion(file, identity, availability);+ if (availability === 'ready') {+ return { file_id: file.file_id, identity, availability, version, file: toRuntimeFile(file) };+ }+ return { file_id: file.file_id, identity, availability, version };+}++export async function resolveChatProjectResources(params: {+ project: Pick<IChatProject, 'file_ids'> | Pick<TChatProject, 'file_ids'>;+ userId: string;+ tenantId?: string;+ getProjectFiles: GetProjectFiles;+}): Promise<CanonicalProjectResource[]> {+ const { fileIds, byId } = await loadProjectFiles(params);+ return fileIds.map((fileId) => {+ const file = byId.get(fileId);+ return file == null+ ? { file_id: fileId, identity: 'missing', availability: 'unavailable', version: 'missing' }+ : toCanonicalProjectResource(file);+ });+}++export async function resolveChatProjectPolicyFiles(params: {+ project: Pick<IChatProject, 'file_ids'> | Pick<TChatProject, 'file_ids'>;+ userId: string;+ tenantId?: string;+ getProjectFiles: GetProjectFiles;+}): Promise<ProjectFileRecord[]> {+ const { fileIds, byId } = await loadProjectFiles({ ...params, includeContent: true });+ return fileIds+ .map((fileId) => byId.get(fileId))+ .filter((file): file is ProjectFileRecord => getChatProjectFileAvailability(file) === 'ready');+}++type RuntimeFileSource = {+ file_id: string;+ filename: string;+ filepath: string;+ object: 'file';+ type: string;+ bytes: number;+ usage: number;+ user: string | { toString(): string };+ tenantId?: string;+};++export function toRuntimeFile(file: RuntimeFileSource): TFile {+ return {+ file_id: file.file_id,+ filename: file.filename,+ filepath: file.filepath,+ object: file.object,+ type: file.type,+ bytes: file.bytes,+ usage: file.usage,+ embedded: true,+ context: FileContext.message_attachment,+ user: typeof file.user === 'string' ? file.user : file.user.toString(),+ ...(file.tenantId != null ? { tenantId: file.tenantId } : {}),+ };+}++/**+ * Resolve resources for Agent runtime. Only currently eligible canonical files are returned,+ * deduplicated and with extracted text omitted. Callers must still intersect these files with+ * the selected Agent's already-enabled file-search capability.+ */+export async function resolveChatProjectFiles(params: {+ project: Pick<IChatProject, 'file_ids'> | Pick<TChatProject, 'file_ids'>;+ userId: string;+ tenantId?: string;+ getProjectFiles: GetProjectFiles;+ resources?: readonly CanonicalProjectResource[];+}): Promise<TFile[]> {+ const resources =+ params.resources ??+ (await resolveChatProjectResources({+ project: params.project,+ userId: params.userId,+ tenantId: params.tenantId,+ getProjectFiles: params.getProjectFiles,+ }));+ const files: TFile[] = [];+ for (const resource of resources) {+ if (resource.availability === 'ready') {+ files.push(resource.file);+ }+ }+ return files;+}++/**+ * Build the HTTP-safe project file view. Unlike runtime resolution, this retains an unavailable+ * placeholder for every stored ID so deleted, expired, or otherwise ineligible references are+ * visible without disclosing another owner's metadata.+ */+export async function listChatProjectFileViews(params: {+ project: Pick<IChatProject, 'file_ids'> | Pick<TChatProject, 'file_ids'>;+ userId: string;+ tenantId?: string;+ getProjectFiles: GetProjectFiles;+}): Promise<TChatProjectFile[]> {+ const { fileIds, byId } = await loadProjectFiles(params);+ return fileIds.map((file_id) => {+ const file = byId.get(file_id);+ return {+ file_id,+ ...(file+ ? {+ ...(typeof file.filename === 'string' ? { filename: file.filename } : {}),+ ...(typeof file.type === 'string' ? { type: file.type } : {}),+ ...(typeof file.bytes === 'number' ? { bytes: file.bytes } : {}),+ }+ : {}),+ availability: getChatProjectFileAvailability(file),+ };+ });+}diff --git a/packages/api/src/projects/resume.spec.ts b/packages/api/src/projects/resume.spec.tsnew file mode 100644index 0000000000..cb724951b0--- /dev/null+++ b/packages/api/src/projects/resume.spec.ts@@ -0,0 +1,176 @@+import type { ResumeProjectContextRequest } from './resume';+import {+ resolveResumeProjectContext,+ hasResumeProjectContextChanged,+ PROJECT_CONTEXT_CHANGED_REASON,+ rejectChangedResumeProjectContext,+} from './resume';+import { getChatProjectContextKey } from './context';++const project = {+ _id: 'project-a',+ tenantId: 'tenant-a',+ instructions: 'Use the project policy.',+ contextRevision: 3,+ file_ids: [],+};+const conversation = {+ conversationId: 'conversation-a',+ chatProjectId: 'project-a',+ user: 'user-a',+ tenantId: 'tenant-a',+};+const currentKey = getChatProjectContextKey({+ projectId: 'project-a',+ contextRevision: 3,+ instructions: project.instructions,+ file_ids: [],+ resources: [],+});++const createReq = (overrides: Partial<ResumeProjectContextRequest> = {}) =>+ ({+ user: { id: 'user-a', tenantId: 'tenant-a' },+ ...overrides,+ }) as ResumeProjectContextRequest;++const createDeps = (storedProject: object | null = project) => ({+ getConvo: jest.fn().mockResolvedValue(conversation),+ getChatProject: jest.fn().mockResolvedValue(storedProject),+ getProjectFiles: jest.fn().mockResolvedValue([]),+ logger: { warn: jest.fn(), error: jest.fn() },+ finalizeJob: jest.fn().mockResolvedValue(true),+ deleteCheckpoint: jest.fn().mockResolvedValue(undefined),+});++describe('resolveResumeProjectContext', () => {+ it('refreshes the conversation and clears cached project hydration', async () => {+ const req = createReq({+ resolvedConversation: { conversationId: 'stale' },+ chatProjectFiles: [],+ chatProjectFilesPromise: Promise.resolve([]),+ });+ const deps = createDeps();+ const context = await resolveResumeProjectContext(req, 'conversation-a', false, deps);+ expect(context?.projectId).toBe('project-a');+ expect(deps.getConvo).toHaveBeenCalledWith('user-a', 'conversation-a');+ expect(req.resolvedConversation).toBe(conversation);+ expect(req.chatProjectFiles).toBeUndefined();+ expect(req.chatProjectFilesPromise).toBeUndefined();+ expect(req.chatProjectContext).toBe(context);+ });++ it('uses the event binding tenant for a bound child conversation', async () => {+ const req = createReq({+ user: { id: 'user-a', tenantId: 'tenant-user' },+ _agentEventBindingParentConversationId: 'parent',+ _agentEventBindingTenantId: 'tenant-a',+ });+ const context = await resolveResumeProjectContext(req, 'conversation-a', false, createDeps());+ expect(context?.projectId).toBe('project-a');+ });++ it('treats a stored membership whose project is unavailable as no project context', async () => {+ const deps = createDeps({ ...project, tenantId: 'tenant-b' });+ const req = createReq();+ await expect(+ resolveResumeProjectContext(req, 'conversation-a', false, deps),+ ).resolves.toBeNull();+ expect(req.chatProjectContext).toBeNull();+ });+});++describe('hasResumeProjectContextChanged', () => {+ it('accepts an unchanged key without hydrating resources', async () => {+ const deps = createDeps();+ await expect(+ hasResumeProjectContextChanged(+ { req: createReq(), conversationId: 'conversation-a', expectedKey: currentKey },+ deps,+ ),+ ).resolves.toBe(false);+ expect(deps.getProjectFiles).not.toHaveBeenCalled();+ });++ it('rejects a changed revision after rehydrating resources', async () => {+ const deps = createDeps({ ...project, contextRevision: 4 });+ await expect(+ hasResumeProjectContextChanged(+ { req: createReq(), conversationId: 'conversation-a', expectedKey: currentKey },+ deps,+ ),+ ).resolves.toBe(true);+ expect(deps.getConvo).toHaveBeenCalledTimes(2);+ });++ it('resumes a legacy pause with no recorded key under the current project context', async () => {+ const deps = createDeps();+ const req = createReq();+ await expect(+ hasResumeProjectContextChanged(+ { req, conversationId: 'conversation-a', expectedKey: undefined },+ deps,+ ),+ ).resolves.toBe(false);+ expect(req.chatProjectContext?.instructions).toBe(project.instructions);+ expect(deps.logger.warn).toHaveBeenCalledWith(+ expect.stringContaining('without a recorded project context key'),+ { conversationId: 'conversation-a', projectId: 'project-a' },+ );+ });++ it('does not warn for a legacy pause without model-facing project context', async () => {+ const deps = createDeps({ ...project, instructions: '' });+ await expect(+ hasResumeProjectContextChanged(+ { req: createReq(), conversationId: 'conversation-a', expectedKey: undefined },+ deps,+ ),+ ).resolves.toBe(false);+ expect(deps.logger.warn).not.toHaveBeenCalled();+ });+});++describe('rejectChangedResumeProjectContext', () => {+ const params = { conversationId: 'conversation-a', expectedKey: currentKey };++ it('does not finalize an unchanged resume', async () => {+ const deps = createDeps();+ await expect(+ rejectChangedResumeProjectContext({ ...params, req: createReq() }, deps),+ ).resolves.toBe(false);+ expect(deps.finalizeJob).not.toHaveBeenCalled();+ });++ it('finalizes and prunes a changed resume', async () => {+ const deps = createDeps(null);+ await expect(+ rejectChangedResumeProjectContext({ ...params, req: createReq() }, deps),+ ).resolves.toBe(true);+ expect(deps.finalizeJob).toHaveBeenCalledWith(PROJECT_CONTEXT_CHANGED_REASON);+ expect(deps.deleteCheckpoint).toHaveBeenCalledTimes(1);+ });++ it('skips pruning when the terminal CAS is lost and tolerates prune failures', async () => {+ const lost = createDeps(null);+ lost.finalizeJob.mockResolvedValue(false);+ await rejectChangedResumeProjectContext({ ...params, req: createReq() }, lost);+ expect(lost.deleteCheckpoint).not.toHaveBeenCalled();++ const pruneFails = createDeps(null);+ pruneFails.deleteCheckpoint.mockRejectedValue(new Error('checkpoint store down'));+ await expect(+ rejectChangedResumeProjectContext({ ...params, req: createReq() }, pruneFails),+ ).resolves.toBe(true);+ expect(pruneFails.logger.warn).toHaveBeenCalled();+ });++ it('propagates a terminalization failure', async () => {+ const deps = createDeps(null);+ deps.finalizeJob.mockRejectedValue(new Error('redis unavailable'));+ await expect(+ rejectChangedResumeProjectContext({ ...params, req: createReq() }, deps),+ ).rejects.toThrow('redis unavailable');+ expect(deps.logger.error).toHaveBeenCalled();+ });+});diff --git a/packages/api/src/projects/resume.ts b/packages/api/src/projects/resume.tsnew file mode 100644index 0000000000..873220da17--- /dev/null+++ b/packages/api/src/projects/resume.ts@@ -0,0 +1,151 @@+import type { TFile } from 'librechat-data-provider';+import type {+ ConversationSnapshot,+ ChatProjectTenantSource,+ ResolvedChatProjectContext,+ ResolveChatProjectContextDeps,+} from './context';+import type { ProjectLogger } from './turn';+import {+ getChatProjectTenantId,+ getChatProjectContextKey,+ resolveChatProjectContext,+ CHAT_PROJECT_CONTEXT_UNAVAILABLE,+} from './context';+import { getSafeErrorMetadata } from '../utils/errors';++export const PROJECT_CONTEXT_CHANGED_REASON: string =+ 'Project context changed before approval could be resumed';++export const PROJECT_CONTEXT_CHANGED_RESPONSE: Readonly<{ code: string; error: string }> = {+ code: 'PROJECT_CONTEXT_CHANGED',+ error: 'Project context changed; start a new turn.',+};++export interface ResumeProjectContextRequest extends ChatProjectTenantSource {+ chatProjectContext?: ResolvedChatProjectContext | null;+ resolvedConversation?: ConversationSnapshot | null;+ chatProjectContextResourcesPromise?: Promise<ResolvedChatProjectContext>;+ chatProjectFiles?: TFile[];+ chatProjectFilesPromise?: Promise<TFile[]>;+}++/**+ * Re-reads the authoritative conversation and project after the approval claim, replacing the+ * request's cached project state. An unavailable project resolves to no project context.+ */+export async function resolveResumeProjectContext(+ req: ResumeProjectContextRequest,+ conversationId: string,+ includeResources: boolean,+ deps: ResolveChatProjectContextDeps,+): Promise<ResolvedChatProjectContext | null> {+ let context: ResolvedChatProjectContext | null;+ let refreshedConversation: ConversationSnapshot | null | undefined;+ try {+ context = await resolveChatProjectContext(+ {+ userId: req.user.id,+ tenantId: getChatProjectTenantId(req),+ conversationId,+ includeResources,+ },+ {+ ...deps,+ getConvo: async (userId, id) => {+ refreshedConversation = await deps.getConvo(userId, id);+ return refreshedConversation;+ },+ },+ );+ req.chatProjectContextResourcesPromise = undefined;+ req.chatProjectFiles = undefined;+ req.chatProjectFilesPromise = undefined;+ req.resolvedConversation = refreshedConversation ?? null;+ } catch (error) {+ if (!(error instanceof Error) || error.message !== CHAT_PROJECT_CONTEXT_UNAVAILABLE) {+ throw error;+ }+ context = null;+ }+ req.chatProjectContext = context;+ return context;+}++/**+ * Compares the claimed pause's recorded project key against the current project context.+ * The originating turn resolves guidance first and hydrates resources only once File Search is+ * known, so a guidance-only mismatch rehydrates resources before the final comparison. A pause+ * recorded before keys existed resumes under the current project context.+ */+export async function hasResumeProjectContextChanged(+ {+ req,+ conversationId,+ expectedKey,+ }: {+ req: ResumeProjectContextRequest;+ conversationId: string;+ expectedKey: string | null | undefined;+ },+ deps: ResolveChatProjectContextDeps & { logger: ProjectLogger },+): Promise<boolean> {+ let context = await resolveResumeProjectContext(req, conversationId, false, deps);+ let currentKey = getChatProjectContextKey(context);+ if (typeof expectedKey !== 'string') {+ if (context != null && (context.instructions.trim() !== '' || context.file_ids.length > 0)) {+ deps.logger.warn(+ '[ResumeAgentController] Resuming a pause without a recorded project context key under the current project context',+ { conversationId, projectId: context.projectId },+ );+ }+ return false;+ }+ if (expectedKey === currentKey) {+ return false;+ }+ context = await resolveResumeProjectContext(req, conversationId, true, deps);+ currentKey = getChatProjectContextKey(context);+ return expectedKey !== currentKey;+}++/**+ * Stops a claimed resume whose project context changed. Only the terminal-CAS winner prunes+ * the generation's checkpoint; a failed terminalization propagates so the caller's failure+ * path owns the running -> error transition instead of answering a non-retryable 409.+ */+export async function rejectChangedResumeProjectContext(+ params: {+ req: ResumeProjectContextRequest;+ conversationId: string;+ expectedKey: string | null | undefined;+ },+ deps: ResolveChatProjectContextDeps & {+ logger: ProjectLogger;+ finalizeJob: (reason: string) => Promise<boolean>;+ deleteCheckpoint: () => Promise<void>;+ },+): Promise<boolean> {+ if (!(await hasResumeProjectContextChanged(params, deps))) {+ return false;+ }+ let finalized: boolean;+ try {+ finalized = await deps.finalizeJob(PROJECT_CONTEXT_CHANGED_REASON);+ } catch (error) {+ deps.logger.error(+ '[ResumeAgentController] Failed to finalize stale project-context resume',+ getSafeErrorMetadata(error),+ );+ throw error;+ }+ if (finalized) {+ await deps.deleteCheckpoint().catch((error: unknown) => {+ deps.logger.warn(+ '[ResumeAgentController] Failed to prune stale project-context checkpoint',+ getSafeErrorMetadata(error),+ );+ });+ }+ return true;+}diff --git a/packages/api/src/projects/turn.spec.ts b/packages/api/src/projects/turn.spec.tsnew file mode 100644index 0000000000..d3335ad85d--- /dev/null+++ b/packages/api/src/projects/turn.spec.ts@@ -0,0 +1,260 @@+import type { AppConfig } from '@librechat/data-schemas';+import {+ getChatProjectTurnFailure,+ resolveAssistantProjectTurn,+ assertChatProjectInstructions,+ resolveApiConversationProject,+ ChatProjectResourcesChangedError,+ resolveInitializationProjectContext,+} from './turn';+import { assertModelBoundContent } from '../middleware/modelBoundContent';+import { CHAT_PROJECT_CONTEXT_UNAVAILABLE } from './context';++const pattern = { id: 'secret', label: 'secret code', regex: 'SECRET-[0-9]+' };+const filters = {+ agentInstructions: {+ pii: { fields: ['instructions'], starterPatterns: [], customPatterns: [pattern] },+ },+} as AppConfig['filters'];+const legacyPii = { customPatterns: [pattern] };+const project = {+ _id: 'project-a',+ instructions: 'Use the project policy.',+ contextRevision: 2,+ file_ids: [],+};+const getProjectFiles = jest.fn().mockResolvedValue([]);+const logger = { warn: jest.fn(), error: jest.fn() };++describe('getChatProjectTurnFailure', () => {+ it('maps changed project resources to a retryable conflict', () => {+ expect(getChatProjectTurnFailure(new ChatProjectResourcesChangedError())).toEqual({+ status: 409,+ code: 'PROJECT_RESOURCES_CHANGED',+ error: expect.stringContaining('retry'),+ retryable: true,+ });+ });++ it('maps an unavailable project to not found and ignores unrelated errors', () => {+ expect(getChatProjectTurnFailure(new Error(CHAT_PROJECT_CONTEXT_UNAVAILABLE))).toEqual({+ status: 404,+ error: 'Conversation context unavailable',+ });+ expect(getChatProjectTurnFailure(new Error('boom'))).toBeNull();+ });++ it('maps a project guidance policy rejection to its response body', () => {+ let rejection: unknown;+ try {+ assertChatProjectInstructions({+ context: { ...project, projectId: 'project-a', instructions: 'SECRET-42', resources: [] },+ filters,+ });+ } catch (error) {+ rejection = error;+ }+ expect(getChatProjectTurnFailure(rejection)).toEqual(+ expect.objectContaining({ status: 400, error: 'content_filter_block' }),+ );+ });+});++describe('assertChatProjectInstructions', () => {+ const context = (instructions: string) => ({+ projectId: 'project-a',+ contextRevision: 1,+ instructions,+ file_ids: [],+ resources: [],+ });++ it('applies the agent instruction filters to project guidance', () => {+ expect(() =>+ assertChatProjectInstructions({ context: context('Reference SECRET-42'), filters }),+ ).toThrow();+ expect(() =>+ assertChatProjectInstructions({ context: context('Nothing sensitive'), filters }),+ ).not.toThrow();+ });++ it('keeps legacy message PII scoped away from instructions', () => {+ expect(() =>+ assertModelBoundContent({+ legacyPii,+ agents: [{ instructions: 'Reference SECRET-42' }],+ }),+ ).not.toThrow();+ });++ it('skips absent or blank guidance', () => {+ expect(() => assertChatProjectInstructions({ context: null, filters })).not.toThrow();+ expect(() => assertChatProjectInstructions({ context: context(' '), filters })).not.toThrow();+ });+});++describe('resolveApiConversationProject', () => {+ const deps = (conversation: object | null, storedProject: object | null = project) => ({+ getConvo: jest.fn().mockResolvedValue(conversation),+ getChatProject: jest.fn().mockResolvedValue(storedProject),+ getProjectFiles,+ logger,+ logPrefix: '[Test]',+ });++ it('returns the stored conversation and its project guidance', async () => {+ const conversation = { conversationId: 'conversation-a', chatProjectId: 'project-a' };+ const result = await resolveApiConversationProject(+ { userId: 'user-a', conversationId: 'conversation-a' },+ deps(conversation),+ );+ expect(result).toEqual({+ ok: true,+ conversation,+ context: expect.objectContaining({ projectId: 'project-a', resources: [] }),+ });+ });++ it('degrades a stored membership whose project is gone', async () => {+ const result = await resolveApiConversationProject(+ { userId: 'user-a', conversationId: 'conversation-a' },+ deps({ conversationId: 'conversation-a', chatProjectId: 'project-a' }, null),+ );+ expect(result).toEqual(expect.objectContaining({ ok: true, context: null }));+ });++ it('rejects missing and read-only conversations', async () => {+ await expect(+ resolveApiConversationProject(+ { userId: 'user-a', conversationId: 'conversation-a' },+ deps(null),+ ),+ ).resolves.toEqual(expect.objectContaining({ ok: false, status: 404, reason: 'not_found' }));+ await expect(+ resolveApiConversationProject(+ { userId: 'user-a', conversationId: 'conversation-a', rejectSubagentThread: true },+ deps({ conversationId: 'conversation-a', subagentThread: { parentConversationId: 'p' } }),+ ),+ ).resolves.toEqual(expect.objectContaining({ ok: false, status: 409, reason: 'read_only' }));+ });++ it('maps a foreign-tenant conversation to not found and read failures to server errors', async () => {+ await expect(+ resolveApiConversationProject(+ { userId: 'user-a', tenantId: 'tenant-a', conversationId: 'conversation-a' },+ deps({ conversationId: 'conversation-a', tenantId: 'tenant-b' }),+ ),+ ).resolves.toEqual(expect.objectContaining({ ok: false, status: 404, reason: 'unavailable' }));++ const failing = deps(null);+ failing.getConvo.mockRejectedValueOnce(new Error('database down'));+ await expect(+ resolveApiConversationProject({ userId: 'user-a', conversationId: 'c' }, failing),+ ).resolves.toEqual(expect.objectContaining({ ok: false, status: 500, reason: 'server_error' }));+ expect(logger.error).toHaveBeenCalledWith(+ '[Test] Conversation context resolution failed',+ expect.objectContaining({ type: 'Error' }),+ );+ });+});++describe('resolveAssistantProjectTurn', () => {+ it('seeds membership for a new conversation and formats guidance', async () => {+ const turn = await resolveAssistantProjectTurn(+ { userId: 'user-a', requestedProjectId: 'project-a' },+ {+ getConvo: jest.fn(),+ getChatProject: jest.fn().mockResolvedValue(project),+ getProjectFiles,+ },+ );+ expect(turn.rejection).toBeUndefined();+ if (turn.rejection) {+ return;+ }+ expect(turn.conversation).toBeNull();+ expect(turn.membershipProjectId).toBe('project-a');+ expect(turn.instructions).toContain(project.instructions);+ });++ it('keeps stored membership for an existing conversation', async () => {+ const getConvo = jest.fn().mockResolvedValue({ conversationId: 'c', chatProjectId: null });+ const turn = await resolveAssistantProjectTurn(+ { userId: 'user-a', conversationId: 'c', requestedProjectId: 'project-a' },+ { getConvo, getChatProject: jest.fn(), getProjectFiles },+ );+ expect(getConvo).toHaveBeenCalledWith('user-a', 'c');+ expect(turn).toEqual(+ expect.objectContaining({ context: null, instructions: '', membershipProjectId: null }),+ );+ });++ it('returns a not-found rejection for an unavailable requested project', async () => {+ const turn = await resolveAssistantProjectTurn(+ { userId: 'user-a', requestedProjectId: 'project-a' },+ { getConvo: jest.fn(), getChatProject: jest.fn().mockResolvedValue(null), getProjectFiles },+ );+ expect(turn.rejection).toEqual({+ status: 404,+ body: { error: 'Conversation context unavailable' },+ });+ });++ it('returns the policy rejection when guidance matches the instruction filters', async () => {+ const turn = await resolveAssistantProjectTurn(+ { userId: 'user-a', requestedProjectId: 'project-a', filters },+ {+ getConvo: jest.fn(),+ getChatProject: jest.fn().mockResolvedValue({ ...project, instructions: 'SECRET-7' }),+ getProjectFiles,+ },+ );+ expect(turn.rejection).toEqual({+ status: 400,+ body: expect.objectContaining({ error: 'content_filter_block' }),+ });+ });++ it('propagates unexpected read failures', async () => {+ await expect(+ resolveAssistantProjectTurn(+ { userId: 'user-a', requestedProjectId: 'project-a' },+ {+ getConvo: jest.fn(),+ getChatProject: jest.fn().mockRejectedValue(new Error('database down')),+ getProjectFiles,+ },+ ),+ ).rejects.toThrow('database down');+ });+});++describe('resolveInitializationProjectContext', () => {+ it('reuses an already-resolved context without reading', async () => {+ const getChatProject = jest.fn();+ const req = { user: { id: 'user-a' }, chatProjectContext: null };+ await expect(+ resolveInitializationProjectContext(+ { req, endpointOption: {}, conversationPromise: Promise.resolve(null) },+ { getConvo: jest.fn(), getChatProject, getProjectFiles },+ ),+ ).resolves.toBeNull();+ expect(getChatProject).not.toHaveBeenCalled();+ });++ it('resolves a bound child conversation in the event binding tenant', async () => {+ const getChatProject = jest.fn().mockResolvedValue({ ...project, tenantId: 'tenant-binding' });+ const req = {+ user: { id: 'user-a', tenantId: 'tenant-user' },+ body: { chatProjectId: 'project-a' },+ _agentEventBindingParentConversationId: 'parent',+ _agentEventBindingTenantId: 'tenant-binding',+ };+ const context = await resolveInitializationProjectContext(+ { req, endpointOption: {}, conversationPromise: Promise.resolve(null) },+ { getConvo: jest.fn(), getChatProject, getProjectFiles },+ );+ expect(context?.projectId).toBe('project-a');+ expect(getChatProject).toHaveBeenCalledWith('user-a', 'project-a');+ });+});diff --git a/packages/api/src/projects/turn.ts b/packages/api/src/projects/turn.tsnew file mode 100644index 0000000000..1aa32d718b--- /dev/null+++ b/packages/api/src/projects/turn.ts@@ -0,0 +1,270 @@+import type { TEndpointOption } from 'librechat-data-provider';+import type { AppConfig } from '@librechat/data-schemas';+import type {+ AgentProjectContextRequest,+ ConversationSnapshot,+ ResolvedChatProjectContext,+ ResolveChatProjectContextDeps,+} from './context';+import type { ContentPolicyError } from '../middleware/contentFilter';+import {+ getChatProjectTenantId,+ resolveChatProjectContext,+ formatChatProjectInstructions,+ CHAT_PROJECT_CONTEXT_UNAVAILABLE,+} from './context';+import { getContentFilterError, isContentFilterError } from '../middleware/contentFilter';+import { assertModelBoundContent } from '../middleware/modelBoundContent';+import { getSafeErrorMetadata } from '../utils/errors';++export const PROJECT_RESOURCES_CHANGED = 'PROJECT_RESOURCES_CHANGED';+export const CHAT_PROJECT_CONTEXT_UNAVAILABLE_RESPONSE: string = 'Conversation context unavailable';++/** Admitted project files moved between admission and runtime hydration; a new turn can retry. */+export class ChatProjectResourcesChangedError extends Error {+ public readonly code: typeof PROJECT_RESOURCES_CHANGED = PROJECT_RESOURCES_CHANGED;+ public readonly status = 409 as const;+ public readonly retryable = true as const;++ constructor() {+ super('Project resources changed during initialization');+ this.name = 'ChatProjectResourcesChangedError';+ Object.setPrototypeOf(this, ChatProjectResourcesChangedError.prototype);+ }+}++export interface ProjectLogger {+ warn: (message: string, meta?: object) => void;+ error: (message: string, meta?: object) => void;+}++export type ChatProjectTurnFailure =+ | { status: 404; error: string }+ | { status: 409; code: string; error: string; retryable: true }+ | ({ status: number } & ContentPolicyError['body']);++/** Maps project-owned turn startup failures to the HTTP status and body sent before the ACK. */+export function getChatProjectTurnFailure(error: unknown): ChatProjectTurnFailure | null {+ if (error instanceof ChatProjectResourcesChangedError) {+ return {+ status: 409,+ code: PROJECT_RESOURCES_CHANGED,+ error: 'Project files changed while this turn was starting. Please retry.',+ retryable: true,+ };+ }+ if (error instanceof Error && error.message === CHAT_PROJECT_CONTEXT_UNAVAILABLE) {+ return { status: 404, error: CHAT_PROJECT_CONTEXT_UNAVAILABLE_RESPONSE };+ }+ if (!isContentFilterError(error)) {+ return null;+ }+ const policyError = getContentFilterError(error) ?? error;+ return { status: policyError.statusCode, ...policyError.body };+}++/**+ * Inspects project guidance as agent instructions. Legacy `messageFilter.pii` is scoped to+ * message, assembled-context and tool-argument sources, so it never applies to instructions.+ */+export function assertChatProjectInstructions({+ context,+ filters,+}: {+ context: ResolvedChatProjectContext | null | undefined;+ filters?: AppConfig['filters'];+}): void {+ if (!context?.instructions.trim()) {+ return;+ }+ assertModelBoundContent({ filters, agents: [{ instructions: context.instructions }] });+}++export function joinChatProjectInstructions(+ base: string | null | undefined,+ instructions: string,+): string {+ return [base, instructions].filter(Boolean).join('\n\n');+}++export type ApiConversationProjectResult =+ | {+ ok: true;+ conversation: ConversationSnapshot;+ context: ResolvedChatProjectContext | null;+ }+ | {+ ok: false;+ status: 404 | 409 | 500;+ reason: 'not_found' | 'read_only' | 'unavailable' | 'server_error';+ message: string;+ };++/**+ * Loads the continued conversation for the OpenAI-compatible and Responses APIs and resolves+ * its authoritative project guidance, mapping every failure to the response the caller sends.+ */+export async function resolveApiConversationProject(+ {+ userId,+ tenantId,+ conversationId,+ rejectSubagentThread = false,+ }: {+ userId: string;+ tenantId?: string | null;+ conversationId: string;+ rejectSubagentThread?: boolean;+ },+ deps: ResolveChatProjectContextDeps & { logger: ProjectLogger; logPrefix: string },+): Promise<ApiConversationProjectResult> {+ try {+ const conversation = await deps.getConvo(userId, conversationId);+ if (!conversation) {+ return { ok: false, status: 404, reason: 'not_found', message: 'Conversation not found' };+ }+ if (rejectSubagentThread && conversation.subagentThread != null) {+ return { ok: false, status: 409, reason: 'read_only', message: 'Conversation is read-only' };+ }+ const context = await resolveChatProjectContext(+ {+ userId,+ tenantId,+ conversationId,+ resolvedConversation: conversation,+ includeResources: false,+ },+ deps,+ );+ return { ok: true, conversation, context };+ } catch (error) {+ deps.logger.error(+ `${deps.logPrefix} Conversation context resolution failed`,+ getSafeErrorMetadata(error),+ );+ const unavailable =+ error instanceof Error && error.message === CHAT_PROJECT_CONTEXT_UNAVAILABLE;+ return unavailable+ ? {+ ok: false,+ status: 404,+ reason: 'unavailable',+ message: CHAT_PROJECT_CONTEXT_UNAVAILABLE_RESPONSE,+ }+ : {+ ok: false,+ status: 500,+ reason: 'server_error',+ message: CHAT_PROJECT_CONTEXT_UNAVAILABLE_RESPONSE,+ };+ }+}++export type AssistantProjectTurn =+ | { rejection: { status: number; body: object } }+ | {+ rejection?: undefined;+ conversation: ConversationSnapshot | null;+ context: ResolvedChatProjectContext | null;+ instructions: string;+ /** Membership written with the final conversation: seeded only on a new conversation. */+ membershipProjectId: string | null | undefined;+ };++/**+ * Resolves project guidance for a hosted Assistants turn and inspects it before any provider+ * side effect. Content-policy and unavailable-project outcomes return the response to send.+ */+export async function resolveAssistantProjectTurn(+ {+ userId,+ tenantId,+ conversationId,+ requestedProjectId,+ resolvedConversation,+ filters,+ }: {+ userId: string;+ tenantId?: string | null;+ conversationId?: string | null;+ requestedProjectId?: string | null;+ resolvedConversation?: ConversationSnapshot | null;+ filters?: AppConfig['filters'];+ },+ deps: ResolveChatProjectContextDeps,+): Promise<AssistantProjectTurn> {+ let conversation = resolvedConversation;+ if (conversation === undefined) {+ conversation = conversationId ? await deps.getConvo(userId, conversationId) : null;+ }+ const existingConversation = conversation ?? null;+ let context: ResolvedChatProjectContext | null;+ try {+ context = await resolveChatProjectContext(+ {+ userId,+ tenantId,+ conversationId,+ requestedProjectId,+ resolvedConversation: existingConversation,+ includeResources: false,+ },+ deps,+ );+ assertChatProjectInstructions({ context, filters });+ } catch (error) {+ const failure = getChatProjectTurnFailure(error);+ if (failure == null || failure.status === 409) {+ throw error;+ }+ const { status, ...body } = failure;+ return { rejection: { status, body } };+ }+ return {+ conversation: existingConversation,+ context,+ instructions: formatChatProjectInstructions(context),+ membershipProjectId:+ existingConversation === null ? context?.projectId : existingConversation.chatProjectId,+ };+}++/**+ * Resolves guidance for an agent initialization that did not arrive with a resolved project+ * context, reusing an already-resolved context (including an explicit `undefined`) as-is.+ */+export function resolveInitializationProjectContext(+ {+ req,+ endpointOption,+ conversationId,+ conversationPromise,+ }: {+ req: AgentProjectContextRequest;+ endpointOption: Partial<TEndpointOption>;+ conversationId?: string | null;+ conversationPromise: Promise<ConversationSnapshot | null | undefined>;+ },+ deps: ResolveChatProjectContextDeps,+): Promise<ResolvedChatProjectContext | null | undefined> {+ if (Object.prototype.hasOwnProperty.call(req, 'chatProjectContext')) {+ return Promise.resolve(req.chatProjectContext);+ }+ const requestedProjectId =+ endpointOption.chatProjectId !== undefined+ ? endpointOption.chatProjectId+ : req.body?.chatProjectId;+ return conversationPromise.then((resolvedConversation) =>+ resolveChatProjectContext(+ {+ userId: req.user.id,+ tenantId: getChatProjectTenantId(req),+ conversationId,+ requestedProjectId,+ resolvedConversation,+ includeResources: false,+ },+ deps,+ ),+ );+}diff --git a/packages/api/src/stream/GenerationJobManager.ts b/packages/api/src/stream/GenerationJobManager.tsindex 749db957be..4588a440ce 100644--- a/packages/api/src/stream/GenerationJobManager.ts+++ b/packages/api/src/stream/GenerationJobManager.ts@@ -8841,7 +8841,7 @@ class GenerationJobManagerClass {contextUsage,// Carry the live pending approval in the resume contract so a reloading /// cross-replica client can rebuild the prompt from resumeState. Client-safe- // projection: the stored record's resumeContext/requestFingerprint stay server-only.+ // projection: projectContextKey, resumeContext, and requestFingerprint stay server-only.pendingAction:verifiedJob.status === 'requires_action' && !isPendingActionStale(verifiedJob)? toClientPendingAction(verifiedJob.pendingAction)diff --git a/packages/api/src/types/http.ts b/packages/api/src/types/http.tsindex 80fec4a6da..8f9d1682ee 100644--- a/packages/api/src/types/http.ts+++ b/packages/api/src/types/http.ts@@ -2,12 +2,14 @@ import type {CodeApprovalMode,CodeEnvironmentMode,CodeWorkspaceSelection,+ TFile,TEndpointOption,TReasoningOverride,Agents,} from 'librechat-data-provider';import type { IUser, AppConfig, IConversation } from '@librechat/data-schemas';import type { Request } from 'express';+import type { ResolvedChatProjectContext } from '../projects/context';/*** LibreChat-specific request body type that extends Express Request body@@ -23,6 +25,7 @@ export type RequestBody = {model?: string;imageDetail?: Agents.ImageDetail;key?: string;+ chatProjectId?: string | null;endpointOption?: Partial<TEndpointOption>;reasoningOverride?: TReasoningOverride;/** Browser IANA timezone used to resolve local-time prompt variables (e.g. `{{current_datetime}}`). */@@ -37,12 +40,21 @@ export type ServerRequest = Request<unknown, unknown, RequestBody> & {config?: AppConfig;/** Server-captured generation start time used to anchor dynamic prompt variables. */turnStartedAt?: number;- /** Server-captured conversation creation time used when inserting conversation metadata. */+ /** Server-captured original conversation creation timestamp. */conversationCreatedAt?: string;/** Conversation read by request middleware (`null` = looked up, absent), reused by the* subagent guard, agent initialization, and the first save instead of re-reading it. */resolvedConversation?: Partial<IConversation> | null;- /** Passport strategy that populated req.user for this request. */+ /** Authoritative server-only project context for the current turn. */+ chatProjectContext?: ResolvedChatProjectContext | null;+ /** Metadata-only project files hydrated once per request. */+ chatProjectFiles?: TFile[];+ /** Request-scoped in-flight project-context resource hydration. */+ chatProjectContextResourcesPromise?: Promise<ResolvedChatProjectContext>;+ /** Request-scoped in-flight hydration shared by connected graph agents. */+ chatProjectFilesPromise?: Promise<TFile[]>;+ /** Internal opt-in marker for conversation graph agent initialization. */+ chatProjectContextEnabled?: boolean;authStrategy?: string;/** Trusted snapshot used to keep a request-scoped override out of saved conversation defaults. */reasoningOverrideBase?: {diff --git a/packages/client/src/components/Button.tsx b/packages/client/src/components/Button.tsxindex da639b2201..32ab865eb9 100644--- a/packages/client/src/components/Button.tsx+++ b/packages/client/src/components/Button.tsx@@ -21,6 +21,8 @@ type ButtonVariantOptions =| 'section-header'| 'section-action'| 'header-action'+ | 'inline-edit'+ | 'card'| null| undefined;size?:@@ -33,6 +35,8 @@ type ButtonVariantOptions =| 'sm'| 'lg'| 'theme'+ | 'row'+ | 'tile'| null| undefined;shape?: 'default' | 'theme' | 'round' | null | undefined;@@ -111,6 +115,21 @@ const buttonVariantRecipe = cva(*/'header-action':'rounded-xl border border-border-light bg-presentation text-text-primary duration-0 hover:bg-surface-active-alt hover:text-text-primary',+ /**+ * Text that turns into its own editor when activated, such as a workspace+ * title or description. It reads as the text it stands for, so the caller+ * sets the typography on the text it renders and this adds only the hover+ * fill and the focus ring that mark it as a control.+ */+ 'inline-edit':+ 'justify-start whitespace-normal text-left hover:bg-surface-hover focus-visible:ring-inset focus-visible:ring-offset-0',+ /**+ * A whole card or list row that is one click target, such as a project+ * tile or a chat row. It carries no fill of its own because the card+ * around it owns the surface; it adds the hover fill and an inset ring,+ * and left-aligns its content, which the caller lays out.+ */+ card: 'justify-start whitespace-normal rounded-2xl text-left font-normal hover:bg-surface-hover focus-visible:ring-inset focus-visible:ring-offset-0',},size: {default: 'h-10 px-4 py-2',@@ -132,6 +151,10 @@ const buttonVariantRecipe = cva(*/'icon-theme': 'size-theme-control p-0',theme: 'h-theme-control gap-theme-compact px-theme-normal',+ /** The padding of a list row that is itself the click target. */+ row: 'h-auto gap-3 px-3.5 py-3',+ /** The padding of a tile that reserves a corner for an overflow menu. */+ tile: 'h-auto gap-0 p-4 pr-12',},shape: {default: 'rounded-lg',@@ -155,6 +178,13 @@ const buttonVariantRecipe = cva(size: 'default',class: 'h-auto px-1 py-2',},+ /* Sized by the text it stands for, like `section-header`, so the default+ * size recipe must not pad it away from the content it lines up with. */+ {+ variant: 'inline-edit',+ size: 'default',+ class: 'h-auto px-0 py-1',+ },/* `size: 'sm'` brings its own `rounded-lg`, emitted after the variant* and so winning the merge. A text-bearing header control keeps the* row's `rounded-xl` corner, matching the icon-sized ones beside it.diff --git a/packages/client/src/components/EmptyState.tsx b/packages/client/src/components/EmptyState.tsxindex 0a381ca907..bf90dd4bdd 100644--- a/packages/client/src/components/EmptyState.tsx+++ b/packages/client/src/components/EmptyState.tsx@@ -37,7 +37,7 @@ export default function EmptyState({className,)}>- <Icon className="text-text-tertiary mb-3 size-5" aria-hidden={true} />+ <Icon className="text-text-tertiary mb-3 size-5 shrink-0" aria-hidden={true} />{title != null && <p className="text-text-primary text-sm font-medium">{title}</p>}{description != null && (// Without a title the description IS the message, so it carries the title'sdiff --git a/packages/client/src/components/Input.tsx b/packages/client/src/components/Input.tsxindex 9ce9211114..d7d9abfa7c 100644--- a/packages/client/src/components/Input.tsx+++ b/packages/client/src/components/Input.tsx@@ -3,18 +3,27 @@ import { fieldControl } from './Field';import { cn } from '~/utils';import './Field.css';+/** `title` edits a heading in place, so the field takes the heading's type scale. */+const INPUT_VARIANTS = {+ default: '',+ title: 'h-12 text-2xl font-semibold tracking-tight',+ 'title-sm': 'text-base font-semibold tracking-tight',+} as const;+export type InputProps = React.InputHTMLAttributes<HTMLInputElement> & {colorTransition?: boolean;+ variant?: keyof typeof INPUT_VARIANTS;};const Input: React.ForwardRefExoticComponent<InputProps & React.RefAttributes<HTMLInputElement>> =React.forwardRef<HTMLInputElement, InputProps>(- ({ className, colorTransition, ...props }, ref) => {+ ({ className, colorTransition, variant = 'default', ...props }, ref) => {return (<inputclassName={cn(fieldControl,'ring-offset-surface-primary',+ INPUT_VARIANTS[variant],colorTransition && 'transition-colors',className ?? '',)}diff --git a/packages/client/src/components/OGDialogTemplate.tsx b/packages/client/src/components/OGDialogTemplate.tsxindex b42570278a..eff1fa197e 100644--- a/packages/client/src/components/OGDialogTemplate.tsx+++ b/packages/client/src/components/OGDialogTemplate.tsx@@ -6,6 +6,7 @@ import {Ref,RefAttributes,} from 'react';+import type { ComponentProps } from 'react';import {OGDialogTitle,OGDialogClose,@@ -66,7 +67,12 @@ type DialogTemplateProps = {footerClassName?: string;showCloseButton?: boolean;showCancelButton?: boolean;+ cancelDisabled?: boolean;onClose?: () => void;+ onOpenAutoFocus?: ComponentProps<typeof OGDialogContent>['onOpenAutoFocus'];+ onCloseAutoFocus?: ComponentProps<typeof OGDialogContent>['onCloseAutoFocus'];+ onEscapeKeyDown?: ComponentProps<typeof OGDialogContent>['onEscapeKeyDown'];+ onInteractOutside?: ComponentProps<typeof OGDialogContent>['onInteractOutside'];};const OGDialogTemplate: ForwardRefExoticComponent<@@ -87,6 +93,11 @@ const OGDialogTemplate: ForwardRefExoticComponent<showCloseButton = false,overlayClassName,showCancelButton = true,+ cancelDisabled = false,+ onOpenAutoFocus,+ onCloseAutoFocus,+ onEscapeKeyDown,+ onInteractOutside,} = props;const isLegacySelection = isSelectionProps(selection);const legacySelection = isLegacySelection ? selection : null;@@ -106,7 +117,7 @@ const OGDialogTemplate: ForwardRefExoticComponent<} flex h-10 items-center justify-center rounded-lg border-none px-4 py-2 text-sm disabled:opacity-80 max-sm:order-first max-sm:w-full sm:order-none`}>{isLoading === true ? (- <Spinner className="size-4 text-text-primary" />+ <Spinner className="text-text-primary size-4" />) : ((selectText as React.JSX.Element))}@@ -120,11 +131,15 @@ const OGDialogTemplate: ForwardRefExoticComponent<<OGDialogContentoverlayClassName={overlayClassName}showCloseButton={showCloseButton}+ onOpenAutoFocus={onOpenAutoFocus}+ onCloseAutoFocus={onCloseAutoFocus}+ onEscapeKeyDown={onEscapeKeyDown}+ onInteractOutside={onInteractOutside}ref={ref}className={cn(/** `border-none` clears the default edge; the contrast variant has to* restore the style as well as the width to survive it. */- 'w-11/12 border-none bg-surface-dialog text-text-primary high-contrast:border high-contrast:border-solid high-contrast:border-border-medium high-contrast:shadow-none',+ 'bg-surface-dialog text-text-primary high-contrast:border high-contrast:border-solid high-contrast:border-border-medium high-contrast:shadow-none w-11/12 border-none',className ?? '',)}onClick={(e) => e.stopPropagation()}@@ -144,7 +159,11 @@ const OGDialogTemplate: ForwardRefExoticComponent<) : null}{showCancelButton && (<OGDialogClose asChild>- <Button variant="outline" aria-label={localize('com_ui_cancel')}>+ <Button+ variant="outline"+ aria-label={localize('com_ui_cancel')}+ disabled={cancelDisabled}+ >{localize('com_ui_cancel')}</Button></OGDialogClose>diff --git a/packages/client/src/components/Resizable.tsx b/packages/client/src/components/Resizable.tsxindex deef6c61ad..5c8ece7137 100644--- a/packages/client/src/components/Resizable.tsx+++ b/packages/client/src/components/Resizable.tsx@@ -13,6 +13,16 @@ const ResizablePanelGroup = ({const ResizablePanel: typeof Panel = Panel;+/** A separator reports the axis it divides, which is the opposite of its group's+ * orientation: a vertical group stacks panels, so its handle is a horizontal bar. */+const handleBase =+ 'group relative flex w-px items-center justify-center bg-border-medium after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-focus-control focus-visible:ring-offset-1 aria-[orientation=horizontal]:h-px aria-[orientation=horizontal]:w-full aria-[orientation=horizontal]:after:inset-x-0 aria-[orientation=horizontal]:after:inset-y-auto aria-[orientation=horizontal]:after:left-0 aria-[orientation=horizontal]:after:top-1/2 aria-[orientation=horizontal]:after:h-1 aria-[orientation=horizontal]:after:w-full aria-[orientation=horizontal]:after:translate-x-0 aria-[orientation=horizontal]:after:-translate-y-1/2';++const handleGrip =+ 'z-10 flex h-4 w-3 items-center justify-center rounded-sm border border-border-light bg-border-medium group-aria-[orientation=horizontal]:h-3 group-aria-[orientation=horizontal]:w-4';++const gripIcon = 'h-2.5 w-2.5 group-aria-[orientation=horizontal]:rotate-90';+const ResizableHandle = ({withHandle,className = '',@@ -20,16 +30,10 @@ const ResizableHandle = ({}: ComponentProps<typeof Separator> & {withHandle?: boolean;}): JSX.Element => (- <Separator- className={cn(- 'bg-border-medium focus-visible:ring-focus-control relative flex w-px items-center justify-center after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:outline-hidden',- className,- )}- {...props}- >+ <Separator className={cn(handleBase, className)} {...props}>{withHandle && (- <div className="bg-border-medium border-border-light z-10 flex h-4 w-3 items-center justify-center rounded-sm border">- <GripVertical className="h-2.5 w-2.5" />+ <div className={handleGrip}>+ <GripVertical className={gripIcon} /></div>)}</Separator>@@ -42,16 +46,15 @@ const ResizableHandleAlt = ({}: ComponentProps<typeof Separator> & {withHandle?: boolean;}): JSX.Element => (- <Separator- className={cn(- 'group bg-border-medium focus-visible:ring-focus-control relative flex w-px items-center justify-center after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:outline-hidden',- className,- )}- {...props}- >+ <Separator className={cn(handleBase, className)} {...props}>{withHandle && (- <div className="bg-border-medium border-border-light invisible z-10 flex h-4 w-3 items-center justify-center rounded-sm border group-hover:visible group-active:visible group-data-[separator=active]:visible">- <GripVertical className="h-2.5 w-2.5" />+ <div+ className={cn(+ handleGrip,+ 'invisible group-hover:visible group-active:visible group-data-[separator=active]:visible',+ )}+ >+ <GripVertical className={gripIcon} /></div>)}</Separator>diff --git a/packages/client/src/components/Textarea.tsx b/packages/client/src/components/Textarea.tsxindex ba22312e0a..b79bae91ac 100644--- a/packages/client/src/components/Textarea.tsx+++ b/packages/client/src/components/Textarea.tsx@@ -3,19 +3,30 @@ import { fieldBase } from './Field';import { cn } from '~/utils';import './Field.css';-export type TextareaProps = React.TextareaHTMLAttributes<HTMLTextAreaElement>;+/** `document` is a long-form editor that reads like the text it will become. */+const TEXTAREA_VARIANTS = {+ default: 'bg-surface-secondary',+ transparent: 'bg-transparent',+ document: 'bg-transparent text-base leading-relaxed',+} as const;++export type TextareaProps = React.TextareaHTMLAttributes<HTMLTextAreaElement> & {+ variant?: keyof typeof TEXTAREA_VARIANTS;+};const Textarea: React.ForwardRefExoticComponent<TextareaProps & React.RefAttributes<HTMLTextAreaElement>-> = React.forwardRef<HTMLTextAreaElement, TextareaProps>(({ className = '', ...props }, ref) => {- return (- <textarea- className={cn(fieldBase, 'bg-surface-secondary min-h-20 resize-none', className)}- ref={ref}- {...props}- />- );-});+> = React.forwardRef<HTMLTextAreaElement, TextareaProps>(+ ({ className = '', variant = 'default', ...props }, ref) => {+ return (+ <textarea+ className={cn(fieldBase, TEXTAREA_VARIANTS[variant], 'min-h-20 resize-none', className)}+ ref={ref}+ {...props}+ />+ );+ },+);Textarea.displayName = 'Textarea';export { Textarea };diff --git a/packages/data-provider/src/api-endpoints.ts b/packages/data-provider/src/api-endpoints.tsindex cebb40f6bd..16d2b05311 100644--- a/packages/data-provider/src/api-endpoints.ts+++ b/packages/data-provider/src/api-endpoints.ts@@ -176,6 +176,15 @@ export const projects = (params: q.ProjectListParams = {}) => {export const projectById = (id: string) => `${projectsRoot}/${encodeURIComponent(id)}`;+export const projectFiles = (projectId: string) => `${projectById(projectId)}/files`;+export const projectAvailableFiles = (+ projectId: string,+ params: q.ProjectAvailableFilesParams = {},+) => `${projectById(projectId)}/files/available${buildQuery(params)}`;++export const projectFile = (projectId: string, fileId: string) =>+ `${projectFiles(projectId)}/${encodeURIComponent(fileId)}`;+export const projectConversation = (conversationId: string) =>`${projectsRoot}/conversations/${encodeURIComponent(conversationId)}`;diff --git a/packages/data-provider/src/config.spec.ts b/packages/data-provider/src/config.spec.tsindex fa1083d00b..a0ca00b949 100644--- a/packages/data-provider/src/config.spec.ts+++ b/packages/data-provider/src/config.spec.ts@@ -6,6 +6,7 @@ import {DEFAULT_MAX_RETAINED_TOOL_COUNT_CHARS,bedrockModels,configSchema,+ chatProjectsConfigSchema,DEFAULT_STEER_ARM_CONFIRMATION_TIMEOUT_MS,codeEnvironmentUserConfigSchema,interfaceSchema,@@ -305,6 +306,31 @@ describe('run-scoped subagent file sharing config', () => {});});+describe('Chat Projects config', () => {+ it('defaults project limits and accepts operator overrides', () => {+ const defaults = configSchema.parse({ version: '1.2.1' });+ expect(defaults.projects).toEqual({+ maxFiles: 50,+ maxInstructionsLength: 16000,+ maxDescriptionLength: 1000,+ });++ const configured = configSchema.parse({+ version: '1.2.1',+ projects: {+ maxFiles: 75,+ maxInstructionsLength: 24000,+ maxDescriptionLength: 2000,+ },+ });+ expect(configured.projects).toEqual({+ maxFiles: 75,+ maxInstructionsLength: 24000,+ maxDescriptionLength: 2000,+ });+ });+});+describe('scheduled MCP preflight config', () => {it('bounds the separate readiness admission pool', () => {expect(@@ -2293,4 +2319,14 @@ describe('interface theme config', () => {}).success,).toBe(false);});++ it('accepts the ceilings and rejects values above them', () => {+ const atCeiling = { maxFiles: 500, maxInstructionsLength: 200000, maxDescriptionLength: 10000 };+ expect(chatProjectsConfigSchema.parse(atCeiling)).toEqual(atCeiling);+ expect(chatProjectsConfigSchema.safeParse({ maxFiles: 501 }).success).toBe(false);+ expect(chatProjectsConfigSchema.safeParse({ maxInstructionsLength: 200001 }).success).toBe(+ false,+ );+ expect(chatProjectsConfigSchema.safeParse({ maxDescriptionLength: 10001 }).success).toBe(false);+ });});diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.tsindex 61f8700031..2e0d6c7102 100644--- a/packages/data-provider/src/config.ts+++ b/packages/data-provider/src/config.ts@@ -1,6 +1,17 @@import { z } from 'zod';import type { ZodError } from 'zod';import type { TEndpointsConfig, TModelsConfig, TConfig } from './types';+import {+ MAX_SUBAGENTS,+ MAX_SUBAGENTS_CEILING,+ MAX_CHAT_PROJECT_DESCRIPTION_LENGTH,+ MAX_CHAT_PROJECT_INSTRUCTIONS_LENGTH,+ MAX_CHAT_PROJECT_FILES,+ MAX_CHAT_PROJECT_FILES_CEILING,+ MAX_CHAT_PROJECT_DESCRIPTION_LENGTH_CEILING,+ MAX_CHAT_PROJECT_INSTRUCTIONS_LENGTH_CEILING,+ DEFAULT_MAX_RETAINED_TOOL_COUNT_CHARS,+} from './limits';import {filtersConfigSchema,MAX_PII_CUSTOM_REGEX_CHARACTERS,@@ -26,11 +37,6 @@ import {export const AGENT_BACKGROUND_COMPLETION_RESULT_MAX_CHARS_DEFAULT = 24 * 1024;export const AGENT_BACKGROUND_COMPLETION_RESULT_MAX_CHARS_HARD_MAX = 64 * 1024;export const AGENT_BACKGROUND_SHUTDOWN_INTERRUPT_GRACE_MS_DEFAULT = 5_000;-import {- MAX_SUBAGENTS,- MAX_SUBAGENTS_CEILING,- DEFAULT_MAX_RETAINED_TOOL_COUNT_CHARS,-} from './limits';import {DEFAULT_MCP_APP_CSP_LIMITS,resolveMCPAppCspLimits,@@ -55,6 +61,11 @@ export {MAX_CHAT_PROJECT_DESCRIPTION_LENGTH,DEFAULT_RETAINED_ANSWER_TOKENS,DEFAULT_MAX_RETAINED_TOOL_COUNT_CHARS,+ MAX_CHAT_PROJECT_INSTRUCTIONS_LENGTH,+ MAX_CHAT_PROJECT_FILES,+ MAX_CHAT_PROJECT_FILES_CEILING,+ MAX_CHAT_PROJECT_DESCRIPTION_LENGTH_CEILING,+ MAX_CHAT_PROJECT_INSTRUCTIONS_LENGTH_CEILING,} from './limits';export const defaultSocialLogins = ['google', 'facebook', 'openid', 'github', 'discord', 'saml'];@@ -2821,6 +2832,7 @@ export type TStartupConfig = {adminPanelURL?: string;customFooter?: string;modelSpecs?: TSpecsConfig;+ projects?: TChatProjectsConfig;modelDescriptions?: Record<string, Record<string, string>>;sharedLinksEnabled: boolean;publicSharedLinksEnabled: boolean;@@ -2834,6 +2846,8 @@ export type TStartupConfig = {rum?: TRumConfig;bundlerURL?: string;staticBundlerURL?: string;+ /** Whether the deployment has a configured RAG service. */+ ragEnabled?: boolean;sharePointFilePickerEnabled?: boolean;sharePointBaseUrl?: string;sharePointPickerGraphScope?: string;@@ -3374,6 +3388,37 @@ export const openIdDiscoverySchema = z.object({});export type TOpenIdDiscoveryConfig = z.infer<typeof openIdDiscoverySchema>;+export const chatProjectsConfigSchema = z+ .object({+ /** Maximum number of reference files attached to one Chat Project. Defaults to 50. */+ maxFiles: z+ .number()+ .int()+ .positive()+ .max(MAX_CHAT_PROJECT_FILES_CEILING)+ .optional()+ .default(MAX_CHAT_PROJECT_FILES),+ /** Maximum instruction characters stored for one Chat Project. Defaults to 16000. */+ maxInstructionsLength: z+ .number()+ .int()+ .positive()+ .max(MAX_CHAT_PROJECT_INSTRUCTIONS_LENGTH_CEILING)+ .optional()+ .default(MAX_CHAT_PROJECT_INSTRUCTIONS_LENGTH),+ /** Maximum description characters stored for one Chat Project. Defaults to 1000. */+ maxDescriptionLength: z+ .number()+ .int()+ .positive()+ .max(MAX_CHAT_PROJECT_DESCRIPTION_LENGTH_CEILING)+ .optional()+ .default(MAX_CHAT_PROJECT_DESCRIPTION_LENGTH),+ })+ .strict()+ .default({});++export type TChatProjectsConfig = z.infer<typeof chatProjectsConfigSchema>;/** Maximum CAS attempts per ACL document, including the initial attempt. */export const permissionWriteAttemptsSchema = z.number().int().min(1).max(100).default(3);@@ -3398,6 +3443,7 @@ export const configSchema = z.object({version: z.string(),permissions: z.object({ maxWriteAttempts: permissionWriteAttemptsSchema }).optional(),cache: z.boolean().default(true),+ projects: chatProjectsConfigSchema,ocr: ocrSchema.optional(),webSearch: webSearchSchema.optional(),langfuse: langfuseConfigSchema.optional(),diff --git a/packages/data-provider/src/data-service.ts b/packages/data-provider/src/data-service.tsindex 07505efdbe..455c805c0a 100644--- a/packages/data-provider/src/data-service.ts+++ b/packages/data-provider/src/data-service.ts@@ -1042,6 +1042,31 @@ export function deleteProject(projectId: string): Promise<t.TDeleteChatProjectRereturn request.delete(endpoints.projectById(projectId));}+export function getProjectFiles(projectId: string): Promise<t.TChatProjectFile[]> {+ return request.get(endpoints.projectFiles(projectId));+}++export function getAvailableProjectFiles(+ projectId: string,+ params: q.ProjectAvailableFilesParams = {},+): Promise<q.ProjectAvailableFilesResponse> {+ return request.get(endpoints.projectAvailableFiles(projectId, params));+}++export function addProjectFile(payload: {+ projectId: string;+ file_id: string;+}): Promise<t.TChatProject> {+ return request.post(endpoints.projectFiles(payload.projectId), { file_id: payload.file_id });+}++export function removeProjectFile(payload: {+ projectId: string;+ file_id: string;+}): Promise<t.TChatProject> {+ return request.delete(endpoints.projectFile(payload.projectId, payload.file_id));+}+export function assignConversationToProject(payload: t.TAssignConversationToProjectRequest,): Promise<t.TAssignConversationToProjectResponse> {diff --git a/packages/data-provider/src/keys.ts b/packages/data-provider/src/keys.tsindex d86428222f..3d4c9b563d 100644--- a/packages/data-provider/src/keys.ts+++ b/packages/data-provider/src/keys.ts@@ -56,6 +56,8 @@ export enum QueryKeys {promptGroup = 'promptGroup',projects = 'projects',project = 'project',+ projectFiles = 'projectFiles',+ projectAvailableFiles = 'projectAvailableFiles',projectConversations = 'projectConversations',categories = 'categories',randomPrompts = 'randomPrompts',@@ -110,6 +112,9 @@ export enum QueryKeys {// Dynamic query keys that require parametersexport const DynamicQueryKeys = {agentFiles: (agentId: string) => ['agentFiles', agentId] as const,+ projectFiles: (projectId: string) => [QueryKeys.projectFiles, projectId] as const,+ projectAvailableFiles: (projectId: string) =>+ [QueryKeys.projectAvailableFiles, projectId] as const,codeEnvironmentStatus: (id: string) => [QueryKeys.codeEnvironments, id, 'status'] as const,} as const;@@ -159,6 +164,8 @@ export enum MutationKeys {updateProject = 'updateProject',deleteProject = 'deleteProject',assignConversationToProject = 'assignConversationToProject',+ addProjectFile = 'addProjectFile',+ removeProjectFile = 'removeProjectFile',/* Skill mutations from the original UI PR — tree/node operations are* phase 2 and currently stubbed in the data-service layer. */createSkillNode = 'createSkillNode',diff --git a/packages/data-provider/src/limits.ts b/packages/data-provider/src/limits.tsindex 167deda457..89e9228c38 100644--- a/packages/data-provider/src/limits.ts+++ b/packages/data-provider/src/limits.ts@@ -22,9 +22,15 @@ export const setMaxSubagents = (value: number | undefined): void => {};/** Chat project field limits. The dialogs and the persistence layer share these,- * so the inputs stop at the same point the server would otherwise truncate. */+ * so the inputs stop at the same point the server would otherwise truncate. */export const MAX_CHAT_PROJECT_NAME_LENGTH = 100;export const MAX_CHAT_PROJECT_DESCRIPTION_LENGTH = 1000;+export const MAX_CHAT_PROJECT_INSTRUCTIONS_LENGTH = 16000;+export const MAX_CHAT_PROJECT_FILES = 50;+/** Hard ceilings an operator cannot raise the configurable limits above. */+export const MAX_CHAT_PROJECT_DESCRIPTION_LENGTH_CEILING = 10000;+export const MAX_CHAT_PROJECT_INSTRUCTIONS_LENGTH_CEILING = 200000;+export const MAX_CHAT_PROJECT_FILES_CEILING = 500;/** Mirrors the bounded graph-child member limit in `@librechat/agents`. */export const MAX_GRAPH_SUBAGENT_MEMBERS = 32;diff --git a/packages/data-provider/src/types.ts b/packages/data-provider/src/types.tsindex 4e6d4a6926..960d6b647d 100644--- a/packages/data-provider/src/types.ts+++ b/packages/data-provider/src/types.ts@@ -408,6 +408,11 @@ export type TChatProject = {_id: string;name: string;description?: string;+ instructions?: string;+ contextRevision?: number;+ file_ids?: string[];+ hasInstructions?: boolean;+ fileCount?: number;user?: string;conversationCount: number;lastConversationAt?: string | null;@@ -419,10 +424,21 @@ export type TChatProject = {export type TCreateChatProjectRequest = {name: string;description?: string;+ instructions?: string;};export type TUpdateChatProjectRequest = Partial<TCreateChatProjectRequest> & {projectId: string;+ /** Revision the edit was based on; a stale value is rejected with a 409 conflict. */+ contextRevision?: number;+};++export type TChatProjectFile = {+ file_id: string;+ filename?: string;+ type?: string;+ bytes?: number;+ availability: 'ready' | 'unavailable';};export type TDeleteChatProjectResponse = {diff --git a/packages/data-provider/src/types/agents.ts b/packages/data-provider/src/types/agents.tsindex 12f98adfac..7220f8add2 100644--- a/packages/data-provider/src/types/agents.ts+++ b/packages/data-provider/src/types/agents.ts@@ -559,6 +559,11 @@ export namespace Agents {* worker that didn't originate the run.*/threadId?: string;+ /**+ * Stable server-only project context identity captured when this action paused.+ * This is intentionally omitted from all client-facing projections.+ */+ projectContextKey?: string;/*** Fingerprint of the request fields that determine the agent/graph + tool set* (endpoint, agent_id, model, spec, ephemeralAgent), captured at pause time. Thediff --git a/packages/data-provider/src/types/files.ts b/packages/data-provider/src/types/files.tsindex 5a415af39b..50c6e4dbe9 100644--- a/packages/data-provider/src/types/files.ts+++ b/packages/data-provider/src/types/files.ts@@ -171,6 +171,7 @@ export type TFile = {width?: number;height?: number;expiresAt?: string | Date;+ expiredAt?: string | Date | null;preview?: string;text?: string;/**diff --git a/packages/data-provider/src/types/queries.ts b/packages/data-provider/src/types/queries.tsindex 4d7dbc8820..5328a8052d 100644--- a/packages/data-provider/src/types/queries.ts+++ b/packages/data-provider/src/types/queries.ts@@ -3,6 +3,7 @@ import type { RerankerTypes, SearchProviders, ScraperProviders } from '../configimport type * as p from '../accessPermissions';import type * as a from '../types/agents';import type * as s from '../schemas';+import type { TFile } from './files';import type * as t from '../types';export type Conversation = {@@ -81,6 +82,16 @@ export type ProjectListResponse = {};export type ProjectData = InfiniteData<ProjectListResponse>;+export type ProjectAvailableFilesParams = {+ cursor?: string;+ limit?: number;+ search?: string;+};++export type ProjectAvailableFilesResponse = {+ files: TFile[];+ nextCursor: string | null;+};/* Messages */export type MessagesListParams = {diff --git a/packages/data-schemas/src/app/service.ts b/packages/data-schemas/src/app/service.tsindex 132afaed7c..3f1f01039b 100644--- a/packages/data-schemas/src/app/service.ts+++ b/packages/data-schemas/src/app/service.ts@@ -1,6 +1,7 @@import {AgentCapabilities,EModelEndpoint,+ chatProjectsConfigSchema,filtersConfigSchema,conversationListConfigSchema,hasActiveFiltersConfig,@@ -180,6 +181,7 @@ export const AppService = async (params?: {const registration = config.registration ?? configDefaults.registration;const emailChange = config.emailChange;const interfaceConfig = await loadDefaultInterface({ config, configDefaults });+ const projects = chatProjectsConfigSchema.parse(config.projects ?? {});const turnstileConfig = loadTurnstileConfig(config, configDefaults);const speech = config.speech;const filters = loadFiltersConfig(config);@@ -199,6 +201,7 @@ export const AppService = async (params?: {mcpSettings,mcpAppSandbox,fileStrategy,+ projects,registration,emailChange,passkeys: config.passkeys,diff --git a/packages/data-schemas/src/index.ts b/packages/data-schemas/src/index.tsindex 933420feef..e2f7e93ce9 100644--- a/packages/data-schemas/src/index.ts+++ b/packages/data-schemas/src/index.ts@@ -46,6 +46,10 @@ export {MCPAuthorityProofError,createMCPAuthorizationFenceRetryStorage,MAX_MCP_AUTHORITY_TARGETS,+ InvalidAvailableProjectFilesCursorError,+ parseAvailableProjectFilesCursor,+ MAX_AVAILABLE_PROJECT_FILES_LIMIT,+ DEFAULT_AVAILABLE_PROJECT_FILES_LIMIT,createMCPAuthorityBootRevision,createMCPAuthorityConfigSourceRevision,createMCPAuthorityCredentialRevision,diff --git a/packages/data-schemas/src/methods/chatProject.spec.ts b/packages/data-schemas/src/methods/chatProject.spec.tsindex 818d5aea28..7f91403afb 100644--- a/packages/data-schemas/src/methods/chatProject.spec.ts+++ b/packages/data-schemas/src/methods/chatProject.spec.ts@@ -1,11 +1,17 @@import mongoose from 'mongoose';import { MongoMemoryServer } from 'mongodb-memory-server';-import type { IChatProject, IConversation } from '~/types';+import {+ FileContext,+ MAX_CHAT_PROJECT_FILES,+ MAX_CHAT_PROJECT_INSTRUCTIONS_LENGTH,+} from 'librechat-data-provider';+import type { IChatProject, IConversation, IMongoFile } from '~/types';import {createChatProjectMethods,updateChatProjectLastConversationForUser,type ChatProjectMethods,} from './chatProject';+import { tenantStorage } from '~/config/tenantContext';import { createModels } from '~/models';jest.mock('~/config/winston', () => ({@@ -18,6 +24,7 @@ jest.mock('~/config/winston', () => ({let mongoServer: InstanceType<typeof MongoMemoryServer>;let ChatProject: mongoose.Model<IChatProject>;let Conversation: mongoose.Model<IConversation>;+let File: mongoose.Model<IMongoFile>;let methods: ChatProjectMethods;let modelsToCleanup: string[] = [];@@ -31,6 +38,7 @@ beforeAll(async () => {ChatProject = mongoose.models.ChatProject as mongoose.Model<IChatProject>;Conversation = mongoose.models.Conversation as mongoose.Model<IConversation>;+ File = mongoose.models.File as mongoose.Model<IMongoFile>;methods = createChatProjectMethods(mongoose);await mongoose.connect(mongoUri);@@ -50,6 +58,7 @@ afterAll(async () => {afterEach(async () => {await ChatProject.deleteMany({});await Conversation.deleteMany({});+ await File.deleteMany({});});async function createConversation(user: string, conversationId: string, title: string) {@@ -515,6 +524,20 @@ describe('ChatProject methods', () => {expect(conversation?.chatProjectId).toBeUndefined();});+ it('unassigns chats before deleting and keeps the project when the unassign fails', async () => {+ const project = await methods.createChatProject(user, { name: 'Ordered' });+ await createConversation(user, 'convo-order', 'First');+ await methods.assignConversationToProject(user, 'convo-order', project._id!.toString());+ const spy = jest.spyOn(Conversation, 'updateMany').mockRejectedValueOnce(new Error('boom'));++ await expect(methods.deleteChatProject(user, project._id!.toString())).rejects.toThrow('boom');+ spy.mockRestore();++ expect(await ChatProject.countDocuments({ _id: project._id })).toBe(1);+ const conversation = await Conversation.findOne({ conversationId: 'convo-order' }).lean();+ expect(conversation?.chatProjectId).toBe(project._id!.toString());+ });+it('isolates projects and assignments by user', async () => {const project = await methods.createChatProject(user, { name: 'Mine' });await createConversation(otherUser, 'convo-1', 'Theirs');@@ -532,3 +555,432 @@ describe('ChatProject methods', () => {expect(deleteResult.deletedCount).toBe(0);});});++describe('persistent Project context', () => {+ const owner = new mongoose.Types.ObjectId().toString();+ const otherOwner = new mongoose.Types.ObjectId().toString();++ async function createReference(fileId: string, overrides: Partial<IMongoFile> = {}) {+ return File.create({+ user: owner,+ file_id: fileId,+ filename: `${fileId}.pdf`,+ filepath: `/uploads/${fileId}.pdf`,+ type: 'application/pdf',+ bytes: 100,+ embedded: true,+ context: FileContext.message_attachment,+ ...overrides,+ });+ }++ it('persists instructions independently of description and advances semantic revisions', async () => {+ const project = await methods.createChatProject(owner, {+ name: 'Documentation',+ description: 'Human-facing summary',+ instructions: 'Use concise technical English.',+ });+ const id = project._id!.toString();+ await methods.updateChatProject(owner, id, { description: 'Renamed summary' });+ const metadataOnly = await methods.getChatProject(owner, id);+ expect(metadataOnly?.instructions).toBe('Use concise technical English.');+ expect(metadataOnly?.contextRevision).toBe(project.contextRevision);+ const updated = await methods.updateChatProject(owner, id, {+ instructions: 'Do not describe experimental features as stable.',+ });+ expect(updated?.contextRevision).toBe((project.contextRevision ?? 0) + 1);+ expect(updated?.description).toBe('Renamed summary');+ expect((await methods.getChatProject(owner, id))?.instructions).toBe(updated?.instructions);+ const unchanged = await methods.updateChatProject(owner, id, {+ name: 'Documentation workspace',+ instructions: updated?.instructions,+ });+ expect(unchanged?.contextRevision).toBe(updated?.contextRevision);+ const listed = (await methods.listChatProjects(owner)).projects[0];+ expect(listed.hasInstructions).toBe(true);+ expect(listed).not.toHaveProperty('instructions');+ expect(listed).not.toHaveProperty('file_ids');+ await methods.updateChatProject(owner, id, { instructions: '' });+ expect((await methods.listChatProjects(owner)).projects[0].hasInstructions).toBe(false);+ });++ it('preserves newer instructions and revisions when a metadata fallback follows a lost conditional update', async () => {+ const project = await methods.createChatProject(owner, {+ name: 'Original metadata',+ instructions: 'Guidance A',+ });+ const id = project._id!.toString();++ let signalConditionalMiss!: () => void;+ const conditionalMiss = new Promise<void>((resolve) => {+ signalConditionalMiss = resolve;+ });+ let releaseFallback!: () => void;+ const fallbackRelease = new Promise<void>((resolve) => {+ releaseFallback = resolve;+ });++ const findOneAndUpdate = ChatProject.findOneAndUpdate.bind(ChatProject);+ const updateSpy = jest+ .spyOn(ChatProject, 'findOneAndUpdate')+ .mockImplementation((filter, update, options) => {+ const query = findOneAndUpdate(filter, update, options);+ const queryFilter = query.getFilter();+ if (+ queryFilter._id?.toString() !== id ||+ queryFilter.user !== owner ||+ queryFilter.instructions == null+ ) {+ return query;+ }++ const exec = query.exec.bind(query);+ jest.spyOn(query, 'exec').mockImplementation(async () => {+ const result = await exec();+ if (!result) {+ signalConditionalMiss();+ await fallbackRelease;+ }+ return result;+ });+ return query;+ });++ let staleUpdate: Promise<IChatProject | null> | undefined;+ try {+ staleUpdate = methods.updateChatProject(owner, id, {+ name: 'Metadata winner',+ instructions: 'Guidance A',+ });+ await Promise.race([+ conditionalMiss,+ staleUpdate.then(() => {+ throw new Error('The unchanged instruction update did not reach its metadata fallback');+ }),+ ]);++ const concurrentWrite = await methods.updateChatProject(owner, id, {+ instructions: 'Guidance B',+ });+ expect(concurrentWrite?.instructions).toBe('Guidance B');++ releaseFallback();+ await staleUpdate;+ } finally {+ releaseFallback();+ updateSpy.mockRestore();+ await staleUpdate?.catch(() => undefined);+ }++ const persisted = await methods.getChatProject(owner, id);+ expect(persisted).toMatchObject({+ name: 'Metadata winner',+ instructions: 'Guidance B',+ contextRevision: (project.contextRevision ?? 0) + 1,+ });+ });++ it('rejects excessive instructions without truncating or changing saved context', async () => {+ const instructions = 'x'.repeat(MAX_CHAT_PROJECT_INSTRUCTIONS_LENGTH);+ const project = await methods.createChatProject(owner, { name: 'At limit', instructions });+ await expect(+ methods.updateChatProject(owner, project._id!.toString(), {+ instructions: `${instructions}x`,+ }),+ ).rejects.toThrow('Invalid project instructions');+ const saved = await methods.getChatProject(owner, project._id!.toString());+ expect(saved?.instructions).toBe(instructions);+ expect(saved?.contextRevision).toBe(project.contextRevision);+ await expect(+ methods.createChatProject(owner, { name: 'Too long', instructions: `${instructions}x` }),+ ).rejects.toThrow('Invalid project instructions');+ });++ it('initializes legacy context fields only when their normalized content changes', async () => {+ const { insertedId } = await ChatProject.collection.insertOne({+ name: 'Legacy',+ user: owner,+ conversationCount: 0,+ });+ const id = insertedId.toString();+ expect((await methods.listChatProjects(owner)).projects[0]).toMatchObject({+ hasInstructions: false,+ fileCount: 0,+ });+ await methods.updateChatProject(owner, id, { instructions: '' });+ expect((await methods.getChatProject(owner, id))?.contextRevision ?? 0).toBe(0);+ const updated = await methods.updateChatProject(owner, id, { instructions: 'New context' });+ expect(updated).toMatchObject({ instructions: 'New context', contextRevision: 1 });+ await createReference('legacy-ref');+ const attached = await methods.addChatProjectFile(owner, id, 'legacy-ref');+ expect(attached).toMatchObject({ file_ids: ['legacy-ref'], contextRevision: 2 });+ });++ it('reuses one canonical reference across Projects and conversations without copying or deleting it', async () => {+ const first = await methods.createChatProject(owner, { name: 'First' });+ const second = await methods.createChatProject(owner, { name: 'Second' });+ const deadline = new Date(Date.now() + 86_400_000);+ const original = await createReference('shared-reference', {+ expiresAt: new Date(Date.now() + 3_600_000),+ expiredAt: deadline,+ });+ const id = first._id!.toString();+ const attached = await methods.addChatProjectFile(owner, id, original.file_id);+ await methods.addChatProjectFile(owner, second._id!.toString(), original.file_id);+ await File.updateOne(+ { _id: original._id },+ { $set: { expiresAt: new Date('2026-12-01T00:00:00.000Z'), temp_file_id: 'retry-temp' } },+ );+ const duplicate = await methods.addChatProjectFile(owner, id, original.file_id);+ expect(duplicate?.file_ids).toEqual(['shared-reference']);+ expect(duplicate?.contextRevision).toBe(attached?.contextRevision);+ for (const conversationId of ['reference-chat-one', 'reference-chat-two']) {+ await createConversation(owner, conversationId, conversationId);+ await methods.assignConversationToProject(owner, conversationId, id);+ }+ const canonical = await File.findOne({ file_id: original.file_id }).lean();+ expect(canonical?._id.toString()).toBe(original._id.toString());+ expect(canonical?.filepath).toBe(original.filepath);+ expect(canonical?.expiredAt).toEqual(deadline);+ expect(canonical).not.toHaveProperty('temp_file_id');+ expect(canonical).not.toHaveProperty('expiresAt');+ expect(await File.countDocuments({})).toBe(1);+ const detached = await methods.removeChatProjectFile(owner, id, original.file_id);+ expect(detached?.file_ids).toEqual([]);+ expect(detached?.contextRevision).toBe((attached?.contextRevision ?? 0) + 1);+ const repeated = await methods.removeChatProjectFile(owner, id, original.file_id);+ expect(repeated?.contextRevision).toBe(detached?.contextRevision);+ await methods.deleteChatProject(owner, second._id!.toString());+ expect(await File.countDocuments({ file_id: original.file_id })).toBe(1);+ expect(await Conversation.countDocuments({ user: owner })).toBe(2);+ });++ it('rejects updates based on a stale contextRevision and accepts current ones', async () => {+ const project = await methods.createChatProject(owner, { name: 'Shared', instructions: 'v1' });+ const id = project._id!.toString();+ const revision = project.contextRevision;++ const first = await methods.updateChatProject(owner, id, {+ instructions: 'v2',+ contextRevision: revision,+ });+ expect(first?.instructions).toBe('v2');+ expect(first?.contextRevision).toBe((revision ?? 0) + 1);++ await expect(+ methods.updateChatProject(owner, id, { instructions: 'v3', contextRevision: revision }),+ ).rejects.toThrow('Project revision conflict');+ await expect(+ methods.updateChatProject(owner, id, { name: 'Renamed', contextRevision: revision }),+ ).rejects.toThrow('Project revision conflict');+ expect((await methods.getChatProject(owner, id))?.instructions).toBe('v2');++ const withoutRevision = await methods.updateChatProject(owner, id, { instructions: 'v4' });+ expect(withoutRevision?.instructions).toBe('v4');++ expect(+ await methods.updateChatProject(owner, new mongoose.Types.ObjectId().toString(), {+ name: 'x',+ contextRevision: 0,+ }),+ ).toBeNull();+ });++ it('releases the temporary hold before attaching and attaches nothing when the release fails', async () => {+ const project = await methods.createChatProject(owner, { name: 'Holds' });+ const id = project._id!.toString();+ const expiresAt = new Date(Date.now() + 3_600_000);+ await createReference('held', { expiresAt });+ await createReference('held-fail', { expiresAt });++ const attached = await methods.addChatProjectFile(owner, id, 'held');+ expect(attached?.file_ids).toEqual(['held']);+ expect(await File.findOne({ file_id: 'held' }).lean()).not.toHaveProperty('expiresAt');++ const spy = jest.spyOn(File, 'updateOne').mockImplementationOnce(() => {+ throw new Error('release failed');+ });+ await expect(methods.addChatProjectFile(owner, id, 'held-fail')).rejects.toThrow(+ 'release failed',+ );+ spy.mockRestore();+ expect((await methods.getChatProject(owner, id))?.file_ids).toEqual(['held']);+ expect((await File.findOne({ file_id: 'held-fail' }).lean())?.expiresAt).toEqual(expiresAt);+ });++ it('attaches nothing when the file is deleted while the attach is in flight', async () => {+ const project = await methods.createChatProject(owner, { name: 'Racing' });+ const id = project._id!.toString();+ await createReference('gone-before-release');+ await createReference('gone-before-attach');++ const release = File.updateOne.bind(File);+ const releaseSpy = jest.spyOn(File, 'updateOne').mockImplementationOnce(((+ ...args: Parameters<typeof File.updateOne>+ ) => {+ return File.deleteOne({ file_id: 'gone-before-release' }).then(() => release(...args));+ }) as unknown as typeof File.updateOne);+ await expect(methods.addChatProjectFile(owner, id, 'gone-before-release')).rejects.toThrow(+ 'Project file unavailable',+ );+ releaseSpy.mockRestore();++ const attach = ChatProject.findOneAndUpdate.bind(ChatProject);+ const attachSpy = jest.spyOn(ChatProject, 'findOneAndUpdate').mockImplementationOnce(((+ ...args: Parameters<typeof ChatProject.findOneAndUpdate>+ ) => {+ const query = attach(...args);+ const exec = query.exec.bind(query);+ query.exec = () => File.deleteOne({ file_id: 'gone-before-attach' }).then(() => exec());+ return query;+ }) as unknown as typeof ChatProject.findOneAndUpdate);+ await expect(methods.addChatProjectFile(owner, id, 'gone-before-attach')).rejects.toThrow(+ 'Project file unavailable',+ );+ attachSpy.mockRestore();++ expect((await methods.getChatProject(owner, id))?.file_ids).toEqual([]);+ });++ it('rejects unauthorized, agent-scoped, unindexed, missing and expired references', async () => {+ const project = await methods.createChatProject(owner, { name: 'Private' });+ const id = project._id!.toString();+ await createReference('foreign', { user: new mongoose.Types.ObjectId(otherOwner) });+ await createReference('agent-index', { context: FileContext.agents });+ await createReference('unindexed', { embedded: false });+ await createReference('expired', { expiredAt: new Date(0) });+ for (const fileId of ['foreign', 'agent-index', 'unindexed', 'expired', 'missing']) {+ await expect(methods.addChatProjectFile(owner, id, fileId)).rejects.toThrow(+ 'Project file unavailable',+ );+ }+ const orphanExpiry = new Date('2026-12-15T00:00:00.000Z');+ await createReference('orphan', { expiresAt: orphanExpiry, temp_file_id: 'orphan-temp' });+ const missingProjectId = new mongoose.Types.ObjectId().toString();+ expect(await methods.addChatProjectFile(owner, missingProjectId, 'orphan')).toBeNull();+ const orphan = await File.findOne({ file_id: 'orphan' }).lean();+ expect(orphan?.expiresAt).toEqual(orphanExpiry);+ expect(orphan?.temp_file_id).toBe('orphan-temp');+ await createReference('private');+ expect(await methods.addChatProjectFile(otherOwner, id, 'private')).toBeNull();+ expect(+ await methods.updateChatProject(otherOwner, id, { instructions: 'Injected' }),+ ).toBeNull();+ expect(await methods.removeChatProjectFile(otherOwner, id, 'private')).toBeNull();+ expect((await methods.getChatProject(owner, id))?.file_ids).toEqual([]);+ });++ it('enforces tenant isolation even for identical owner IDs', async () => {+ const id = await tenantStorage.run({ tenantId: 'project-tenant-a' }, async () => {+ const project = await methods.createChatProject(owner, {+ name: 'Tenant A',+ instructions: 'A',+ });+ await createReference('tenant-a-ref');+ await methods.addChatProjectFile(owner, project._id!.toString(), 'tenant-a-ref');+ return project._id!.toString();+ });+ await tenantStorage.run({ tenantId: 'project-tenant-b' }, async () => {+ await createReference('tenant-b-ref');+ expect(await methods.getChatProject(owner, id)).toBeNull();+ expect((await methods.listChatProjects(owner)).projects).toEqual([]);+ expect(await methods.updateChatProject(owner, id, { instructions: 'B' })).toBeNull();+ expect(await methods.addChatProjectFile(owner, id, 'tenant-b-ref')).toBeNull();+ expect(await methods.removeChatProjectFile(owner, id, 'tenant-a-ref')).toBeNull();+ expect((await methods.deleteChatProject(owner, id)).deletedCount).toBe(0);+ });+ await tenantStorage.run({ tenantId: 'project-tenant-a' }, async () => {+ await expect(methods.addChatProjectFile(owner, id, 'tenant-b-ref')).rejects.toThrow(+ 'Project file unavailable',+ );+ expect(await methods.getChatProject(owner, id)).toMatchObject({+ instructions: 'A',+ file_ids: ['tenant-a-ref'],+ });+ });+ });++ it('bounds concurrent attachment writes at the Project limit without consuming the losing hold', async () => {+ const project = await methods.createChatProject(owner, { name: 'Almost full' });+ const existingIds = Array.from(+ { length: MAX_CHAT_PROJECT_FILES - 1 },+ (_, index) => `ref-${index}`,+ );+ await ChatProject.updateOne({ _id: project._id }, { $set: { file_ids: existingIds } });+ const now = Date.now();+ const day = 24 * 60 * 60 * 1000;+ const firstExpiry = new Date(now + day);+ const secondExpiry = new Date(now + 2 * day);+ const firstRetentionExpiry = new Date(now + 3 * day);+ const secondRetentionExpiry = new Date(now + 4 * day);+ await createReference('last-a', {+ expiresAt: firstExpiry,+ temp_file_id: 'temporary-a',+ expiredAt: firstRetentionExpiry,+ });+ await createReference('last-b', {+ expiresAt: secondExpiry,+ temp_file_id: 'temporary-b',+ expiredAt: secondRetentionExpiry,+ });++ // Delay admission execution until both contenders have completed their initial Project read.+ let admissions = 0;+ let releaseAdmissions!: () => void;+ const bothAdmissions = new Promise<void>((resolve) => {+ releaseAdmissions = resolve;+ });+ const findOneAndUpdate = ChatProject.findOneAndUpdate.bind(ChatProject);+ const admissionSpy = jest+ .spyOn(ChatProject, 'findOneAndUpdate')+ .mockImplementation((filter, update, options) => {+ const query = findOneAndUpdate(filter, update, options);+ const queryFilter = query.getFilter();+ if (+ admissions < 2 &&+ queryFilter._id?.toString() === project._id!.toString() &&+ queryFilter.file_ids != null+ ) {+ admissions += 1;+ const exec = query.exec.bind(query);+ jest.spyOn(query, 'exec').mockImplementation(async () => {+ if (admissions === 2) {+ releaseAdmissions();+ }+ await bothAdmissions;+ return await exec();+ });+ }+ return query;+ });++ try {+ const results = await Promise.allSettled(+ ['last-a', 'last-b'].map((id) =>+ methods.addChatProjectFile(owner, project._id!.toString(), id),+ ),+ );+ expect(results.filter((result) => result.status === 'fulfilled')).toHaveLength(1);+ const rejected = results.find((result) => result.status === 'rejected');+ expect(rejected?.status === 'rejected' && rejected.reason.message).toBe(+ 'Project file limit reached',+ );+ } finally {+ admissionSpy.mockRestore();+ }++ const savedProject = await methods.getChatProject(owner, project._id!.toString());+ expect(savedProject?.file_ids).toHaveLength(MAX_CHAT_PROJECT_FILES);+ const winner = savedProject?.file_ids?.includes('last-a') ? 'last-a' : 'last-b';+ const loser = winner === 'last-a' ? 'last-b' : 'last-a';+ const winnerFile = await File.findOne({ file_id: winner }).lean();+ const loserFile = await File.findOne({ file_id: loser }).lean();+ expect(winnerFile).not.toHaveProperty('expiresAt');+ expect(winnerFile).not.toHaveProperty('temp_file_id');+ expect(loserFile?.expiresAt).toEqual(loser === 'last-a' ? firstExpiry : secondExpiry);+ expect(loserFile?.temp_file_id).toBe(`temporary-${loser === 'last-a' ? 'a' : 'b'}`);+ expect(loserFile?.expiredAt).toEqual(+ loser === 'last-a' ? firstRetentionExpiry : secondRetentionExpiry,+ );+ });+});diff --git a/packages/data-schemas/src/methods/chatProject.ts b/packages/data-schemas/src/methods/chatProject.tsindex 1e926b5d58..4a2504bc43 100644--- a/packages/data-schemas/src/methods/chatProject.ts+++ b/packages/data-schemas/src/methods/chatProject.ts@@ -1,9 +1,13 @@import {+ FileContext,+ MAX_CHAT_PROJECT_FILES,+ MAX_CHAT_PROJECT_INSTRUCTIONS_LENGTH,MAX_CHAT_PROJECT_NAME_LENGTH,MAX_CHAT_PROJECT_DESCRIPTION_LENGTH,} from 'librechat-data-provider';import type { FilterQuery, Model, SortOrder, Types } from 'mongoose';-import type { IChatProject, IChatProjectDocument, IConversation } from '~/types';+import type { TChatProjectsConfig } from 'librechat-data-provider';+import type { IChatProject, IChatProjectDocument, IConversation, IMongoFile } from '~/types';import { buildRetentionVisibilityFilter } from '~/utils/retention';import { isValidObjectIdString } from '~/utils/objectId';import { escapeRegExp } from '~/utils/string';@@ -15,9 +19,14 @@ export type ChatProjectSortDirection = 'asc' | 'desc';export type CreateChatProjectInput = {name: string;description?: string | null;+ instructions?: string;};-export type UpdateChatProjectInput = Partial<CreateChatProjectInput>;+export type UpdateChatProjectInput = Partial<CreateChatProjectInput> & {+ contextRevision?: number;+};++export const CHAT_PROJECT_CONFLICT = 'Project revision conflict';export type ListChatProjectsOptions = {cursor?: string | null;@@ -44,7 +53,11 @@ export type AssignConversationToProjectResult = {};export interface ChatProjectMethods {- createChatProject(user: string, input: CreateChatProjectInput): Promise<IChatProject>;+ createChatProject(+ user: string,+ input: CreateChatProjectInput,+ limits?: Partial<ChatProjectLimits>,+ ): Promise<IChatProject>;getChatProject(user: string, projectId: string): Promise<IChatProject | null>;listChatProjects(user: string,@@ -54,8 +67,20 @@ export interface ChatProjectMethods {user: string,projectId: string,input: UpdateChatProjectInput,+ limits?: Partial<ChatProjectLimits>,): Promise<IChatProject | null>;deleteChatProject(user: string, projectId: string): Promise<DeleteChatProjectResult>;+ addChatProjectFile(+ user: string,+ projectId: string,+ fileId: string,+ limits?: Partial<ChatProjectLimits>,+ ): Promise<IChatProject | null>;+ removeChatProjectFile(+ user: string,+ projectId: string,+ fileId: string,+ ): Promise<IChatProject | null>;assignConversationToProject(user: string,conversationId: string,@@ -68,16 +93,26 @@ type ProjectCursor = {primary: string | null;id: string;};+export type ChatProjectLimits = Pick<+ TChatProjectsConfig,+ 'maxFiles' | 'maxInstructionsLength' | 'maxDescriptionLength'+>;-type ProjectLean = IChatProject & { _id: Types.ObjectId };type ProjectStatsSnapshot = Pick<IChatProject,'conversationCount' | 'lastConversationAt' | 'lastConversationId'>;+type ProjectLean = IChatProject & { _id: Types.ObjectId };const VALID_SORT_FIELDS = new Set<ChatProjectSortBy>(['name', 'createdAt', 'lastConversationAt']);const PROJECT_STATS_REFRESH_MAX_ATTEMPTS = 8;+const resolveChatProjectLimits = (limits?: Partial<ChatProjectLimits>): ChatProjectLimits => ({+ maxFiles: limits?.maxFiles ?? MAX_CHAT_PROJECT_FILES,+ maxInstructionsLength: limits?.maxInstructionsLength ?? MAX_CHAT_PROJECT_INSTRUCTIONS_LENGTH,+ maxDescriptionLength: limits?.maxDescriptionLength ?? MAX_CHAT_PROJECT_DESCRIPTION_LENGTH,+});+function normalizeSortBy(sortBy?: string): ChatProjectSortBy {return VALID_SORT_FIELDS.has(sortBy as ChatProjectSortBy)? (sortBy as ChatProjectSortBy)@@ -95,10 +130,29 @@ function normalizeLimit(limit?: number): number {return Math.min(Math.max(Math.floor(limit), 1), 100);}-function sanitizeProjectInput(input: CreateChatProjectInput): CreateChatProjectInput {+function validateProjectInstructions(+ instructions: string | undefined,+ limits?: Partial<ChatProjectLimits>,+): string {+ if (instructions === undefined) {+ return '';+ }+ const { maxInstructionsLength } = resolveChatProjectLimits(limits);+ if (typeof instructions !== 'string' || instructions.length > maxInstructionsLength) {+ throw new Error('Invalid project instructions');+ }+ return instructions.trim();+}++function sanitizeProjectInput(+ input: CreateChatProjectInput,+ limits?: Partial<ChatProjectLimits>,+): CreateChatProjectInput {+ const { maxDescriptionLength } = resolveChatProjectLimits(limits);return {name: input.name.trim().slice(0, MAX_CHAT_PROJECT_NAME_LENGTH),- description: input.description?.trim().slice(0, MAX_CHAT_PROJECT_DESCRIPTION_LENGTH) ?? '',+ description: input.description?.trim().slice(0, maxDescriptionLength) ?? '',+ instructions: validateProjectInstructions(input.instructions, limits),};}@@ -306,7 +360,6 @@ export async function updateChatProjectLastConversationForUser(return;}}-/*** The chat can stop being visible while this pointer write is in flight: an archive-all* sweep, a single archive from another tab, or a retention flip, each of which has@@ -332,9 +385,10 @@ export function createChatProjectMethods(mongoose: typeof import('mongoose')): Casync function createChatProject(user: string,input: CreateChatProjectInput,+ limits?: Partial<ChatProjectLimits>,): Promise<IChatProject> {const ChatProject = mongoose.models.ChatProject as Model<IChatProjectDocument>;- const sanitized = sanitizeProjectInput(input);+ const sanitized = sanitizeProjectInput(input, limits);if (!sanitized.name) {throw new Error('Project name is required');}@@ -389,10 +443,27 @@ export function createChatProjectMethods(mongoose: typeof import('mongoose')): Cconst query =filters.length === 1 ? filters[0] : ({ $and: filters } as FilterQuery<IChatProjectDocument>);- const projects = await ChatProject.find(query)- .sort({ [sortBy]: sortOrder, _id: sortOrder })- .limit(limit + 1)- .lean<ProjectLean[]>();+ const projects = await ChatProject.aggregate<ProjectLean>([+ { $match: query },+ { $sort: { [sortBy]: sortOrder, _id: sortOrder } },+ { $limit: limit + 1 },+ {+ $project: {+ name: 1,+ description: 1,+ user: 1,+ tenantId: 1,+ conversationCount: 1,+ lastConversationAt: 1,+ lastConversationId: 1,+ createdAt: 1,+ updatedAt: 1,+ contextRevision: 1,+ hasInstructions: { $ne: [{ $ifNull: ['$instructions', ''] }, ''] },+ fileCount: { $size: { $ifNull: ['$file_ids', []] } },+ },+ },+ ]);let nextCursor: string | null = null;if (projects.length > limit) {@@ -410,13 +481,15 @@ export function createChatProjectMethods(mongoose: typeof import('mongoose')): Cuser: string,projectId: string,input: UpdateChatProjectInput,+ limits?: Partial<ChatProjectLimits>,): Promise<IChatProject | null> {if (!isValidObjectIdString(projectId)) {return null;}const ChatProject = mongoose.models.ChatProject as Model<IChatProjectDocument>;- const update: Partial<Pick<IChatProject, 'name' | 'description'>> = {};+ const update: Partial<Pick<IChatProject, 'name' | 'description' | 'instructions'>> = {};+ const { maxDescriptionLength } = resolveChatProjectLimits(limits);if (typeof input.name === 'string') {const name = input.name.trim().slice(0, MAX_CHAT_PROJECT_NAME_LENGTH);if (!name) {@@ -425,15 +498,165 @@ export function createChatProjectMethods(mongoose: typeof import('mongoose')): Cupdate.name = name;}if (input.description !== undefined) {- update.description =- input.description?.trim().slice(0, MAX_CHAT_PROJECT_DESCRIPTION_LENGTH) ?? '';+ update.description = input.description?.trim().slice(0, maxDescriptionLength) ?? '';}-- return await ChatProject.findOneAndUpdate(- { _id: new mongoose.Types.ObjectId(projectId), user },+ const ownerFilter = { _id: new mongoose.Types.ObjectId(projectId), user };+ const expected = input.contextRevision;+ const hasExpected = typeof expected === 'number' && Number.isInteger(expected);+ const filter = hasExpected ? { ...ownerFilter, contextRevision: expected } : ownerFilter;+ const conflictOrNull = async (): Promise<IChatProject | null> => {+ if (!hasExpected) {+ return null;+ }+ const current = await getChatProject(user, projectId);+ if (current) {+ throw new Error(CHAT_PROJECT_CONFLICT);+ }+ return null;+ };+ if (input.instructions !== undefined) {+ const instructions = validateProjectInstructions(input.instructions, limits);+ const changed = await ChatProject.findOneAndUpdate(+ {+ ...filter,+ instructions: instructions === '' ? { $nin: ['', null] } : { $ne: instructions },+ },+ { $set: { ...update, instructions }, $inc: { contextRevision: 1 } },+ { new: true, runValidators: true },+ ).lean<IChatProject>();+ if (changed) {+ return changed;+ }+ }+ if (Object.keys(update).length === 0) {+ const current = await getChatProject(user, projectId);+ if (current && hasExpected && current.contextRevision !== expected) {+ throw new Error(CHAT_PROJECT_CONFLICT);+ }+ return current;+ }+ const saved = await ChatProject.findOneAndUpdate(+ filter,{ $set: update },{ new: true, runValidators: true },).lean<IChatProject>();+ return saved ?? (await conflictOrNull());+ }++ async function addChatProjectFile(+ user: string,+ projectId: string,+ fileId: string,+ limits?: Partial<ChatProjectLimits>,+ ): Promise<IChatProject | null> {+ const { maxFiles } = resolveChatProjectLimits(limits);+ const project = await getChatProject(user, projectId);+ if (!project) {+ return null;+ }+ if (!fileId || typeof fileId !== 'string' || fileId.length > 128) {+ throw new Error('Project file unavailable');+ }+ const alreadyAttached = project.file_ids?.includes(fileId) === true;+ if (!alreadyAttached && (project.file_ids?.length ?? 0) >= maxFiles) {+ throw new Error('Project file limit reached');+ }++ const File = mongoose.models.File as Model<IMongoFile>;+ const file = await File.findOne({+ file_id: fileId,+ user,+ tenantId: project.tenantId ?? null,+ embedded: true,+ context: FileContext.message_attachment,+ $or: [{ expiredAt: null }, { expiredAt: { $gt: new Date() } }],+ })+ .select('_id file_id expiresAt temp_file_id')+ .lean();+ if (!file) {+ throw new Error('Project file unavailable');+ }++ const released = await File.updateOne(+ { _id: file._id, file_id: fileId, user, tenantId: project.tenantId ?? null },+ { $unset: { expiresAt: '', temp_file_id: '' } },+ { timestamps: false },+ );+ if (released.matchedCount === 0) {+ throw new Error('Project file unavailable');+ }+ const restoreTemporaryHold = async (): Promise<void> => {+ const hold = {+ ...(file.expiresAt != null ? { expiresAt: file.expiresAt } : {}),+ ...(file.temp_file_id != null ? { temp_file_id: file.temp_file_id } : {}),+ };+ if (Object.keys(hold).length === 0) {+ return;+ }+ try {+ await File.updateOne({ _id: file._id, user }, { $set: hold }, { timestamps: false });+ } catch (error) {+ logger.warn('[chatProject] Failed to restore temporary file hold', error);+ }+ };++ const ChatProject = mongoose.models.ChatProject as Model<IChatProjectDocument>;+ /** A file deleted between the release and the attach has already run its project+ * cleanup, so the reference added after it would dangle; take it back out. */+ const dropIfFileDeleted = async (attached: IChatProject): Promise<IChatProject> => {+ if (await File.exists({ _id: file._id })) {+ return attached;+ }+ await ChatProject.updateOne(+ { _id: project._id, user, file_ids: fileId },+ { $pull: { file_ids: fileId }, $inc: { contextRevision: 1 } },+ );+ throw new Error('Project file unavailable');+ };+ try {+ const updated = await ChatProject.findOneAndUpdate(+ {+ _id: project._id,+ user,+ file_ids: { $ne: fileId },+ [`file_ids.${maxFiles - 1}`]: { $exists: false },+ },+ { $addToSet: { file_ids: fileId }, $inc: { contextRevision: 1 } },+ { new: true, runValidators: true },+ ).lean<IChatProject>();+ if (updated) {+ return await dropIfFileDeleted(updated);+ }+ const current = await getChatProject(user, projectId);+ if (current?.file_ids?.includes(fileId)) {+ return current;+ }+ await restoreTemporaryHold();+ if (!current) {+ return null;+ }+ } catch (error) {+ await restoreTemporaryHold();+ throw error;+ }+ throw new Error('Project file limit reached');+ }++ async function removeChatProjectFile(+ user: string,+ projectId: string,+ fileId: string,+ ): Promise<IChatProject | null> {+ if (!isValidObjectIdString(projectId)) {+ return null;+ }+ const ChatProject = mongoose.models.ChatProject as Model<IChatProjectDocument>;+ const project = await ChatProject.findOneAndUpdate(+ { _id: new mongoose.Types.ObjectId(projectId), user, file_ids: fileId },+ { $pull: { file_ids: fileId }, $inc: { contextRevision: 1 } },+ { new: true },+ ).lean<IChatProject>();+ return project ?? getChatProject(user, projectId);}async function deleteChatProject(@@ -452,13 +675,11 @@ export function createChatProjectMethods(mongoose: typeof import('mongoose')): Creturn { deletedCount: 0, modifiedCount: 0 };}- const [conversationResult, deleteResult] = await Promise.all([- Conversation.updateMany(- { user, chatProjectId: projectId },- { $unset: { chatProjectId: '' } },- ),- ChatProject.deleteOne(projectFilter),- ]);+ const conversationResult = await Conversation.updateMany(+ { user, chatProjectId: projectId },+ { $unset: { chatProjectId: '' } },+ );+ const deleteResult = await ChatProject.deleteOne(projectFilter);return {deletedCount: deleteResult.deletedCount ?? 0,@@ -536,6 +757,8 @@ export function createChatProjectMethods(mongoose: typeof import('mongoose')): ClistChatProjects,updateChatProject,deleteChatProject,+ addChatProjectFile,+ removeChatProjectFile,assignConversationToProject,refreshChatProjectStats,};diff --git a/packages/data-schemas/src/methods/conversation.spec.ts b/packages/data-schemas/src/methods/conversation.spec.tsindex 97897c1aec..a18cc48a93 100644--- a/packages/data-schemas/src/methods/conversation.spec.ts+++ b/packages/data-schemas/src/methods/conversation.spec.ts@@ -18,6 +18,7 @@ import type {} from '../types';import { ConversationMethods, createConversationMethods } from './conversation';import { tenantStorage, runAsSystem } from '~/config/tenantContext';+import { createChatProjectMethods } from './chatProject';import { createModels } from '../models';jest.mock('~/config/winston', () => ({@@ -256,6 +257,52 @@ describe('Conversation Operations', () => {expect(saved?.initial_agent_id).toBe('agent-a');expect(saved?.agent_id).toBe('agent-b');});+ it('does not undo explicit Project moves or removal when a stale turn completes', async () => {+ const firstProject = await ChatProject.create({+ user: mockCtx.userId,+ name: 'Insert Project A',+ conversationCount: 0,+ lastConversationAt: null,+ lastConversationId: null,+ });+ const secondProject = await ChatProject.create({+ user: mockCtx.userId,+ name: 'Insert Project B',+ conversationCount: 0,+ lastConversationAt: null,+ lastConversationId: null,+ });+ const conversationId = uuidv4();++ await saveConvo(mockCtx, {+ conversationId,+ title: 'Project turn',+ chatProjectId: firstProject._id!.toString(),+ });+ const projects = createChatProjectMethods(mongoose);+ await projects.assignConversationToProject(+ mockCtx.userId,+ conversationId,+ secondProject._id!.toString(),+ );+ await saveConvo(mockCtx, {+ conversationId,+ title: 'Stale turn',+ chatProjectId: firstProject._id!.toString(),+ });+ expect((await Conversation.findOne({ conversationId }).lean())?.chatProjectId).toBe(+ secondProject._id!.toString(),+ );+ await projects.assignConversationToProject(mockCtx.userId, conversationId, null);+ await saveConvo(mockCtx, {+ conversationId,+ title: 'Another stale turn',+ chatProjectId: firstProject._id!.toString(),+ });++ const saved = await Conversation.findOne({ conversationId }).lean();+ expect(saved?.chatProjectId == null).toBe(true);+ });it('stores explicit null attribution for a new non-agent conversation', async () => {await saveConvo(mockCtx, mockConversationData);@@ -507,7 +554,7 @@ describe('Conversation Operations', () => {expect(saved).toHaveProperty('initial_agent_id', null);});- it('refreshes both projects when a save moves a conversation between them', async () => {+ it('does not reassign membership or Project counts from a stale save payload', async () => {const projectA = await ChatProject.create({user: mockCtx.userId,name: 'Project A',@@ -528,7 +575,7 @@ describe('Conversation Operations', () => {endpoint: EModelEndpoint.openAI,chatProjectId: projectAId,});- // A stale tab re-submits with the new project id, moving the chat A -> B.+ // Only explicit Project assignment may move this existing conversation.await saveConvo(mockCtx, {conversationId,endpoint: EModelEndpoint.openAI,@@ -537,10 +584,10 @@ describe('Conversation Operations', () => {const refreshedA = await ChatProject.findById(projectA._id).lean<IChatProject>();const refreshedB = await ChatProject.findById(projectB._id).lean<IChatProject>();- expect(refreshedA?.conversationCount).toBe(0);- expect(refreshedA?.lastConversationId == null).toBe(true);- expect(refreshedB?.conversationCount).toBe(1);- expect(refreshedB?.lastConversationId).toBe(conversationId);+ expect(refreshedA?.conversationCount).toBe(1);+ expect(refreshedA?.lastConversationId).toBe(conversationId);+ expect(refreshedB?.conversationCount).toBe(0);+ expect(refreshedB?.lastConversationId == null).toBe(true);});it('bulkSaveConvos refreshes the project a conversation leaves', async () => {@@ -1054,6 +1101,16 @@ describe('Conversation Operations', () => {updatedAt: when,});}+ await ChatProject.updateOne(+ { _id: project._id },+ {+ $set: {+ conversationCount: 2,+ lastConversationAt: newerAt,+ lastConversationId: newer,+ },+ },+ );await saveConvo({ userId: 'user123' },diff --git a/packages/data-schemas/src/methods/conversation.ts b/packages/data-schemas/src/methods/conversation.tsindex f5235c1f16..1a14e6d825 100644--- a/packages/data-schemas/src/methods/conversation.ts+++ b/packages/data-schemas/src/methods/conversation.ts@@ -2352,38 +2352,24 @@ export function createConversationMethods(delete unsetFields.codeEnvironmentMode;delete unsetFields.codeWorkspaces;stripActorCheckpointFields(unsetFields);-- if (Object.prototype.hasOwnProperty.call(update, 'chatProjectId') && update.chatProjectId) {- const chatProjectId = typeof update.chatProjectId === 'string' ? update.chatProjectId : '';- let isValidChatProject = isValidObjectIdString(chatProjectId);-- if (isValidChatProject) {+ let chatProjectIdOnInsert: string | undefined;+ // Turn saves may seed a new conversation, never move or detach an existing one.+ const candidate = update.chatProjectId;+ delete update.chatProjectId;+ delete unsetFields.chatProjectId;+ if (metadata?.noUpsert !== true && typeof candidate === 'string') {+ if (isValidObjectIdString(candidate)) {const ChatProject = mongoose.models.ChatProject as Model<IChatProjectDocument>;const project = await ChatProject.exists({- _id: new mongoose.Types.ObjectId(chatProjectId),+ _id: new mongoose.Types.ObjectId(candidate),user: userId,});- isValidChatProject = project != null;- }-- if (!isValidChatProject) {- delete update.chatProjectId;- unsetFields.chatProjectId = 1;+ if (project != null) {+ chatProjectIdOnInsert = candidate;+ }}}- const mayChangeProjectMembership =- Object.prototype.hasOwnProperty.call(update, 'chatProjectId') ||- Object.prototype.hasOwnProperty.call(unsetFields, 'chatProjectId');- let previousChatProjectId: string | null = null;- if (mayChangeProjectMembership) {- const existing = await Conversation.findOne(- { conversationId, user: userId },- 'chatProjectId',- ).lean<{ chatProjectId?: string | null } | null>();- previousChatProjectId = existing?.chatProjectId ?? null;- }-if (newConversationId) {update.conversationId = newConversationId;}@@ -2494,6 +2480,7 @@ export function createConversationMethods(initial_agent_id: initialAgentId,...decisionOnInsert,...retentionOnInsert,+ ...(chatProjectIdOnInsert ? { chatProjectId: chatProjectIdOnInsert } : {}),...(createdAtForInsert ? { createdAt: createdAtForInsert } : {}),};return operation;@@ -2687,24 +2674,12 @@ export function createConversationMethods(conversation.isTemporary = false;}- const newChatProjectId = conversation.chatProjectId ?? null;- const projectMembershipChanged = previousChatProjectId !== newChatProjectId;-/* The conversation and its reply stamp are durable by now, and the caller hands thisdocument to the client as the turn's conversation. Project statistics are maintenanceon a different collection: letting one of their failures reach the catch below wouldanswer a successful save with an error, dropping the stamp from the terminal event andpresenting a reply the user already watched arrive as unread on the next refresh. */try {- /**- * A chat that moved between projects (e.g. a stale tab re-submitting an- * older project id) must fully recompute the stats of the project it left;- * the incremental path only ever touches the project it now belongs to.- */- if (projectMembershipChanged && previousChatProjectId) {- await refreshChatProjectStatsForUser(mongoose, userId, previousChatProjectId);- }-if (conversation.chatProjectId) {const isRetentionVisibilityUpdate =typeof update.isTemporary === 'boolean' ||@@ -2722,14 +2697,8 @@ export function createConversationMethods(conversation.isTemporary === true ||(conversation.expiredAt != null &&new Date(conversation.expiredAt).getTime() <= Date.now());- /**- * A move into this project (projectMembershipChanged) also needs a full- * refresh: the incremental path only bumps the count for brand-new inserts,- * so a pre-existing chat joining the project would otherwise be uncounted.- */const isNewConversation = conversationResult.lastErrorObject?.updatedExisting === false;const shouldRefreshProjectStats =- projectMembershipChanged ||isNewConversation ||typeof update.isArchived === 'boolean' ||Object.prototype.hasOwnProperty.call(unsetFields, 'isArchived') ||@@ -2738,7 +2707,7 @@ export function createConversationMethods(if (shouldRefreshProjectStats) {await refreshChatProjectStatsForUser(mongoose, userId, conversation.chatProjectId);- } else {+ } else if (!preserveUpdatedAt) {await updateChatProjectLastConversationForUser(mongoose,userId,diff --git a/packages/data-schemas/src/methods/file.spec.ts b/packages/data-schemas/src/methods/file.spec.tsindex 47b32ef814..426984d2e1 100644--- a/packages/data-schemas/src/methods/file.spec.ts+++ b/packages/data-schemas/src/methods/file.spec.ts@@ -2,6 +2,7 @@ import mongoose from 'mongoose';import { v4 as uuidv4 } from 'uuid';import { MongoMemoryServer } from 'mongodb-memory-server';import { EToolResources, FileContext } from 'librechat-data-provider';+import type { IChatProject, IMongoFile } from '~/types';import { _resetStrictCache } from '~/models/plugins/tenantIsolation';import { runAsSystem } from '~/config/tenantContext';import { createFileMethods } from './file';@@ -120,6 +121,169 @@ describe('File Methods', () => {});});+ describe('getAvailableProjectFiles', () => {+ it('treats an empty tenant id as no tenant, matching project file reads', async () => {+ const userId = new mongoose.Types.ObjectId().toString();+ await File.create({+ user: userId,+ file_id: 'untenanted',+ filename: 'Untenanted.txt',+ filepath: '/uploads/untenanted',+ object: 'file',+ type: 'text/plain',+ bytes: 1,+ embedded: true,+ context: FileContext.message_attachment,+ });+ const result = await fileMethods.getAvailableProjectFiles({+ userId,+ tenantId: '',+ excludedFileIds: [],+ limit: 10,+ });+ expect(result.files.map((file) => file.file_id)).toEqual(['untenanted']);+ });++ it('paginates only eligible owner files with stable cursors and literal search', async () => {+ const userId = new mongoose.Types.ObjectId().toString();+ const now = new Date('2026-01-01T00:00:00.000Z');+ const base = {+ user: userId,+ tenantId: 'tenant-a',+ filename: 'Report excluded.txt',+ filepath: '/uploads/report',+ object: 'file',+ type: 'text/plain',+ bytes: 1,+ usage: 0,+ embedded: true,+ context: FileContext.message_attachment,+ text: 'secret',+ storageKey: 'internal-storage-key',+ };+ await File.create([+ { ...base, file_id: 'report-1', filename: 'Report [literal].txt' },+ { ...base, file_id: 'report-2', filename: 'Report two.txt' },+ {+ ...base,+ file_id: 'expired',+ expiredAt: new Date('2025-12-31T23:59:59.000Z'),+ },+ { ...base, file_id: 'foreign-tenant', tenantId: 'tenant-b' },+ { ...base, file_id: 'foreign-owner', user: new mongoose.Types.ObjectId().toString() },+ { ...base, file_id: 'agent-knowledge', context: FileContext.agents },+ { ...base, file_id: 'not-indexed', embedded: false },+ { ...base, file_id: 'attached' },+ ]);++ const first = await fileMethods.getAvailableProjectFiles({+ userId,+ tenantId: 'tenant-a',+ excludedFileIds: ['attached'],+ limit: 1,+ search: 'report',+ now,+ });+ await File.updateOne(+ { file_id: first.files[0].file_id },+ { $set: { filename: `Report ${'renamed'.repeat(100)}` } },+ );+ const second = await fileMethods.getAvailableProjectFiles({+ userId,+ tenantId: 'tenant-a',+ excludedFileIds: ['attached'],+ limit: 1,+ search: 'report',+ cursor: first.nextCursor,+ now,+ });++ expect(first.files).toHaveLength(1);+ expect(second.files).toHaveLength(1);+ expect(first.files[0].file_id).toBe('report-2');+ expect(second.files[0].file_id).toBe('report-1');+ expect(first.nextCursor).toEqual(expect.any(String));+ expect(second.nextCursor).toBeNull();+ expect(first.files[0]).not.toHaveProperty('text');+ expect(second.files[0]).not.toHaveProperty('storageKey');+ /** The picker's rows reach `@librechat/api` and the client, so the identifiers must+ * already be plain strings rather than driver objects. */+ expect(first.files[0]).toMatchObject({ _id: expect.any(String), user: userId });+ const literalMatch = await fileMethods.getAvailableProjectFiles({+ userId,+ tenantId: 'tenant-a',+ search: '[literal]',+ now,+ });+ expect(literalMatch.files.map((file) => file.file_id)).toEqual(['report-1']);+ });++ it.each([0, 51, 1.5])('rejects an unbounded page size: %p', async (limit) => {+ await expect(+ fileMethods.getAvailableProjectFiles({+ userId: new mongoose.Types.ObjectId().toString(),+ tenantId: 'tenant-a',+ limit,+ }),+ ).rejects.toThrow('Invalid project file limit');+ });+ });++ describe('getProjectFiles', () => {+ it('enforces owner scope and only includes content when requested', async () => {+ const userId = new mongoose.Types.ObjectId().toString();+ await File.create([+ {+ file_id: 'project-owned',+ user: userId,+ tenantId: 'tenant-a',+ embedded: true,+ context: FileContext.message_attachment,+ filename: 'owned.txt',+ filepath: '/uploads/owned.txt',+ type: 'text/plain',+ bytes: 1,+ text: 'private project content',+ },+ {+ file_id: 'project-foreign',+ user: new mongoose.Types.ObjectId().toString(),+ tenantId: 'tenant-a',+ embedded: true,+ context: FileContext.message_attachment,+ filename: 'foreign.txt',+ filepath: '/uploads/foreign.txt',+ type: 'text/plain',+ bytes: 1,+ text: 'must not leak',+ },+ ]);++ const metadata = await fileMethods.getProjectFiles({+ fileIds: ['project-owned', 'project-foreign'],+ userId,+ tenantId: 'tenant-a',+ });+ expect(metadata.map((file) => file.file_id)).toEqual(['project-owned']);+ expect(metadata[0]).toEqual(+ expect.objectContaining({+ user: userId,+ _id: expect.any(String),+ }),+ );+ expect(metadata[0]?.updatedAt).toBeInstanceOf(Date);+ expect(metadata[0]).not.toHaveProperty('text');++ const withContent = await fileMethods.getProjectFiles({+ fileIds: ['project-owned'],+ userId,+ tenantId: 'tenant-a',+ includeContent: true,+ });+ expect(withContent[0]?.text).toBe('private project content');+ });+ });+describe('claimCodeFile', () => {it('claims code output files independently per tenant', async () => {const userId = new mongoose.Types.ObjectId().toString();@@ -1522,6 +1686,37 @@ describe('File Methods', () => {expect(updated?.expiresAt).toBeUndefined();});+ /* `prepareImageURL` clears the upload TTL with nothing but the id on every+ * reuse of an image. Project resume compatibility fingerprints canonical+ * content by `updatedAt`, so that bookkeeping must not read as a new+ * version while a real field write still must. */+ it('clears the upload TTL without posing as a content write', async () => {+ const fileId = uuidv4();+ await fileMethods.createFile({+ file_id: fileId,+ user: new mongoose.Types.ObjectId(),+ filename: 'reused.png',+ filepath: '/uploads/reused.png',+ type: 'image/png',+ bytes: 100,+ });+ const stamp = new Date('2020-01-01T00:00:00.000Z');+ await File.updateOne(+ { file_id: fileId },+ { $set: { updatedAt: stamp } },+ {+ timestamps: false,+ },+ );++ const reused = await fileMethods.updateFile({ file_id: fileId });+ expect(reused?.expiresAt).toBeUndefined();+ expect(reused?.updatedAt).toEqual(stamp);++ const rewritten = await fileMethods.updateFile({ file_id: fileId, text: 'extracted' });+ expect(rewritten?.updatedAt).not.toEqual(stamp);+ });+/* The optional `extraFilter` enables conditional updates — used by* the deferred-preview render's `finalizePreview` to guard against* an older render of the same `file_id` overwriting a newer turn's@@ -1628,7 +1823,7 @@ describe('File Methods', () => {expect(updated2?.usage).toBe(6);});- it('should skip usage and TTL mutation when the owner filter does not match', async () => {+ it('scopes usage and hold consumption without advancing the content version', async () => {const fileId = uuidv4();const ownerId = new mongoose.Types.ObjectId();const otherUserId = new mongoose.Types.ObjectId();@@ -1643,6 +1838,11 @@ describe('File Methods', () => {bytes: 100,usage: 0,});+ const contentUpdatedAt = new Date('2020-01-01');+ await File.collection.updateOne(+ { file_id: fileId },+ { $set: { updatedAt: contentUpdatedAt } },+ );const denied = await fileMethods.updateFileUsage({file_id: fileId,@@ -1663,6 +1863,12 @@ describe('File Methods', () => {expect(allowed?.usage).toBe(1);expect(allowed?.temp_file_id).toBeUndefined();expect(allowed?.expiresAt).toBeUndefined();+ expect(allowed?.updatedAt).toEqual(contentUpdatedAt);+ const changedContent = await fileMethods.updateFile({+ file_id: fileId,+ text: 'Updated canonical file contents.',+ });+ expect(changedContent?.updatedAt?.getTime()).toBeGreaterThan(contentUpdatedAt.getTime());});});@@ -2051,6 +2257,86 @@ describe('File Methods', () => {});});+ describe('project reference cleanup on delete', () => {+ async function seed() {+ const userId = new mongoose.Types.ObjectId();+ const ChatProject = mongoose.models.ChatProject as mongoose.Model<IChatProject>;+ const ids = [uuidv4(), uuidv4()];+ for (const fileId of ids) {+ await fileMethods.createFile({+ file_id: fileId,+ user: userId,+ filename: `${fileId}.txt`,+ filepath: `/uploads/${fileId}.txt`,+ type: 'text/plain',+ bytes: 1,+ });+ }+ const project = await ChatProject.create({+ user: userId.toString(),+ name: 'P',+ file_ids: [...ids, 'other'],+ contextRevision: 4,+ });+ const untouched = await ChatProject.create({+ user: new mongoose.Types.ObjectId().toString(),+ name: 'Q',+ file_ids: [ids[0]],+ contextRevision: 1,+ });+ return { ids, project, untouched, ChatProject };+ }++ it('pulls a deleted file from the owner projects and bumps the revision', async () => {+ const { ids, project, untouched, ChatProject } = await seed();+ await fileMethods.deleteFile(ids[0]);+ const after = await ChatProject.findById(project._id).lean();+ expect(after?.file_ids).toEqual([ids[1], 'other']);+ expect(after?.contextRevision).toBe(5);+ const other = await ChatProject.findById(untouched._id).lean();+ expect(other?.file_ids).toEqual([ids[0]]);+ expect(other?.contextRevision).toBe(1);+ });++ it('pulls every id removed by deleteFiles', async () => {+ const { ids, project, ChatProject } = await seed();+ await fileMethods.deleteFiles(ids);+ const after = await ChatProject.findById(project._id).lean();+ expect(after?.file_ids).toEqual(['other']);+ expect(after?.contextRevision).toBe(5);+ });++ it('pulls a file removed through deleteFileByFilter', async () => {+ const { ids, project, ChatProject } = await seed();+ await fileMethods.deleteFileByFilter({ file_id: ids[1] });+ const after = await ChatProject.findById(project._id).lean();+ expect(after?.file_ids).toEqual([ids[0], 'other']);+ });++ it('clears the user projects on a user-wide delete without reading the files', async () => {+ const { project, untouched, ChatProject } = await seed();+ const File = mongoose.models.File as mongoose.Model<IMongoFile>;+ const findSpy = jest.spyOn(File, 'find');+ await fileMethods.deleteFiles([], project.user);+ expect(findSpy).not.toHaveBeenCalled();+ findSpy.mockRestore();+ const after = await ChatProject.findById(project._id).lean();+ expect(after?.file_ids).toEqual([]);+ expect(after?.contextRevision).toBe(5);+ expect((await ChatProject.findById(untouched._id).lean())?.file_ids).toHaveLength(1);+ });++ it('still reports a completed delete when the project cleanup fails', async () => {+ const { ids, ChatProject } = await seed();+ const spy = jest.spyOn(ChatProject, 'updateMany').mockImplementationOnce(() => {+ throw new Error('cleanup failed');+ });+ const deleted = await fileMethods.deleteFile(ids[0]);+ spy.mockRestore();+ expect(deleted?.file_id).toBe(ids[0]);+ });+ });+describe('deleteFiles', () => {it('should delete multiple files by file_ids', async () => {const userId = new mongoose.Types.ObjectId();@@ -2198,10 +2484,6 @@ describe('File Methods', () => {expect(file?.storageKey).toBe('r/eu-central-1/uploads/user123/file.txt');expect(file?.storageRegion).toBe('eu-central-1');});-- it('should handle empty updates array gracefully', async () => {- await expect(fileMethods.batchUpdateFiles([])).resolves.toBeUndefined();- });});describe('sweepOrphanedPreviews', () => {diff --git a/packages/data-schemas/src/methods/file.ts b/packages/data-schemas/src/methods/file.tsindex 156fd477ea..2c74b1c976 100644--- a/packages/data-schemas/src/methods/file.ts+++ b/packages/data-schemas/src/methods/file.ts@@ -1,3 +1,4 @@+import { Types } from 'mongoose';import { createHash } from 'crypto';import { EToolResources, FileContext, FileSources } from 'librechat-data-provider';import type { CodeEnvRef, TFile } from 'librechat-data-provider';@@ -11,9 +12,167 @@ import type {RunArtifactRunScope,PublishRunArtifactInput,} from '~/types/file';+import type { IChatProjectDocument } from '~/types';import { tenantSafeBulkWrite } from '~/utils/tenantBulkWrite';+import { escapeRegExp } from '~/utils/string';import logger from '../config/winston';+export const DEFAULT_AVAILABLE_PROJECT_FILES_LIMIT = 20;+export const MAX_AVAILABLE_PROJECT_FILES_LIMIT = 50;++/** Plain projection of a candidate file. The picker's response crosses into `@librechat/api`+ * and the client, so this names no Mongoose type: `_id` and `user` are already strings here. */+export type AvailableProjectFileRecord = {+ _id: string;+ file_id: string;+ filename: string;+ filepath: string;+ object: 'file';+ type: string;+ bytes: number;+ usage: number;+ embedded?: boolean;+ context?: string;+ user: string;+ tenantId?: string;+};++type AvailableProjectFileRecordSource = Pick<+ IMongoFile,+ | '_id'+ | 'file_id'+ | 'filename'+ | 'filepath'+ | 'object'+ | 'type'+ | 'bytes'+ | 'usage'+ | 'embedded'+ | 'context'+ | 'user'+ | 'tenantId'+>;++function normalizeAvailableProjectFileRecord(+ file: AvailableProjectFileRecordSource,+): AvailableProjectFileRecord {+ return {+ _id: file._id.toString(),+ file_id: file.file_id,+ filename: file.filename,+ filepath: file.filepath,+ object: file.object,+ type: file.type,+ bytes: file.bytes,+ usage: file.usage,+ ...(file.embedded !== undefined ? { embedded: file.embedded } : {}),+ ...(file.context !== undefined ? { context: file.context } : {}),+ user: file.user.toString(),+ ...(file.tenantId !== undefined ? { tenantId: file.tenantId } : {}),+ };+}++export type AvailableProjectFilesOptions = FileOwnerScope & {+ excludedFileIds?: string[];+ limit?: number;+ cursor?: string | null;+ search?: string;+ now?: Date;+};++export type AvailableProjectFilesResult = {+ files: AvailableProjectFileRecord[];+ nextCursor: string | null;+};++export type ProjectFileRecord = {+ _id: string;+ file_id: string;+ filename: string;+ filepath: string;+ object: 'file';+ type: string;+ bytes: number;+ usage: number;+ embedded?: boolean;+ context?: string;+ expiredAt?: Date | null;+ user: string;+ tenantId?: string;+ createdAt?: Date;+ updatedAt?: Date;+ previewRevision?: string;+ status?: 'pending' | 'ready' | 'failed';+ text?: string;+};++type ProjectFileRecordSource = Pick<+ IMongoFile,+ | '_id'+ | 'file_id'+ | 'filename'+ | 'filepath'+ | 'object'+ | 'type'+ | 'bytes'+ | 'usage'+ | 'embedded'+ | 'context'+ | 'expiredAt'+ | 'user'+ | 'tenantId'+ | 'createdAt'+ | 'updatedAt'+ | 'previewRevision'+ | 'status'+ | 'text'+>;++function normalizeProjectFileRecord(file: ProjectFileRecordSource): ProjectFileRecord {+ return {+ _id: file._id.toString(),+ file_id: file.file_id,+ filename: file.filename,+ filepath: file.filepath,+ object: file.object,+ type: file.type,+ bytes: file.bytes,+ usage: file.usage,+ ...(file.embedded !== undefined ? { embedded: file.embedded } : {}),+ ...(file.context !== undefined ? { context: file.context } : {}),+ ...(file.expiredAt !== undefined ? { expiredAt: file.expiredAt } : {}),+ user: file.user.toString(),+ ...(file.tenantId !== undefined ? { tenantId: file.tenantId } : {}),+ ...(file.createdAt !== undefined ? { createdAt: file.createdAt } : {}),+ ...(file.updatedAt !== undefined ? { updatedAt: file.updatedAt } : {}),+ ...(file.previewRevision !== undefined ? { previewRevision: file.previewRevision } : {}),+ ...(file.status !== undefined ? { status: file.status } : {}),+ ...(file.text !== undefined ? { text: file.text } : {}),+ };+}++export type ProjectFilesOptions = FileOwnerScope & {+ fileIds: string[];+ includeContent?: boolean;+};++export class InvalidAvailableProjectFilesCursorError extends Error {+ constructor() {+ super('Invalid project file cursor');+ this.name = 'InvalidAvailableProjectFilesCursorError';+ }+}++export function parseAvailableProjectFilesCursor(cursor?: string | null): string | null {+ if (cursor == null || cursor === '') {+ return null;+ }+ if (cursor.length !== 24 || !Types.ObjectId.isValid(cursor)) {+ throw new InvalidAvailableProjectFilesCursorError();+ }+ return cursor;+}+export type FileOwnerScope = {userId: string;tenantId?: string | null;@@ -136,6 +295,10 @@ export function createFileMethods(mongoose: typeof import('mongoose')): {selectFields?: Record<string, 0 | 1> | string | null,limit?: number | null,) => Promise<IMongoFile[] | null>;+ getProjectFiles: (options: ProjectFilesOptions) => Promise<ProjectFileRecord[]>;+ getAvailableProjectFiles: (+ options: AvailableProjectFilesOptions,+ ) => Promise<AvailableProjectFilesResult>;getExpiredFiles: (limit?: number, options?: ExpiredFileQueryOptions) => Promise<IMongoFile[]>;incrementFileDeletionAttempts: (file_id: string) => Promise<number>;deferExpiredFile: (file_id: string, deletionRetryAt: Date) => Promise<void>;@@ -386,6 +549,115 @@ export function createFileMethods(mongoose: typeof import('mongoose')): {}return await query.sort(sortOptions).lean<IMongoFile[]>();}+ async function getProjectFiles({+ fileIds,+ userId,+ tenantId,+ includeContent = false,+ }: ProjectFilesOptions): Promise<ProjectFileRecord[]> {+ const File = mongoose.models.File as Model<IMongoFile>;+ const query = File.find({+ file_id: { $in: fileIds },+ user: userId,+ embedded: true,+ context: FileContext.message_attachment,+ // Mongo's null predicate matches explicit null and legacy missing tenant fields.+ tenantId: tenantId != null && tenantId !== '' ? tenantId : null,+ });+ if (includeContent) {+ query.select({});+ } else {+ query.select({+ _id: 1,+ file_id: 1,+ filename: 1,+ filepath: 1,+ object: 1,+ type: 1,+ bytes: 1,+ usage: 1,+ embedded: 1,+ context: 1,+ expiredAt: 1,+ user: 1,+ tenantId: 1,+ createdAt: 1,+ updatedAt: 1,+ previewRevision: 1,+ status: 1,+ });+ }+ const files = (await query.lean<ProjectFileRecordSource[]>()) ?? [];+ return files.map(normalizeProjectFileRecord);+ }++ async function getAvailableProjectFiles({+ userId,+ tenantId,+ excludedFileIds = [],+ limit = DEFAULT_AVAILABLE_PROJECT_FILES_LIMIT,+ cursor,+ search,+ now = new Date(),+ }: AvailableProjectFilesOptions): Promise<AvailableProjectFilesResult> {+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_AVAILABLE_PROJECT_FILES_LIMIT) {+ throw new RangeError('Invalid project file limit');+ }++ const decodedCursor = parseAvailableProjectFilesCursor(cursor);+ const filters: FilterQuery<IMongoFile>[] = [+ {+ user: userId,+ tenantId: tenantId != null && tenantId !== '' ? tenantId : null,+ embedded: true,+ context: FileContext.message_attachment,+ $or: [{ expiredAt: null }, { expiredAt: { $gt: now } }],+ },+ ];+ if (excludedFileIds.length > 0) {+ filters[0].file_id = { $nin: excludedFileIds };+ }+ const normalizedSearch = search?.trim();++ if (normalizedSearch) {+ filters.push({+ filename: { $regex: escapeRegExp(normalizedSearch), $options: 'i' },+ });+ }+ if (decodedCursor) {+ filters.push({ _id: { $lt: new Types.ObjectId(decodedCursor) } });+ }++ const File = mongoose.models.File as Model<IMongoFile>;+ const files = await File.find(filters.length === 1 ? filters[0] : { $and: filters })+ .select({+ _id: 1,+ file_id: 1,+ filename: 1,+ filepath: 1,+ object: 1,+ type: 1,+ bytes: 1,+ usage: 1,+ embedded: 1,+ context: 1,+ user: 1,+ tenantId: 1,+ })+ .sort({ _id: -1 })+ .limit(limit + 1)+ .lean<AvailableProjectFileRecordSource[]>();++ let nextCursor: string | null = null;+ if (files.length > limit) {+ files.pop();+ const lastFile = files[files.length - 1];+ if (lastFile) {+ nextCursor = lastFile._id.toString();+ }+ }+ return { files: files.map(normalizeAvailableProjectFileRecord), nextCursor };+ }/*** Expired files the sweep may attempt right now, oldest deadline first.@@ -845,6 +1117,12 @@ export function createFileMethods(mongoose: typeof import('mongoose')): {* same `file_id` overwriting a newer turn's record on cross-turn* filename reuse.*+ * Content timestamps advance only when the caller actually writes a+ * field. Clearing the upload TTL alone is bookkeeping: image reuse+ * calls this with nothing but the id on every turn, and consumers that+ * fingerprint content by `updatedAt` (Project resume compatibility)+ * would otherwise read a new version and reject an approved turn.+ ** @param data - The data to update, must contain file_id* @param extraFilter - Optional extra equality filter merged into the query.* @returns A promise that resolves to the updated file document, or@@ -864,6 +1142,7 @@ export function createFileMethods(mongoose: typeof import('mongoose')): {const query: FilterQuery<IMongoFile> = extraFilter ? { file_id, ...extraFilter } : { file_id };return File.findOneAndUpdate(query, updateOperation, {new: true,+ timestamps: Object.keys(update).length > 0,}).lean<IMongoFile>();}@@ -964,11 +1243,59 @@ export function createFileMethods(mongoose: typeof import('mongoose')): {const query: FilterQuery<IMongoFile> = user? withOwnerScope({ file_id }, { userId: user, tenantId }): { file_id };+ /** Usage and temporary-upload cleanup are bookkeeping, not content writes. */return File.findOneAndUpdate(query, updateOperation, {new: true,+ timestamps: false,}).lean<IMongoFile>();}+ /**+ * Removes deleted file ids from the owner's Chat Projects so a project never+ * keeps a dangling reference, bumping the revision of every project it changes.+ */+ async function detachFilesFromProjects(+ files: Pick<IMongoFile, 'file_id' | 'user'>[],+ ): Promise<void> {+ const ChatProject = mongoose.models.ChatProject as Model<IChatProjectDocument> | undefined;+ if (!ChatProject || files.length === 0) {+ return;+ }+ const idsByUser = new Map<string, string[]>();+ for (const file of files) {+ const user = String(file.user);+ idsByUser.set(user, [...(idsByUser.get(user) ?? []), file.file_id]);+ }+ try {+ await Promise.all(+ [...idsByUser].map(([user, fileIds]) =>+ ChatProject.updateMany(+ { user, file_ids: { $in: fileIds } },+ { $pull: { file_ids: { $in: fileIds } }, $inc: { contextRevision: 1 } },+ ),+ ),+ );+ } catch (error) {+ logger.warn('[detachFilesFromProjects] Failed to detach deleted files from projects', error);+ }+ }++ /** Clears every project file reference of a user whose files were all deleted. */+ async function detachAllUserFilesFromProjects(user: string): Promise<void> {+ const ChatProject = mongoose.models.ChatProject as Model<IChatProjectDocument> | undefined;+ if (!ChatProject) {+ return;+ }+ try {+ await ChatProject.updateMany(+ { user, 'file_ids.0': { $exists: true } },+ { $set: { file_ids: [] }, $inc: { contextRevision: 1 } },+ );+ } catch (error) {+ logger.warn('[detachAllUserFilesFromProjects] Failed to detach deleted files', error);+ }+ }+/*** Deletes a file identified by file_id.* @param file_id - The unique identifier of the file to delete@@ -976,7 +1303,11 @@ export function createFileMethods(mongoose: typeof import('mongoose')): {*/async function deleteFile(file_id: string): Promise<IMongoFile | null> {const File = mongoose.models.File as Model<IMongoFile>;- return File.findOneAndDelete({ file_id }).lean<IMongoFile>();+ const deleted = await File.findOneAndDelete({ file_id }).lean<IMongoFile>();+ if (deleted) {+ await detachFilesFromProjects([deleted]);+ }+ return deleted;}/**@@ -986,7 +1317,11 @@ export function createFileMethods(mongoose: typeof import('mongoose')): {*/async function deleteFileByFilter(filter: FilterQuery<IMongoFile>): Promise<IMongoFile | null> {const File = mongoose.models.File as Model<IMongoFile>;- return File.findOneAndDelete(filter).lean<IMongoFile>();+ const deleted = await File.findOneAndDelete(filter).lean<IMongoFile>();+ if (deleted) {+ await detachFilesFromProjects([deleted]);+ }+ return deleted;}/**@@ -1000,11 +1335,18 @@ export function createFileMethods(mongoose: typeof import('mongoose')): {user?: string,): Promise<{ deletedCount?: number }> {const File = mongoose.models.File as Model<IMongoFile>;- let deleteQuery: FilterQuery<IMongoFile> = { file_id: { $in: file_ids } };if (user) {- deleteQuery = { user: user };+ const result = await File.deleteMany({ user });+ await detachAllUserFilesFromProjects(user);+ return result;}- return File.deleteMany(deleteQuery);+ const deleteQuery: FilterQuery<IMongoFile> = { file_id: { $in: file_ids } };+ const doomed = await File.find(deleteQuery)+ .select({ file_id: 1, user: 1 })+ .lean<IMongoFile[]>();+ const result = await File.deleteMany(deleteQuery);+ await detachFilesFromProjects(doomed);+ return result;}/**@@ -1037,7 +1379,7 @@ export function createFileMethods(mongoose: typeof import('mongoose')): {},}));- const result = await tenantSafeBulkWrite(File, bulkOperations);+ const result = await tenantSafeBulkWrite(File, bulkOperations, { timestamps: false });logger.info(`Updated ${result.modifiedCount} files with new S3 URLs`);}@@ -1212,6 +1554,8 @@ export function createFileMethods(mongoose: typeof import('mongoose')): {listRunArtifacts,findFileById,getFiles,+ getProjectFiles,+ getAvailableProjectFiles,getExpiredFiles,incrementFileDeletionAttempts,deferExpiredFile,diff --git a/packages/data-schemas/src/methods/index.ts b/packages/data-schemas/src/methods/index.tsindex 0a8238951a..a05d75f828 100644--- a/packages/data-schemas/src/methods/index.ts+++ b/packages/data-schemas/src/methods/index.ts@@ -1,3 +1,12 @@+import type {+ FileMethods,+ FileOwnerScope,+ AvailableProjectFileRecord,+ AvailableProjectFilesOptions,+ AvailableProjectFilesResult,+ ProjectFileRecord,+ ProjectFilesOptions,+} from './file';import type { RoleMethods, RoleDeps } from './role';import {createOpenIDRefreshFlightMethods,@@ -14,10 +23,10 @@ import {import { createSessionMethods, DEFAULT_REFRESH_TOKEN_EXPIRY, type SessionMethods } from './session';import { createPasskeyMethods, type PasskeyMethods } from './passkey';import { createUserMethods, DEFAULT_SESSION_EXPIRY, type UserMethods } from './user';-import { createFileMethods, type FileMethods, type FileOwnerScope } from './file';import { createTokenMethods, type TokenMethods } from './token';import { createRoleMethods, RoleConflictError } from './role';import { createKeyMethods, type KeyMethods } from './key';+import { createFileMethods } from './file';/* Memories */import { createMemoryMethods, type MemoryMethods } from './memory';/* Tool Favorites */@@ -518,6 +527,13 @@ export function createMethods(};}+export {+ InvalidAvailableProjectFilesCursorError,+ parseAvailableProjectFilesCursor,+ MAX_AVAILABLE_PROJECT_FILES_LIMIT,+ DEFAULT_AVAILABLE_PROJECT_FILES_LIMIT,+} from './file';+export type {UserMethods,PasskeyMethods,@@ -527,9 +543,14 @@ export type {OpenIDRefreshFlightMethods,RoleMethods,KeyMethods,+ MemoryMethods,FileMethods,FileOwnerScope,- MemoryMethods,+ AvailableProjectFileRecord,+ AvailableProjectFilesOptions,+ AvailableProjectFilesResult,+ ProjectFileRecord,+ ProjectFilesOptions,ToolFavoriteMethods,AgentCategoryMethods,AgentApiKeyMethods,diff --git a/packages/data-schemas/src/schema/chatProject.ts b/packages/data-schemas/src/schema/chatProject.tsindex 837a68b3e7..7c196f002d 100644--- a/packages/data-schemas/src/schema/chatProject.ts+++ b/packages/data-schemas/src/schema/chatProject.ts@@ -1,4 +1,8 @@import { Schema } from 'mongoose';+import {+ MAX_CHAT_PROJECT_DESCRIPTION_LENGTH_CEILING,+ MAX_CHAT_PROJECT_INSTRUCTIONS_LENGTH_CEILING,+} from 'librechat-data-provider';import type { IChatProjectDocument } from '~/types';const chatProjectSchema: Schema<IChatProjectDocument> = new Schema<IChatProjectDocument>(@@ -14,7 +18,21 @@ const chatProjectSchema: Schema<IChatProjectDocument> = new Schema<IChatProjectDtype: String,default: '',trim: true,- maxlength: 1000,+ maxlength: MAX_CHAT_PROJECT_DESCRIPTION_LENGTH_CEILING,+ },+ instructions: {+ type: String,+ default: '',+ maxlength: MAX_CHAT_PROJECT_INSTRUCTIONS_LENGTH_CEILING,+ },+ contextRevision: {+ type: Number,+ default: 0,+ min: 0,+ },+ file_ids: {+ type: [String],+ default: [],},user: {type: String,diff --git a/packages/data-schemas/src/schema/file.ts b/packages/data-schemas/src/schema/file.tsindex 5825ac6cb0..f8445ad9dc 100644--- a/packages/data-schemas/src/schema/file.ts+++ b/packages/data-schemas/src/schema/file.ts@@ -220,6 +220,10 @@ const file: Schema<IMongoFile> = new Schema();file.index({ expiredAt: 1 });+file.index(+ { user: 1, tenantId: 1, context: 1, _id: -1 },+ { name: 'project_file_picker', partialFilterExpression: { embedded: true } },+);file.index({ createdAt: 1, updatedAt: 1 });file.index({ filename: 1, conversationId: 1, context: 1, tenantId: 1 },diff --git a/packages/data-schemas/src/types/app.ts b/packages/data-schemas/src/types/app.tsindex 4d7a656cc2..32196ab952 100644--- a/packages/data-schemas/src/types/app.ts+++ b/packages/data-schemas/src/types/app.ts@@ -4,6 +4,7 @@ import type {TFileConfig,TAzureConfig,TCustomConfig,+ TChatProjectsConfig,TMemoryConfig,EModelEndpoint,TVertexAIConfig,@@ -79,6 +80,8 @@ export interface AppConfig {fileStrategies?: TCustomConfig['fileStrategies'];/** CloudFront CDN configuration */cloudfront?: CloudFrontConfig;+ /** Chat Projects limits resolved from the deployment configuration */+ projects?: TChatProjectsConfig;/** Registration configurations */registration?: TCustomConfig['registration'];/** Changing the registered email address */diff --git a/packages/data-schemas/src/types/chatProject.ts b/packages/data-schemas/src/types/chatProject.tsindex 8486ec6f2b..75bd043cbe 100644--- a/packages/data-schemas/src/types/chatProject.ts+++ b/packages/data-schemas/src/types/chatProject.ts@@ -4,6 +4,11 @@ export interface IChatProject {_id?: Types.ObjectId;name: string;description?: string;+ instructions?: string;+ contextRevision?: number;+ file_ids?: string[];+ hasInstructions?: boolean;+ fileCount?: number;user: string;conversationCount: number;lastConversationAt?: Date | null;