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
⚡ perf: Exclude Agent Version History From Default `getAgent` Reads (#16070)
Marco Beretta5f4a07f40bcc
diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.jsindex 451fcf83fc..fcf65b8c02 100644--- a/api/server/controllers/agents/client.js+++ b/api/server/controllers/agents/client.js@@ -226,7 +226,7 @@ const db = require('~/models');const loadAgent = (params) =>loadAgentFn(params, {- getAgent: db.getAgent,+ getAgent: db.getAgentWithVersionCount,getMCPServerTools,getAccessibleMCPServers,});diff --git a/api/server/controllers/agents/v1.js b/api/server/controllers/agents/v1.jsindex e34647cf2b..e975d86746 100644--- a/api/server/controllers/agents/v1.js+++ b/api/server/controllers/agents/v1.js@@ -1108,7 +1108,7 @@ const updateAgentHandler = async (req, res) => {includesToolsConfiguration ||includesToolOptionsConfiguration) {- existingAgent = await db.getAgent({ id });+ existingAgent = await db.getAgent({ id }, {});if (!existingAgent) {return res.status(404).json({ error: 'Agent not found' });}@@ -1237,7 +1237,7 @@ const updateAgentHandler = async (req, res) => {// Convert OCR to context in incoming updateDataconvertOcrToContextInPlace(updateData);- existingAgent ??= await db.getAgent({ id });+ existingAgent ??= await db.getAgent({ id }, {});if (!existingAgent) {return res.status(404).json({ error: 'Agent not found' });@@ -2066,7 +2066,7 @@ const revertAgentVersionHandler = async (req, res) => {return res.status(400).json({ error: 'version_index is required' });}- const existingAgent = await db.getAgent({ id });+ const existingAgent = await db.getAgent({ id }, {});if (!existingAgent) {return res.status(404).json({ error: 'Agent not found' });diff --git a/api/server/middleware/accessResources/canAccessAgentFromBody.js b/api/server/middleware/accessResources/canAccessAgentFromBody.jsindex 913f6c3521..6a2b9ef914 100644--- a/api/server/middleware/accessResources/canAccessAgentFromBody.js+++ b/api/server/middleware/accessResources/canAccessAgentFromBody.js@@ -13,7 +13,7 @@ const { checkPermission } = require('~/server/services/PermissionService');const { canAccessResource } = require('./canAccessResource');const db = require('~/models');-const { getRoleByName, getAgent } = db;+const { getRoleByName, getAgentWithVersionCount } = db;const resolveEnforcedAgentId = (req, endpoint) => {const modelSpecs = req.config?.modelSpecs;@@ -39,7 +39,7 @@ const resolveAgentIdFromBody = async (agentCustomId) => {if (isEphemeralAgentId(agentCustomId)) {return null;}- return getAgent({ id: agentCustomId });+ return getAgentWithVersionCount({ id: agentCustomId });};/**diff --git a/api/server/services/Endpoints/agents/addedConvo.js b/api/server/services/Endpoints/agents/addedConvo.jsindex 031e7d5823..4fed579568 100644--- a/api/server/services/Endpoints/agents/addedConvo.js+++ b/api/server/services/Endpoints/agents/addedConvo.js@@ -17,7 +17,7 @@ const db = require('~/models');const loadAddedAgent = (params) =>loadAddedAgentFn(params, {- getAgent: db.getAgent,+ getAgent: db.getAgentWithVersionCount,getMCPServerTools,getAccessibleMCPServers,});diff --git a/api/server/services/Endpoints/agents/build.js b/api/server/services/Endpoints/agents/build.jsindex 4c9a40a2ab..7c5ce99434 100644--- a/api/server/services/Endpoints/agents/build.js+++ b/api/server/services/Endpoints/agents/build.js@@ -7,7 +7,7 @@ const db = require('~/models');const loadAgent = (params) =>loadAgentFn(params, {- getAgent: db.getAgent,+ getAgent: db.getAgentWithVersionCount,getMCPServerTools,getAccessibleMCPServers,});diff --git a/e2e/specs/mock/scenarios/agent-version-projection.spec.ts b/e2e/specs/mock/scenarios/agent-version-projection.spec.tsnew file mode 100644index 0000000000..62d6c33f64--- /dev/null+++ b/e2e/specs/mock/scenarios/agent-version-projection.spec.ts@@ -0,0 +1,126 @@+import { expect, test } from '@playwright/test';+import type { AgentDetail } from '../agents.helpers';+import { cleanupAgent, openAgentBuilder, uniqueAgentName } from '../agents.helpers';+import { MOCK_ENDPOINTS, NEW_CHAT_PATH, getAccessToken, requestJson } from '../helpers';++type AgentVersion = {+ name?: string;+ description?: string | null;+ createdAt?: string;+ updatedAt?: string;+};++const createAgent = async (page: Parameters<typeof getAccessToken>[0], name: string) => {+ const token = await getAccessToken(page);+ return requestJson<AgentDetail>(page, {+ path: '/api/agents',+ token,+ method: 'POST',+ body: {+ name,+ description: 'Agent version projection acceptance fixture.',+ instructions: 'Keep this fixture deterministic.',+ provider: MOCK_ENDPOINTS[0].label,+ model: MOCK_ENDPOINTS[0].model,+ },+ });+};++test.describe('agent version projection', () => {+ test('editing an agent still offers its version history @scenario:editing-agent-offers-version-history', async ({+ page,+ }) => {+ test.setTimeout(90000);+ const agentName = uniqueAgentName('E2E Version History Agent');+ let agentId: string | undefined;++ try {+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ const created = await createAgent(page, agentName);+ agentId = created.id;+ const token = await getAccessToken(page);+ await requestJson<AgentDetail>(page, {+ path: `/api/agents/${encodeURIComponent(agentId)}`,+ token,+ method: 'PATCH',+ body: { description: 'A second saved version for history.' },+ });++ const form = await openAgentBuilder(page);+ await form.getByRole('combobox', { name: 'Agent', exact: true }).click();+ await page.getByRole('option', { name: agentName, exact: true }).click();+ await expect(form.getByLabel('Agent name')).toHaveValue(agentName);+ await form.getByRole('button', { name: 'Select Agent' }).click();+ await form.getByRole('button', { name: 'Version', exact: true }).click();++ await expect(page.getByRole('heading', { name: 'Version History' })).toBeVisible();+ await expect(page.getByRole('list', { name: 'Version History' })).toBeVisible();+ await expect(page.getByText(/2 versions?/)).toBeVisible();+ } finally {+ await cleanupAgent(page, agentId);+ }+ });++ test('a reverted agent version applies its saved configuration @scenario:reverted-agent-version-applies', async ({+ page,+ }) => {+ test.setTimeout(90000);+ const initialName = uniqueAgentName('E2E Revert Initial');+ const changedName = uniqueAgentName('E2E Revert Changed');+ let agentId: string | undefined;++ try {+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ const created = await createAgent(page, initialName);+ agentId = created.id;+ const token = await getAccessToken(page);+ await requestJson<AgentDetail>(page, {+ path: `/api/agents/${encodeURIComponent(agentId)}`,+ token,+ method: 'PATCH',+ body: { name: changedName },+ });+ const versions = await requestJson<AgentVersion[]>(page, {+ path: `/api/agents/${encodeURIComponent(agentId)}/versions`,+ token,+ });+ const initialIndex = versions.findIndex((version) => version.name === initialName);+ expect(initialIndex).toBeGreaterThanOrEqual(0);++ const reverted = await requestJson<AgentDetail>(page, {+ path: `/api/agents/${encodeURIComponent(agentId)}/revert`,+ token,+ method: 'POST',+ body: { version_index: initialIndex },+ });+ expect(reverted.name).toBe(initialName);++ const form = await openAgentBuilder(page);+ await form.getByRole('combobox', { name: 'Agent', exact: true }).click();+ await page.getByRole('option', { name: initialName, exact: true }).click();+ await expect(form.getByLabel('Agent name')).toHaveValue(initialName);+ } finally {+ await cleanupAgent(page, agentId);+ }+ });++ test('the agent list loads agents without transferring their history @scenario:agent-list-loads-without-history', async ({+ page,+ }) => {+ test.setTimeout(90000);+ const agentName = uniqueAgentName('E2E Agent List');+ let agentId: string | undefined;++ try {+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ const created = await createAgent(page, agentName);+ agentId = created.id;++ const form = await openAgentBuilder(page);+ await form.getByRole('combobox', { name: 'Agent', exact: true }).click();+ await expect(page.getByRole('option', { name: agentName, exact: true })).toBeVisible();+ } finally {+ await cleanupAgent(page, agentId);+ }+ });+});diff --git a/packages/api/src/agents/__tests__/load.spec.ts b/packages/api/src/agents/__tests__/load.spec.tsindex bb5559b87a..18d199ceda 100644--- a/packages/api/src/agents/__tests__/load.spec.ts+++ b/packages/api/src/agents/__tests__/load.spec.ts@@ -16,13 +16,14 @@ import { loadAgent } from '../load';let Agent: mongoose.Model<unknown>;let createAgent: ReturnType<typeof createMethods>['createAgent'];-let getAgent: ReturnType<typeof createMethods>['getAgent'];+let getAgentWithVersionCount: ReturnType<typeof createMethods>['getAgentWithVersionCount'];const mockGetMCPServerTools = jest.fn();const mockGetAccessibleMCPServers = jest.fn();const deps: LoadAgentDeps = {- getAgent: (searchParameter) => getAgent(searchParameter) as Promise<LibreChatAgent | null>,+ getAgent: (searchParameter) =>+ getAgentWithVersionCount(searchParameter) as Promise<LibreChatAgent | null>,getMCPServerTools: mockGetMCPServerTools,getAccessibleMCPServers: mockGetAccessibleMCPServers,};@@ -37,7 +38,7 @@ describe('loadAgent', () => {await mongoose.connect(mongoUri);const methods = createMethods(mongoose);createAgent = methods.createAgent;- getAgent = methods.getAgent;+ getAgentWithVersionCount = methods.getAgentWithVersionCount;}, 20000);afterAll(async () => {diff --git a/packages/api/src/agents/added.ts b/packages/api/src/agents/added.tsindex b08fe163d3..481c1c26f3 100644--- a/packages/api/src/agents/added.ts+++ b/packages/api/src/agents/added.ts@@ -55,7 +55,10 @@ function applyModelSpecSubagents(}export interface LoadAddedAgentDeps {- getAgent: (searchParameter: { id: string }) => Promise<Agent | null>;+ /** Resolves the agent without its `versions` history; `version` carries the count. */+ getAgent: (searchParameter: {+ id: string;+ }) => Promise<(Agent & { version?: number; versions?: { length: number } }) | null>;getMCPServerTools: (userId: string,serverName: string,@@ -99,9 +102,8 @@ export async function loadAddedAgent(return null;}- const agentRecord = agent as Record<string, unknown>;- const versions = agentRecord.versions as unknown[] | undefined;- agentRecord.version = versions ? versions.length : 0;+ const agentRecord = agent as Agent & { version?: number; versions?: { length: number } };+ agentRecord.version ??= agentRecord.versions?.length ?? 0;agent.id = appendAgentIdSuffix(agent.id, 1);return agent;}diff --git a/packages/api/src/agents/load.ts b/packages/api/src/agents/load.tsindex 569a9caba8..7ae16333b5 100644--- a/packages/api/src/agents/load.ts+++ b/packages/api/src/agents/load.ts@@ -31,7 +31,10 @@ const { mcp_all, mcp_delimiter } = Constants;type ModelParametersWithPromptPrefix = AgentModelParameters & { promptPrefix?: string | null };export interface LoadAgentDeps {- getAgent: (searchParameter: { id: string }) => Promise<Agent | null>;+ /** Resolves the agent without its `versions` history; `version` carries the count. */+ getAgent: (searchParameter: {+ id: string;+ }) => Promise<(Agent & { version?: number; versions?: { length: number } }) | null>;getMCPServerTools: (userId: string,serverName: string,@@ -242,8 +245,6 @@ export async function loadAgent(return null;}- // Set version count from versions array length- const agentWithVersion = agent as Agent & { versions?: unknown[]; version?: number };- agentWithVersion.version = agentWithVersion.versions ? agentWithVersion.versions.length : 0;+ agent.version ??= agent.versions?.length ?? 0;return agent;}diff --git a/packages/data-schemas/src/methods/agent.spec.ts b/packages/data-schemas/src/methods/agent.spec.tsindex 57facac58d..0fbe6b0e49 100644--- a/packages/data-schemas/src/methods/agent.spec.ts+++ b/packages/data-schemas/src/methods/agent.spec.ts@@ -2392,7 +2392,7 @@ describe('Agent Methods', () => {},);- const firstUpdate = await getAgent({ id: agentId });+ const firstUpdate = await getAgent({ id: agentId }, {});expect(firstUpdate!.description).toBe('Updated description');expect(firstUpdate!.tools).toContain('tool1');expect(firstUpdate!.tools).toContain('tool2');@@ -2405,7 +2405,7 @@ describe('Agent Methods', () => {},);- const secondUpdate = await getAgent({ id: agentId });+ const secondUpdate = await getAgent({ id: agentId }, {});expect(secondUpdate!.tools).toHaveLength(2);expect(secondUpdate!.tools).toContain('tool2');expect(secondUpdate!.tools).toContain('tool3');@@ -2419,7 +2419,7 @@ describe('Agent Methods', () => {},);- const thirdUpdate = await getAgent({ id: agentId });+ const thirdUpdate = await getAgent({ id: agentId }, {});const toolCount = thirdUpdate!.tools!.filter((t) => t === 'tool3').length;expect(toolCount).toBe(2);expect(thirdUpdate!.versions).toHaveLength(4);@@ -2489,14 +2489,14 @@ describe('Agent Methods', () => {},);- const complexAgent = await getAgent({ id: agentId });+ const complexAgent = await getAgent({ id: agentId }, {});expect(complexAgent!.versions).toHaveLength(3);expect(complexAgent!.model_parameters?.temperature).toBe(0.8);expect(complexAgent!.model_parameters?.max_tokens).toBe(1000);await updateAgent({ id: agentId }, { model_parameters: {} });- const emptyParamsAgent = await getAgent({ id: agentId });+ const emptyParamsAgent = await getAgent({ id: agentId }, {});expect(emptyParamsAgent!.versions).toHaveLength(4);expect(emptyParamsAgent!.model_parameters).toEqual({});});@@ -2524,7 +2524,7 @@ describe('Agent Methods', () => {expect(duplicateUpdate!.versions).toHaveLength(2); // No new version created- const agent = await getAgent({ id: testAgentId });+ const agent = await getAgent({ id: testAgentId }, {});expect(agent!.versions).toHaveLength(2);}});@@ -2546,7 +2546,7 @@ describe('Agent Methods', () => {* same shape `addAgentResourceFile` produces when it attaches a file. */await updateAgent({ id: agentId }, { $addToSet: { tools: 'file_search' } });- const afterAdd = await getAgent({ id: agentId });+ const afterAdd = await getAgent({ id: agentId }, {});expect(afterAdd!.tools).toEqual(['file_search']);expect(afterAdd!.versions).toHaveLength(2);expect((afterAdd!.versions![1] as VersionEntry).tools).toEqual([]);@@ -2558,7 +2558,7 @@ describe('Agent Methods', () => {expect(removed!.tools).toEqual([]);expect(removed!.versions).toHaveLength(2);- const reloaded = await getAgent({ id: agentId });+ const reloaded = await getAgent({ id: agentId }, {});expect(reloaded!.tools).toEqual([]);expect(reloaded!.versions).toHaveLength(2);});@@ -2594,7 +2594,7 @@ describe('Agent Methods', () => {/** The re-attach snapshots the current state, so the document now equals the newest* version and the next attach is judged a duplicate. */- const settled = await getAgent({ id: agentId });+ const settled = await getAgent({ id: agentId }, {});const newestVersion = settled!.versions![settled!.versions!.length - 1] as VersionEntry;expect(fileIdsOf(settled)).toEqual(['f1']);expect(newestVersion.tool_resources).toEqual(settled!.tool_resources);@@ -2634,7 +2634,7 @@ describe('Agent Methods', () => {/** The document now equals its newest version, so the snapshot is a duplicate and* only the operator can justify recording an entry. */- const settled = await getAgent({ id: agentId });+ const settled = await getAgent({ id: agentId }, {});const versionCount = settled!.versions!.length;/** Re-attaching an id the agent already holds makes `$addToSet` a Mongo no-op. An@@ -2645,7 +2645,7 @@ describe('Agent Methods', () => {file_id: 'f1',});- const after = await getAgent({ id: agentId });+ const after = await getAgent({ id: agentId }, {});expect(after!.versions).toHaveLength(versionCount);expect((after?.tool_resources as Record<string, { file_ids?: string[] }> | undefined)?.file_search@@ -2677,7 +2677,7 @@ describe('Agent Methods', () => {file_id: 'f1',});- const settled = await getAgent({ id: agentId });+ const settled = await getAgent({ id: agentId }, {});const versionCount = settled!.versions!.length;/** The no-op reading comes from a document fetched before the write, so a `$pull`@@ -2699,7 +2699,7 @@ describe('Agent Methods', () => {expect(suppressedUpdate.$addToSet).toBeUndefined();expect(suppressedUpdate.$push).toBeUndefined();expect(suppressedUpdate.$pull).toBeUndefined();- expect((await getAgent({ id: agentId }))!.versions).toHaveLength(versionCount);+ expect((await getAgent({ id: agentId }, {}))!.versions).toHaveLength(versionCount);});test('should record a version when a duplicate direct update carries an atomic operator', async () => {@@ -2726,7 +2726,7 @@ describe('Agent Methods', () => {expect(updated!.tools).toEqual(['appended_tool']);expect(updated!.versions).toHaveLength(3);- const reloaded = await getAgent({ id: agentId });+ const reloaded = await getAgent({ id: agentId }, {});expect(reloaded!.tools).toEqual(['appended_tool']);expect(reloaded!.versions).toHaveLength(3);});@@ -2774,7 +2774,7 @@ describe('Agent Methods', () => {{ avatar: { filepath: '/images/a.png', source: 'local' } },{ skipVersioning: true },);- const withAvatar = await getAgent({ id: agentId });+ const withAvatar = await getAgent({ id: agentId }, {});expect(withAvatar!.avatar).toBeTruthy();expect((withAvatar!.versions![1] as VersionEntry).avatar).toBeUndefined();@@ -2800,13 +2800,13 @@ describe('Agent Methods', () => {});await updateAgent({ id: agentId }, { name: 'Idempotent' });- const before = await getAgent({ id: agentId });+ const before = await getAgent({ id: agentId }, {});const duplicate = await updateAgent({ id: agentId }, { name: 'Idempotent' });/** The suppressed path reports the unchanged version count as `version`. */expect((duplicate as IAgent & { version?: number }).version).toBe(before!.versions!.length);- const after = await getAgent({ id: agentId });+ const after = await getAgent({ id: agentId }, {});expect(after!.name).toBe(before!.name);expect(after!.tools).toEqual(before!.tools);expect(after!.versions).toHaveLength(before!.versions!.length);@@ -3456,7 +3456,7 @@ describe('Agent Methods', () => {// Since we're updating back to the same model_parameters but with a different description,// it should create a new version- const agent = await getAgent({ id: agentId });+ const agent = await getAgent({ id: agentId }, {});expect(agent!.versions).toHaveLength(3);});@@ -3624,7 +3624,7 @@ describe('Agent Methods', () => {expect(repopulated?.versions).toHaveLength(3);// Verify all versions have correct support_contact- const finalAgent = await getAgent({ id: agentId });+ const finalAgent = await getAgent({ id: agentId }, {});expect(finalAgent!.versions![0]?.support_contact).toEqual({name: 'Support',email: '[email protected]',@@ -3674,7 +3674,7 @@ describe('Agent Methods', () => {},);- const finalAgent = await getAgent({ id: agentId });+ const finalAgent = await getAgent({ id: agentId }, {});// Verify version historyexpect(finalAgent!.versions).toHaveLength(3);@@ -3833,7 +3833,7 @@ describe('Agent Methods', () => {await updateAgent({ id: agentId }, { description: `Version ${i}` });}- const agent = await getAgent({ id: agentId });+ const agent = await getAgent({ id: agentId }, {});expect(agent!.versions).toHaveLength(21);expect(agent!.description).toBe('Version 19');});@@ -4859,7 +4859,7 @@ describe('Agent Methods', () => {await updateAgent({ id: agentId }, { agent_ids: ['agent3'] });- const finalAgent = await getAgent({ id: agentId });+ const finalAgent = await getAgent({ id: agentId }, {});expect(finalAgent!.versions).toHaveLength(3);expect(finalAgent!.versions![0]?.agent_ids).toEqual(['agent1']);diff --git a/packages/data-schemas/src/methods/agent.ts b/packages/data-schemas/src/methods/agent.tsindex e25aa52cc9..701a505658 100644--- a/packages/data-schemas/src/methods/agent.ts+++ b/packages/data-schemas/src/methods/agent.ts@@ -547,14 +547,19 @@ async function generateActionMetadataHash(return hashHex;}+export interface GetAgent {+ (searchParameter: FilterQuery<IAgent>): Promise<Omit<IAgent, 'versions'> | null>;+ (+ searchParameter: FilterQuery<IAgent>,+ projection: ProjectionType<IAgent>,+ ): Promise<IAgent | null>;+}+export function createAgentMethods(mongoose: typeof import('mongoose'),deps: AgentDeps,): {- getAgent: (- searchParameter: FilterQuery<IAgent>,- projection?: ProjectionType<IAgent>,- ) => Promise<IAgent | null>;+ getAgent: GetAgent;getAgentVersions: (searchParameter: FilterQuery<IAgent>) => Promise<IAgent['versions'] | null>;getAgentWithVersionCount: (searchParameter: FilterQuery<IAgent>,@@ -741,14 +746,16 @@ export function createAgentMethods(/*** Get an agent document based on the provided search parameter.+ * Without an explicit projection, the unbounded `versions` history is excluded;+ * pass `{}` (or a projection including `versions`) to read the full history.*/- async function getAgent(+ const getAgent: GetAgent = async (searchParameter: FilterQuery<IAgent>,- projection?: ProjectionType<IAgent>,- ): Promise<IAgent | null> {+ projection: ProjectionType<IAgent> = { versions: 0 },+ ): Promise<IAgent | null> => {const Agent = mongoose.models.Agent as Model<IAgent>;return await Agent.findOne(searchParameter, projection).lean<IAgent>();- }+ };/*** Get an agent's version history only, without the rest of the document.