Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🏷️ fix: Resolve endpoints.all Title Settings per Field and Fold Ollama Endpoint Names (#17316)
Danny Avila618922069746
diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.jsindex a691971a36..426e81012d 100644--- a/api/server/controllers/agents/client.js+++ b/api/server/controllers/agents/client.js@@ -18,6 +18,7 @@ const {getBalanceConfig,omitTitleOptions,getProviderConfig,+ resolveTitleConfig,formatMemoryContext,createCachedTokenCounter,applyContextToAgent,@@ -1646,8 +1647,8 @@ class AgentClient extends BaseClient {return undefined;}/** Per-endpoint opt-in via `activityLabel: true` in librechat.yaml,- * resolved the same way the title options are (endpoints.all > named- * endpoint > custom endpoint config). Custom endpoints live in the+ * resolved per field the same way the title options are (endpoints.all >+ * named endpoint > custom endpoint config). Custom endpoints live in the* `endpoints.custom` ARRAY, so their settings are only visible through* the matched entry — without it every custom endpoint reads as* disabled. */@@ -6150,34 +6151,29 @@ class AgentClient extends BaseClient {let titleProviderConfig = getProviderConfig({ provider: endpoint, appConfig });- /** @type {TEndpoint | undefined} */- const endpointConfig =- appConfig.endpoints?.all ??- appConfig.endpoints?.[endpoint] ??- titleProviderConfig.customEndpointConfig;- if (!endpointConfig) {- logger.debug(- `[api/server/controllers/agents/client.js #titleConvo] No endpoint config for "${endpoint}"`,- );- }+ const titleConfig = resolveTitleConfig({+ appConfig,+ endpoint,+ customEndpointConfig: titleProviderConfig.customEndpointConfig,+ });- if (endpointConfig?.titleConvo === false) {+ if (titleConfig.titleConvo === false) {logger.debug(`[api/server/controllers/agents/client.js #titleConvo] Title generation disabled for endpoint "${endpoint}"`,);return;}- if (endpointConfig?.titleEndpoint && endpointConfig.titleEndpoint !== endpoint) {+ if (titleConfig.titleEndpoint && titleConfig.titleEndpoint !== endpoint) {try {titleProviderConfig = getProviderConfig({- provider: endpointConfig.titleEndpoint,+ provider: titleConfig.titleEndpoint,appConfig,});- endpoint = endpointConfig.titleEndpoint;+ endpoint = titleConfig.titleEndpoint;} catch (error) {logger.warn(- `[api/server/controllers/agents/client.js #titleConvo] Error getting title endpoint config for "${endpointConfig.titleEndpoint}", falling back to default`,+ `[api/server/controllers/agents/client.js #titleConvo] Error getting title endpoint config for "${titleConfig.titleEndpoint}", falling back to default`,getSafeErrorMetadata(error),);// Fall back to original provider config@@ -6186,12 +6182,8 @@ class AgentClient extends BaseClient {}}- if (- endpointConfig &&- endpointConfig.titleModel &&- endpointConfig.titleModel !== Constants.CURRENT_MODEL- ) {- clientOptions.model = endpointConfig.titleModel;+ if (titleConfig.titleModel && titleConfig.titleModel !== Constants.CURRENT_MODEL) {+ clientOptions.model = titleConfig.titleModel;}const options = await titleProviderConfig.getOptions({@@ -6255,8 +6247,8 @@ class AgentClient extends BaseClient {if (provider === Providers.GOOGLE &&- (endpointConfig?.titleMethod === TitleMethod.FUNCTIONS ||- endpointConfig?.titleMethod === TitleMethod.STRUCTURED)+ (titleConfig.titleMethod === TitleMethod.FUNCTIONS ||+ titleConfig.titleMethod === TitleMethod.STRUCTURED)) {clientOptions.json = true;}@@ -6285,9 +6277,9 @@ class AgentClient extends BaseClient {clientOptions,inputText: text,contentParts: immediate ? [] : this.contentParts,- titleMethod: endpointConfig?.titleMethod,- titlePrompt: endpointConfig?.titlePrompt,- titlePromptTemplate: endpointConfig?.titlePromptTemplate,+ titleMethod: titleConfig.titleMethod,+ titlePrompt: titleConfig.titlePrompt,+ titlePromptTemplate: titleConfig.titlePromptTemplate,chainOptions: {runName: 'TitleRun',signal: abortController.signal,diff --git a/api/server/controllers/agents/client.test.js b/api/server/controllers/agents/client.test.jsindex 77e2f1b05f..7f5799e2f2 100644--- a/api/server/controllers/agents/client.test.js+++ b/api/server/controllers/agents/client.test.js@@ -4819,6 +4819,96 @@ describe('AgentClient - titleConvo', () => {expect(generateTitleCall.clientOptions.model).toBe('gpt-4o-mini');});+ it('keeps endpoint title settings when the all block sets only unrelated keys', async () => {+ mockReq.config = {+ endpoints: {+ all: { streamRate: 1, headers: { 'x-gateway': 'title' } },+ [EModelEndpoint.openAI]: {+ titleModel: 'gpt-3.5-turbo',+ titlePrompt: 'Endpoint title prompt',+ titleMethod: 'structured',+ },+ },+ };++ await client.titleConvo({ text: 'Test', abortController: new AbortController() });++ const generateTitleCall = mockRun.generateTitle.mock.calls[0][0];+ expect(generateTitleCall.clientOptions.model).toBe('gpt-3.5-turbo');+ expect(generateTitleCall).toEqual(+ expect.objectContaining({+ titleMethod: 'structured',+ titlePrompt: 'Endpoint title prompt',+ }),+ );+ });++ it('resolves each title field on its own across the all and endpoint blocks', async () => {+ mockReq.config = {+ endpoints: {+ all: { titlePrompt: 'All config title prompt' },+ [EModelEndpoint.openAI]: {+ titleModel: 'gpt-3.5-turbo',+ titlePrompt: 'Endpoint title prompt',+ titleMethod: 'structured',+ },+ },+ };++ await client.titleConvo({ text: 'Test', abortController: new AbortController() });++ const generateTitleCall = mockRun.generateTitle.mock.calls[0][0];+ expect(generateTitleCall.clientOptions.model).toBe('gpt-3.5-turbo');+ expect(generateTitleCall).toEqual(+ expect.objectContaining({+ titleMethod: 'structured',+ titlePrompt: 'All config title prompt',+ }),+ );+ });++ it('skips titles when the endpoint disables them beside an unrelated all block', async () => {+ mockReq.config = {+ endpoints: {+ all: { streamRate: 1 },+ [EModelEndpoint.openAI]: { titleConvo: false, titleModel: 'gpt-3.5-turbo' },+ },+ };++ const result = await client.titleConvo({+ text: 'Test',+ abortController: new AbortController(),+ });++ expect(result).toBeUndefined();+ expect(mockRun.generateTitle).not.toHaveBeenCalled();+ });++ it('does not run the endpoint titleModel on a titleEndpoint the all block names', async () => {+ const originalApiKey = process.env.ANTHROPIC_API_KEY;+ process.env.ANTHROPIC_API_KEY = 'test-anthropic-key';+ mockReq.config = {+ endpoints: {+ all: { titleEndpoint: EModelEndpoint.anthropic },+ [EModelEndpoint.openAI]: { titleModel: 'gpt-3.5-turbo' },+ },+ };++ try {+ await client.titleConvo({ text: 'Test', abortController: new AbortController() });+ } finally {+ if (originalApiKey) {+ process.env.ANTHROPIC_API_KEY = originalApiKey;+ } else {+ delete process.env.ANTHROPIC_API_KEY;+ }+ }++ const generateTitleCall = mockRun.generateTitle.mock.calls[0][0];+ expect(generateTitleCall.provider).toBe(Providers.ANTHROPIC);+ expect(generateTitleCall.clientOptions.model).not.toBe('gpt-3.5-turbo');+ });+it('should use all config with titleEndpoint and verify provider switch', async () => {// Mock the API key for the titleEndpoint providerconst originalApiKey = process.env.ANTHROPIC_API_KEY;diff --git a/api/server/services/Endpoints/agents/initialize.spec.js b/api/server/services/Endpoints/agents/initialize.spec.jsindex 336b0ccab6..0b90e7aea8 100644--- a/api/server/services/Endpoints/agents/initialize.spec.js+++ b/api/server/services/Endpoints/agents/initialize.spec.js@@ -1142,6 +1142,73 @@ describe('initializeClient — processAgent ACL gate', () => {canCreateSkillSpy.mockRestore();}});++ describe('an agent saved under another spelling of a served endpoint', () => {+ const actualApi = jest.requireActual('@librechat/api');++ /** The effective config as served: custom endpoint `Ollama` from librechat.yaml, its+ * models under the served name `ollama`, and `allowedProviders` in served names. */+ const runAgent = async (provider, catalog = { ollama: ['llama3.2'] }) => {+ const req = makeReq();+ req.config = {+ endpoints: {+ agents: { allowedProviders: ['ollama'] },+ custom: [+ {+ name: 'Ollama',+ apiKey: 'ollama',+ baseURL: 'http://ollama.test:11434/v1',+ models: { default: ['llama3.2'] },+ },+ ],+ },+ };+ getModelsConfig.mockResolvedValueOnce(catalog);+ mockValidateAgentModel.mockImplementation(actualApi.validateAgentModel);+ mockInitializeAgent.mockImplementation(actualApi.initializeAgent);+ loadAgentTools.mockResolvedValue({ tools: [], toolContextMap: {}, toolDefinitions: [] });+ await initializeClient({+ req,+ res: {},+ signal: new AbortController().signal,+ endpointOption: {+ ...makeEndpointOption(),+ agent: Promise.resolve({+ id: PRIMARY_ID,+ name: 'Primary',+ provider,+ model: 'llama3.2',+ tools: [],+ }),+ model_parameters: { model: 'llama3.2' },+ },+ });+ return agentClientArgs.agent;+ };++ afterEach(() => {+ mockValidateAgentModel.mockReset();+ mockInitializeAgent.mockReset();+ loadAgentTools.mockReset();+ });++ it.each(['Ollama', 'OLLAMA'])(+ 'validates and runs an agent saved as %s on the served ollama endpoint',+ async (provider) => {+ const agent = await runAgent(provider);++ expect(agent.endpoint).toBe('ollama');+ expect(agent.model).toBe('llama3.2');+ expect(mockValidateAgentModel).toHaveBeenCalledTimes(1);+ },+ );++ it('still rejects a provider the served allowedProviders do not name', async () => {+ await expect(runAgent('Probe', { Probe: ['llama3.2'] })).rejects.toThrow(+ ErrorTypes.INVALID_AGENT_PROVIDER,+ );+ });+ });});describe('initializeClient — subagent loading', () => {diff --git a/librechat.example.yaml b/librechat.example.yamlindex 15215eb6e8..5207e790c2 100644--- a/librechat.example.yaml+++ b/librechat.example.yaml@@ -1100,6 +1100,14 @@ endpoints:# userId: '507f1f77bcf86cd799439011'# tenantId: 'tenant-id'+ # (optional) Title settings under `endpoints.all` apply to every endpoint one field at a+ # time: a field set here wins over the endpoint's own value, and a field left out keeps it.+ # `titleEndpoint` and `titleModel` are one choice, taken together from the first of `all`,+ # the endpoint's block, or its custom endpoint entry that sets either.+ # all:+ # titleConvo: true+ # titleMethod: completion+# (optional) Custom request headers for the built-in OpenAI / Google endpoints.# Forwarded on every request to the provider (or an AI gateway / reverse proxy# in front of it) while keeping provider-native request shaping intact. Valuesdiff --git a/packages/api/src/admin/config.changes.integration.spec.ts b/packages/api/src/admin/config.changes.integration.spec.tsindex 55b8e398b9..00a4acd6e0 100644--- a/packages/api/src/admin/config.changes.integration.spec.ts+++ b/packages/api/src/admin/config.changes.integration.spec.ts@@ -834,6 +834,200 @@ describe('POST …/changes: entries librechat.yaml owns', () => {});});+describe('POST …/changes: entry names the runtime folds together', () => {+ const CUSTOM = 'endpoints.custom';+ const ollama = (name: string, extra: Record<string, unknown> = {}) =>+ endpoint(name, { baseURL: 'https://ollama.example.com/v1', ...extra });++ /** Stores `Ollama` with a key through the API, returning the stored entry. */+ async function storeOllama(params: { principalType: string; principalId: string }) {+ const created = await send(+ {+ ops: [+ {+ op: 'upsertEntry',+ fieldPath: CUSTOM,+ entry: ollama('Ollama', { apiKey: 'sk-ollama-secret-0001' }),+ },+ { op: 'upsertEntry', fieldPath: CUSTOM, entry: endpoint('foo') },+ ],+ },+ params,+ );+ expect(created.status).toBe(200);+ const [entry] = (await storedDocument(params.principalId))!.overrides.endpoints.custom;+ expect(entry.apiKey.startsWith('v3:')).toBe(true);+ expect(entry.apiKeyPreview).toBe('...0001');+ return entry as { apiKey: string; apiKeyPreview: string };+ }++ it('upserts `ollama` onto a stored `Ollama`, keeping its key, instead of adding a duplicate', async () => {+ const params = nextParams();+ const stored = await storeOllama(params);++ const { status, body } = await send(+ {+ ops: [+ {+ op: 'upsertEntry',+ fieldPath: CUSTOM,+ entry: ollama('ollama', { modelDisplayLabel: 'Local' }),+ },+ ],+ },+ params,+ );++ expect(status).toBe(200);+ expect(body.applied.map((ref) => ref.key)).toEqual(['ollama']);+ const custom = (await storedDocument(params.principalId))!.overrides.endpoints.custom;+ expect(custom).toEqual([+ {+ ...ollama('ollama', { modelDisplayLabel: 'Local' }),+ apiKey: stored.apiKey,+ apiKeyPreview: '...0001',+ },+ endpoint('foo'),+ ]);+ expect(secrets.resolveCustomEndpointSecrets(custom[0]).apiKey).toBe('sk-ollama-secret-0001');+ });++ it('collapses a stored two-spelling entry on upsert, keeping the key the runtime used', async () => {+ const stored = await storeOllama(nextParams());+ const params = nextParams();+ await seedDocument(+ params.principalId,+ {+ endpoints: {+ custom: [+ ollama('Ollama', { apiKey: stored.apiKey, apiKeyPreview: stored.apiKeyPreview }),+ endpoint('foo'),+ { name: 'ollama', modelDisplayLabel: 'Old' },+ ],+ },+ },+ [],+ );++ const { status } = await send(+ {+ ops: [+ {+ op: 'upsertEntry',+ fieldPath: CUSTOM,+ entry: ollama('ollama', { modelDisplayLabel: 'New' }),+ },+ ],+ },+ params,+ );++ expect(status).toBe(200);+ expect((await storedDocument(params.principalId))!.overrides.endpoints.custom).toEqual([+ {+ ...ollama('ollama', { modelDisplayLabel: 'New' }),+ apiKey: stored.apiKey,+ apiKeyPreview: '...0001',+ },+ endpoint('foo'),+ ]);+ });++ it('removes a stored `Ollama` by removeEntry `ollama`', async () => {+ const params = nextParams();+ await storeOllama(params);++ const { status, body } = await send(+ { ops: [{ op: 'removeEntry', fieldPath: CUSTOM, key: 'ollama' }] },+ params,+ );++ expect(status).toBe(200);+ expect(body.written).toBe(true);+ expect(body.applied.map((ref) => ref.key)).toEqual(['ollama']);+ expect((await storedDocument(params.principalId))!.overrides).toEqual({+ endpoints: { custom: [endpoint('foo')] },+ });+ });++ it('refuses a rename onto another spelling of a stored entry as entry_exists', async () => {+ const params = nextParams();+ await storeOllama(params);+ const before = await storedDocument(params.principalId);++ const { status, body } = await send(+ { ops: [{ op: 'rename', fieldPath: CUSTOM, from: 'foo', to: 'ollama' }] },+ params,+ );++ expect(status).toBe(400);+ expect(body).toMatchObject({+ code: 'CONFIG_ENTRY_INVALID',+ reason: 'entry_exists',+ opIndex: 0,+ });+ expect(await storedDocument(params.principalId)).toEqual(before);+ });++ it('treats every spelling of a YAML entry as that entry', async () => {+ const deps = createDeps({+ getAppConfig: async () =>+ ({+ config: {+ ...YAML,+ endpoints: { custom: [...YAML.endpoints.custom, ollama('Ollama')] },+ },+ }) as unknown as AppConfig,+ });+ const params = nextParams();+ const created = await send(+ {+ ops: [+ {+ op: 'upsertEntry',+ fieldPath: CUSTOM,+ entry: { name: 'ollama', modelDisplayLabel: 'L' },+ },+ { op: 'upsertEntry', fieldPath: CUSTOM, entry: endpoint('own') },+ ],+ },+ params,+ deps,+ );+ expect(created.status).toBe(200);+ const before = await storedDocument(params.principalId);++ for (const op of [+ { op: 'rename', fieldPath: CUSTOM, from: 'ollama', to: 'other' },+ { op: 'rename', fieldPath: CUSTOM, from: 'own', to: 'OLLAMA' },+ ]) {+ const { status, body } = await send({ ops: [op] }, params, deps);+ expect(status).toBe(400);+ expect(body).toMatchObject({+ code: 'CONFIG_ENTRY_INVALID',+ reason: 'inherited_entry',+ opIndex: 0,+ });+ }+ expect(await storedDocument(params.principalId)).toEqual(before);+ });++ it('refuses two changes of a batch that name one entry in two spellings', async () => {+ const { status, body } = await send(+ {+ ops: [+ { op: 'upsertEntry', fieldPath: CUSTOM, entry: ollama('Ollama') },+ { op: 'removeEntry', fieldPath: CUSTOM, key: 'ollama' },+ ],+ },+ nextParams(),+ );++ expect(status).toBe(400);+ expect(body).toMatchObject({ code: 'DUPLICATE_FIELD_PATH', opIndex: 1 });+ });+});+describe('POST …/changes: skipped, not refused (owner decision #2)', () => {it('stores the rest of the batch and reports each skipped change or part with its reason', async () => {const params = nextParams();diff --git a/packages/api/src/admin/config.handler.spec.ts b/packages/api/src/admin/config.handler.spec.tsindex 33388cdf25..af274320ee 100644--- a/packages/api/src/admin/config.handler.spec.ts+++ b/packages/api/src/admin/config.handler.spec.ts@@ -2663,6 +2663,115 @@ describe('createAdminConfigHandlers', () => {expect(deps.writeConfigDocument).toHaveBeenCalledTimes(1);});+ it('rejects one write that names a custom endpoint twice in spellings the runtime folds', async () => {+ const { handlers, deps } = createHandlers();+ const req = mockReq({+ params: { principalType: 'role', principalId: 'admin' },+ body: {+ overrides: {+ endpoints: {+ custom: [+ { name: 'Ollama', baseURL: 'http://first:11434/v1' },+ { name: 'ollama', baseURL: 'http://second:11434/v1' },+ ],+ },+ },+ },+ });+ const res = mockRes();++ await handlers.upsertConfigOverrides(req, res);++ expect(res.statusCode).toBe(400);+ expect(res.body?.issues).toEqual([+ {+ path: 'endpoints.custom.0',+ segments: ['endpoints', 'custom', '0'],+ code: 'duplicate_merge_key',+ },+ ]);+ expect(deps.writeConfigDocument).not.toHaveBeenCalled();+ });++ it('accepts an override spelled `ollama` onto the YAML `Ollama` it merges into', async () => {+ const { handlers, deps } = createHandlers({+ getAppConfig: jest.fn().mockResolvedValue({+ config: {+ endpoints: {+ custom: [+ {+ name: 'Ollama',+ apiKey: 'ollama',+ baseURL: 'http://yaml-host:11434/v1',+ models: { default: ['llama3'] },+ },+ ],+ },+ },+ }),+ });+ const req = mockReq({+ params: { principalType: 'role', principalId: 'admin' },+ body: {+ overrides: {+ endpoints: { custom: [{ name: 'ollama', modelDisplayLabel: 'Local' }] },+ },+ },+ });+ const res = mockRes();++ await handlers.upsertConfigOverrides(req, res);++ expect(res.statusCode).toBe(201);+ expect(deps.writeConfigDocument).toHaveBeenCalledTimes(1);+ });++ it('keeps the key a stored two-spelling `Ollama` document applies when a write omits it', async () => {+ const { handlers, deps } = createHandlers({+ findConfigByPrincipal: jest.fn().mockResolvedValue({+ _id: 'c1',+ configVersion: 1,+ priority: 10,+ overrides: {+ endpoints: {+ custom: [+ {+ name: 'Ollama',+ baseURL: 'http://override-first:11434/v1',+ apiKey: 'v3:test:sk-ollama-first-key',+ apiKeyPreview: '...-key',+ },+ { name: 'ollama', modelDisplayLabel: 'legacy-second' },+ ],+ },+ },+ }),+ });+ const req = mockReq({+ params: { principalType: 'role', principalId: 'admin' },+ body: {+ overrides: {+ endpoints: {+ custom: [{ name: 'ollama', baseURL: 'http://override-first:11434/v1' }],+ },+ },+ },+ });+ const res = mockRes();++ await handlers.upsertConfigOverrides(req, res);++ expect(res.statusCode).toBe(200);+ expect(writtenField(deps, 'endpoints.custom')).toEqual([+ {+ name: 'ollama',+ baseURL: 'http://override-first:11434/v1',+ apiKey: 'v3:test:sk-ollama-first-key',+ apiKeyPreview: '...-key',+ },+ ]);+ });+it('rejects a field patch with an invalid value and writes no entry', async () => {const { handlers, deps } = createHandlers();const req = mockReq({diff --git a/packages/api/src/admin/config.ts b/packages/api/src/admin/config.tsindex 84b9e7f7e0..216c0bdd1a 100644--- a/packages/api/src/admin/config.ts+++ b/packages/api/src/admin/config.ts@@ -23,6 +23,8 @@ import {setConfigFields,applyConfigChange,getConfigEntryKey,+ getConfigEntryMatcher,+ getConfigEntryIdentity,unsetConfigPaths,getConfigRevision,isConfigEntryError,@@ -1181,7 +1183,8 @@ function prepareEntryChange(/*** What a change addresses, for refusing two changes of a batch that address the same thing: a- * path, or one entry of a collection (by its key; a rename by the key it starts from).+ * path, or one entry of a collection (by its key's identity, so `Ollama` and `ollama` are one+ * custom endpoint; a rename by the key it starts from).*/function getChangeIdentity(raw: Record<string, unknown>,@@ -1191,18 +1194,20 @@ function getChangeIdentity(if (!isEntryOp(op)) {return JSON.stringify(['path', segments]);}+ const toEntry = (key: unknown): string =>+ JSON.stringify([+ 'entry',+ segments,+ typeof key === 'string' ? getConfigEntryIdentity(segments, key) : null,+ ]);if (op === 'rename') {- return JSON.stringify(['entry', segments, raw.from]);+ return toEntry(raw.from);}if (op === 'removeEntry') {- return JSON.stringify(['entry', segments, raw.key]);+ return toEntry(raw.key);}const keyField = getConfigArrayMergeKey(segments);- return JSON.stringify([- 'entry',- segments,- keyField ? getConfigEntryKey(raw.entry, keyField) : null,- ]);+ return toEntry(keyField ? getConfigEntryKey(raw.entry, keyField) : null);}/**@@ -1328,13 +1333,17 @@ function expandChange(change: PreparedChange, overrides: unknown): ConfigChange[}}-/** Whether `librechat.yaml` itself defines entry `name` of the collection a change addresses. */+/**+ * Whether `librechat.yaml` itself defines entry `name` of the collection a change addresses:+ * an entry of a merged-by-key array by its identity, so `ollama` names the YAML `Ollama`.+ */function isYamlEntry(base: unknown, change: PreparedChange, name: string): boolean {const node = getAtPath(base, change.target.segments);const keyField = getConfigArrayMergeKey(change.target.segments);if (keyField) {return (- Array.isArray(node) && node.some((item) => isPlainRecord(item) && item[keyField] === name)+ Array.isArray(node) &&+ node.some(getConfigEntryMatcher(change.target.segments, keyField, name)));}return isPlainRecord(node) && Object.prototype.hasOwnProperty.call(node, name);diff --git a/packages/api/src/admin/meta.spec.ts b/packages/api/src/admin/meta.spec.tsindex 534270642d..35a05c5d2b 100644--- a/packages/api/src/admin/meta.spec.ts+++ b/packages/api/src/admin/meta.spec.ts@@ -15,6 +15,7 @@ import {PrincipalModel,configSchema,RerankerTypes,+ EModelEndpoint,SearchProviders,ScraperProviders,PERMISSION_SUB_KEYS,@@ -41,6 +42,7 @@ import { createRequestSanitizer, rejectUnsafeConfigKeys } from '~/middleware/sanimport { redactConfigSecrets, encryptConfigSecretFields } from './secrets';import { MCPServersRegistry } from '~/mcp/registry/MCPServersRegistry';import { createMCPPolicyResolver } from '~/mcp/registry/policy';+import { resolveTitleConfig } from '~/endpoints/config';import { createAppConfigService } from '~/app/service';import { createAdminConfigHandlers } from './config';import { ADMIN_CONFIG_FEATURES } from './meta';@@ -292,7 +294,17 @@ describe('meta rules equal the rules the server applies', () => {runtimeFields: [...RUNTIME_CONFIG_INTERFACE_FIELDS],permissionSubKeys: [...PERMISSION_SUB_KEYS],});- expect(meta.rules.titleResolution).toBe('block');+ });++ it('reports per-field title resolution exactly when titles resolve endpoints.all per field', () => {+ const { titleModel } = resolveTitleConfig({+ appConfig: {+ endpoints: { all: { streamRate: 1 }, openAI: { titleModel: 'x' } },+ } as Partial<AppConfig> as AppConfig,+ endpoint: EModelEndpoint.openAI,+ });+ expect(meta.rules.titleResolution).toBe(titleModel === 'x' ? 'field' : 'block');+ expect(meta.rules.titleResolution).toBe('field');});it('lists exactly the secret fields reads withhold, with their preview companions', () => {diff --git a/packages/api/src/admin/meta.ts b/packages/api/src/admin/meta.tsindex 5962af0109..7817cb6f5b 100644--- a/packages/api/src/admin/meta.ts+++ b/packages/api/src/admin/meta.ts@@ -58,7 +58,7 @@ export function buildAdminConfigMeta(limits: AdminConfigMeta['limits']): AdminCoruntimeFields: [...RUNTIME_CONFIG_INTERFACE_FIELDS],permissionSubKeys: [...PERMISSION_SUB_KEYS],},- titleResolution: 'block',+ titleResolution: 'field',},};}diff --git a/packages/api/src/admin/secrets.spec.ts b/packages/api/src/admin/secrets.spec.tsindex cd1b7a916d..f45d750323 100644--- a/packages/api/src/admin/secrets.spec.ts+++ b/packages/api/src/admin/secrets.spec.ts@@ -1029,6 +1029,50 @@ describe('Custom endpoint config secrets', () => {expect(decryptV3(spaced.apiKey)).toBe('sk-prod-spaced-key');});+ it('matches endpoint names the runtime folds together as one identity', () => {+ const existing = encryptConfigSecrets(+ endpointsWith([+ { name: 'Ollama', apiKey: 'sk-ollama-stored-key' },+ { name: 'OpenRouter', apiKey: 'sk-or-stored-value' },+ ]),+ );+ const next = encryptConfigSecrets(endpointsWith([{ name: 'ollama' }, { name: 'openrouter' }]));++ const preserved = preserveConfigSecrets(next, existing);+ const [ollama, openRouter] = preserved.endpoints.custom as Array<Record<string, string>>;++ expect(decryptV3(ollama.apiKey)).toBe('sk-ollama-stored-key');+ expect(ollama.apiKeyPreview).toBe('...-key');+ expect(openRouter.apiKey).toBeUndefined();+ });++ /** A document stored before names were folded may hold both spellings; the runtime merge+ * combines them in order, so an omitted key keeps the key that merge applies. */+ it.each([+ ['only the earlier item holds a key', [{ apiKey: 'sk-ollama-first-key' }, {}], 'first'],+ [+ 'both items hold a key',+ [{ apiKey: 'sk-ollama-first-key' }, { apiKey: 'sk-ollama-second-key' }],+ 'second',+ ],+ ])('keeps the combined key of two stored spellings when %s', (_case, keys, expected) => {+ const existing = encryptConfigSecrets(+ endpointsWith([+ { name: 'Ollama', baseURL: 'http://first/v1', ...keys[0] },+ { name: 'ollama', modelDisplayLabel: 'Second', ...keys[1] },+ ]),+ );++ const preserved = preserveConfigSecrets(+ encryptConfigSecrets(endpointsWith([{ name: 'ollama' }])),+ existing,+ );++ const [entry] = preserved.endpoints.custom as Array<Record<string, string>>;+ expect(decryptV3(entry.apiKey)).toBe(`sk-ollama-${expected}-key`);+ expect(entry.apiKeyPreview).toBe('...-key');+ });+it('does not preserve keys for duplicated endpoint identities', () => {const existing = encryptConfigSecrets(endpointsWith([diff --git a/packages/api/src/admin/secrets.ts b/packages/api/src/admin/secrets.tsindex bdc7ce4e26..5dc3c83629 100644--- a/packages/api/src/admin/secrets.ts+++ b/packages/api/src/admin/secrets.ts@@ -1,6 +1,12 @@import isPlainObject from 'lodash/isPlainObject';-import { encryptV3, decryptV3, logger } from '@librechat/data-schemas';import { envVarRegex, extractEnvVariable } from 'librechat-data-provider';+import {+ logger,+ encryptV3,+ decryptV3,+ foldConfigMergeKey,+ combineFoldedConfigItems,+} from '@librechat/data-schemas';import type { AdminConfigRules } from '@librechat/data-schemas';import { isUserProvided } from '~/utils/common';@@ -68,7 +74,7 @@ interface ArraySecretField {secretKey: string;/** Masked-preview companion on each item, always the sibling `<secretKey>Preview`. */previewKey: string;- /** Item field matched verbatim across writes for omit-to-keep round-trips. */+ /** Item field matched across writes for omit-to-keep round-trips, as the merge keys it. */identityKey: string;/** Reference values that must stay readable and never encrypt, e.g. `user_provided`, `${ENV_VAR}`. */isPassthroughValue: (value: string) => boolean;@@ -534,16 +540,18 @@ function getSecretArray(root: unknown, field: ArraySecretField, basePath = ''):}/**- * Exact-string entry identity for preserve matching. Deliberately untrimmed:- * the runtime config merge keys entries by their verbatim name, so `"Prod"`- * and `" Prod "` are distinct endpoints with distinct credentials.+ * Entry identity for preserve matching: the identity the runtime config merge keys entries+ * by (`foldConfigMergeKey`), so `Ollama` and `ollama` share one stored key. Deliberately+ * untrimmed: `"Prod"` and `" Prod "` are distinct endpoints with distinct credentials.*/function getEntryIdentity(entry: Record<string, unknown> | null,field: ArraySecretField,): string | undefined {const value = entry?.[field.identityKey];- return typeof value === 'string' && value !== '' ? value : undefined;+ return typeof value === 'string' && value !== ''+ ? foldConfigMergeKey(field.arrayPath, value)+ : undefined;}/**@@ -597,10 +605,20 @@ function applyArraySecretWrites(entries: unknown[], field: ArraySecretField): vo}}+/**+ * Stored entries as the runtime merge reads them: a document stored before names were folded+ * may name one entry in two spellings, which the merge combines (`combineFoldedConfigItems`),+ * so the secret an omitted key keeps is the one the runtime uses.+ */+function getStoredSecretEntries(existing: unknown, field: ArraySecretField): unknown[] | null {+ const entries = getSecretArray(existing, field);+ return entries && combineFoldedConfigItems(field.arrayPath, entries);+}+function preserveArraySecrets(result: unknown, existing: unknown, basePath: string): void {for (const field of ARRAY_SECRET_FIELDS) {const entries = getSecretArray(result, field, basePath);- const existingEntries = getSecretArray(existing, field);+ const existingEntries = getStoredSecretEntries(existing, field);if (!entries || !existingEntries) {continue;}diff --git a/packages/api/src/agents/__tests__/initialize.test.ts b/packages/api/src/agents/__tests__/initialize.test.tsindex b31fb565b2..1d3a2a6660 100644--- a/packages/api/src/agents/__tests__/initialize.test.ts+++ b/packages/api/src/agents/__tests__/initialize.test.ts@@ -466,6 +466,67 @@ describe('initializeAgent — execution context', () => {});});+describe('initializeAgent: allowed providers', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ /** The effective config serves `endpoints.agents.allowedProviders` in served names, so a+ * YAML `Ollama` arrives as `ollama`. The chat path's model check before this is covered in+ * `api/server/services/Endpoints/agents/initialize.spec.js`. */+ it.each(['ollama', 'Ollama', 'OLLAMA'])(+ 'sets up an agent saved with provider %s on the served ollama endpoint',+ async (provider) => {+ const { agent, req, res, loadTools, db } = createMocks({+ provider,+ overrideProvider: Providers.OPENAI,+ });++ const result = await initializeAgent(+ {+ req,+ res,+ agent,+ loadTools,+ endpointOption: { endpoint: EModelEndpoint.agents },+ allowedProviders: new Set(['ollama']),+ isInitialAgent: true,+ },+ db,+ );++ expect(mockGetProviderConfig).toHaveBeenCalledWith(+ expect.objectContaining({ provider: 'ollama' }),+ );+ const { getOptions } = mockGetProviderConfig.mock.results[0].value;+ expect(getOptions).toHaveBeenCalledWith(expect.objectContaining({ endpoint: 'ollama' }));+ expect(result.endpoint).toBe('ollama');+ },+ );++ it('rejects a provider the allowed list does not name', async () => {+ const { agent, req, res, loadTools, db } = createMocks({+ provider: 'OpenRouter',+ overrideProvider: Providers.OPENAI,+ });++ await expect(+ initializeAgent(+ {+ req,+ res,+ agent,+ loadTools,+ endpointOption: { endpoint: EModelEndpoint.agents },+ allowedProviders: new Set(['ollama']),+ isInitialAgent: true,+ },+ db,+ ),+ ).rejects.toThrow(ErrorTypes.INVALID_AGENT_PROVIDER);+ });+});+describe('initializeAgent: ChatProject context', () => {beforeEach(() => {jest.clearAllMocks();diff --git a/packages/api/src/agents/activityLabels/host.ts b/packages/api/src/agents/activityLabels/host.tsindex 3fdd3e42e6..a44d1f1b33 100644--- a/packages/api/src/agents/activityLabels/host.ts+++ b/packages/api/src/agents/activityLabels/host.ts@@ -175,14 +175,10 @@ export interface ResolvedReasoningLabelConfig {maxPerRun?: number;}-/**- * Reads the per-endpoint `activity*` settings, mirroring how titles resolve- * theirs: an `endpoints.all` block wins over the named endpoint, which wins- * over a custom endpoint's own config.- *//*** Reads ONE endpoint setting, global-then-named, rather than picking a whole- * config object.+ * config object — the same per-field resolution titles use+ * (`resolveTitleConfig`).** Selecting wholesale means any `endpoints.all` block — even one carrying* nothing but `headers` — shadows the named/custom endpoint entirely, so adiff --git a/packages/api/src/agents/initialize.ts b/packages/api/src/agents/initialize.tsindex 51a57bc6a8..727acd32d6 100644--- a/packages/api/src/agents/initialize.ts+++ b/packages/api/src/agents/initialize.ts@@ -14,6 +14,7 @@ import {hasActivePiiPatterns,replaceSpecialVars,providerEndpointMap,+ normalizeEndpointName,} from 'librechat-data-provider';import type {AgentToolResources,@@ -1366,6 +1367,16 @@ export async function initializeAgent(}}+ /**+ * An agent saved under another spelling of a folded endpoint name (`Ollama`) runs on the+ * endpoint the runtime serves (`ollama`). Folded once, before anything keys on it: the+ * `allowedProviders` check (served names, `normalizeEndpointReferences`), provider setup,+ * user key lookups and token configs all read the served name.+ */+ const servedProvider = normalizeEndpointName(agent.provider);+ if (servedProvider !== agent.provider) {+ agent.provider = servedProvider;+ }if (isAgentsEndpoint(endpointOption?.endpoint) &&allowedProviders.size > 0 &&diff --git a/packages/api/src/app/references.spec.ts b/packages/api/src/app/references.spec.tsnew file mode 100644index 0000000000..00b8ea9e7f--- /dev/null+++ b/packages/api/src/app/references.spec.ts@@ -0,0 +1,111 @@+import { EModelEndpoint } from 'librechat-data-provider';+import type { AppConfig } from '@librechat/data-schemas';+import { normalizeEndpointReferences } from './references';++const asConfig = (config: Record<string, unknown>): AppConfig => config as unknown as AppConfig;++describe('normalizeEndpointReferences', () => {+ it('folds and dedupes addedEndpoints, spec endpoints and allowedProviders', () => {+ const config = asConfig({+ modelSpecs: {+ enforce: false,+ list: [+ { name: 'local', label: 'Local', preset: { endpoint: 'Ollama', model: 'llama3' } },+ { name: 'gpt', label: 'GPT', preset: { endpoint: EModelEndpoint.openAI } },+ ],+ addedEndpoints: ['Ollama', EModelEndpoint.openAI, 'ollama', 'OLLAMA'],+ },+ endpoints: {+ [EModelEndpoint.agents]: { allowedProviders: ['Ollama', EModelEndpoint.openAI] },+ [EModelEndpoint.openAI]: { titleModel: 'gpt-4o-mini' },+ },+ });++ const normalized = normalizeEndpointReferences(config);++ expect(normalized.modelSpecs?.addedEndpoints).toEqual(['ollama', EModelEndpoint.openAI]);+ expect(normalized.modelSpecs?.list?.map((spec) => spec.preset?.endpoint)).toEqual([+ 'ollama',+ EModelEndpoint.openAI,+ ]);+ expect(normalized.modelSpecs?.list?.[0]?.preset).toEqual({+ endpoint: 'ollama',+ model: 'llama3',+ });+ expect(normalized.modelSpecs?.enforce).toBe(false);+ expect(normalized.endpoints?.agents?.allowedProviders).toEqual([+ 'ollama',+ EModelEndpoint.openAI,+ ]);+ expect(normalized.endpoints?.openAI).toBe(config.endpoints?.openAI);+ });++ it('leaves the input untouched', () => {+ const config = asConfig({+ modelSpecs: {+ addedEndpoints: ['Ollama'],+ list: [{ name: 'a', preset: { endpoint: 'Ollama' } }],+ },+ endpoints: { [EModelEndpoint.agents]: { allowedProviders: ['Ollama'] } },+ });+ const snapshot = JSON.parse(JSON.stringify(config));++ normalizeEndpointReferences(config);++ expect(config).toEqual(snapshot);+ });++ it('returns the same objects when every reference is already a served name', () => {+ const spec = { name: 'a', label: 'A', preset: { endpoint: 'ollama' } };+ const config = asConfig({+ modelSpecs: { list: [spec], addedEndpoints: ['ollama', 'Custom Gateway'] },+ endpoints: { [EModelEndpoint.agents]: { allowedProviders: [EModelEndpoint.openAI] } },+ });++ const normalized = normalizeEndpointReferences(config);++ expect(normalized).toBe(config);+ expect(normalized.modelSpecs?.list?.[0]).toBe(spec);+ });++ it('keeps unchanged parts by identity when only one reference changes', () => {+ const list = [{ name: 'a', label: 'A', preset: { endpoint: EModelEndpoint.openAI } }];+ const config = asConfig({+ modelSpecs: { list, addedEndpoints: ['Ollama'] },+ endpoints: { [EModelEndpoint.agents]: { allowedProviders: [EModelEndpoint.openAI] } },+ });++ const normalized = normalizeEndpointReferences(config);++ expect(normalized.modelSpecs?.list).toBe(list);+ expect(normalized.modelSpecs?.addedEndpoints).toEqual(['ollama']);+ expect(normalized.endpoints).toBe(config.endpoints);+ });++ it('does not add keys a config leaves out', () => {+ const config = asConfig({+ modelSpecs: { list: [{ name: 'a', preset: { endpoint: 'Ollama' } }] },+ });++ const normalized = normalizeEndpointReferences(config);++ expect(Object.keys(normalized.modelSpecs ?? {})).toEqual(['list']);+ expect(normalized).not.toHaveProperty('endpoints');+ });++ it('keeps other spellings of non-folded endpoint names verbatim', () => {+ const config = asConfig({+ modelSpecs: { addedEndpoints: ['OpenRouter', 'openrouter'] },+ endpoints: { [EModelEndpoint.agents]: { allowedProviders: ['OpenRouter'] } },+ });++ expect(normalizeEndpointReferences(config)).toBe(config);+ });++ it('accepts a config with no model specs or agents block', () => {+ const config = asConfig({ endpoints: { [EModelEndpoint.openAI]: {} } });++ expect(normalizeEndpointReferences(config)).toBe(config);+ expect(normalizeEndpointReferences(asConfig({}))).toEqual({});+ });+});diff --git a/packages/api/src/app/references.ts b/packages/api/src/app/references.tsnew file mode 100644index 0000000000..7e0e430aef--- /dev/null+++ b/packages/api/src/app/references.ts@@ -0,0 +1,90 @@+import { normalizeEndpointName } from 'librechat-data-provider';+import type { AppConfig } from '@librechat/data-schemas';++type ModelSpecs = NonNullable<AppConfig['modelSpecs']>;+type ModelSpecList = ModelSpecs['list'];++/** Folds each name the way the runtime serves it and drops repeats; the same array when unchanged. */+function normalizeEndpointNames(names: string[] | undefined): string[] | undefined {+ if (!names?.length) {+ return names;+ }+ const seen = new Set<string>();+ const normalized: string[] = [];+ let changed = false;+ for (const name of names) {+ const served = normalizeEndpointName(name);+ if (seen.has(served)) {+ changed = true;+ continue;+ }+ seen.add(served);+ normalized.push(served);+ changed ||= served !== name;+ }+ return changed ? normalized : names;+}++/** Folds each spec's `preset.endpoint`; the same list, and the same specs, when unchanged. */+function normalizeSpecEndpoints(list: ModelSpecList): ModelSpecList {+ if (!list?.length) {+ return list;+ }+ let changed = false;+ const normalized = list.map((spec) => {+ const endpoint = spec?.preset?.endpoint;+ if (typeof endpoint !== 'string') {+ return spec;+ }+ const served = normalizeEndpointName(endpoint);+ if (served === endpoint) {+ return spec;+ }+ changed = true;+ return { ...spec, preset: { ...spec.preset, endpoint: served } };+ });+ return changed ? normalized : list;+}++function normalizeModelSpecs(modelSpecs: AppConfig['modelSpecs']): AppConfig['modelSpecs'] {+ if (modelSpecs == null) {+ return modelSpecs;+ }+ const list = normalizeSpecEndpoints(modelSpecs.list);+ const addedEndpoints = normalizeEndpointNames(modelSpecs.addedEndpoints);+ if (list === modelSpecs.list && addedEndpoints === modelSpecs.addedEndpoints) {+ return modelSpecs;+ }+ return {+ ...modelSpecs,+ ...(list !== modelSpecs.list && { list }),+ ...(addedEndpoints !== modelSpecs.addedEndpoints && { addedEndpoints }),+ };+}++/**+ * Rewrites the endpoint names the effective config refers to into the names the runtime+ * serves (`normalizeEndpointName`, which folds `Ollama` to `ollama`), without repeats:+ * `modelSpecs.addedEndpoints`, each `modelSpecs.list[].preset.endpoint`, and+ * `endpoints.agents.allowedProviders`. Their consumers (the endpoint menu, agent provider+ * checks, the agent builder) compare them verbatim with served endpoint keys, so a YAML or+ * admin-written `Ollama` would otherwise match nothing.+ *+ * Returns the same config object when nothing changes, so cached configs keep their identity.+ */+export function normalizeEndpointReferences(config: AppConfig): AppConfig {+ const modelSpecs = normalizeModelSpecs(config.modelSpecs);+ const agents = config.endpoints?.agents;+ const allowedProviders = normalizeEndpointNames(agents?.allowedProviders);+ const agentsChanged = allowedProviders !== agents?.allowedProviders;+ if (modelSpecs === config.modelSpecs && !agentsChanged) {+ return config;+ }+ return {+ ...config,+ ...(modelSpecs !== config.modelSpecs && { modelSpecs }),+ ...(agentsChanged && {+ endpoints: { ...config.endpoints, agents: { ...agents, allowedProviders } },+ }),+ };+}diff --git a/packages/api/src/app/service.spec.ts b/packages/api/src/app/service.spec.tsindex 472147c0ab..e4e8bdc77c 100644--- a/packages/api/src/app/service.spec.ts+++ b/packages/api/src/app/service.spec.ts@@ -8,6 +8,7 @@ import {_resetOverrideStrictCache,getAppConfigOptionsFromUser,} from './service';+import { loadCustomEndpointsConfig } from '~/endpoints/custom/config';import { getProviderConfig } from '~/endpoints/config/providers';/** Extends AppConfig with mock fields used by merge behavior tests. */@@ -725,6 +726,91 @@ describe('createAppConfigService', () => {expect(config.modelSpecs?.list?.[0]?.preset?.endpoint).toBe('agents');});+ describe('endpoint names the runtime folds together', () => {+ function ollamaBase() {+ return AppService({+ config: {+ interface: { modelSelect: true },+ endpoints: {+ custom: [+ {+ name: 'Ollama',+ apiKey: 'ollama',+ baseURL: 'http://yaml-host:11434/v1',+ models: { default: ['llama3'] },+ modelDisplayLabel: 'Ollama (YAML)',+ },+ ],+ agents: { allowedProviders: ['Ollama', 'openAI'] },+ },+ modelSpecs: {+ list: [{ name: 'local', label: 'Local', preset: { endpoint: 'Ollama' } }],+ addedEndpoints: ['Ollama', 'agents', 'ollama'],+ },+ },+ });+ }++ it('serves YAML endpoint references under their served names', async () => {+ const deps = createDeps({+ loadBaseConfig: jest.fn().mockResolvedValue(await ollamaBase()),+ });+ const { getAppConfig } = createAppConfigService(deps);++ for (const config of [+ await getAppConfig({ baseOnly: true }),+ await getAppConfig({ role: 'USER' }),+ ]) {+ expect(config.modelSpecs?.addedEndpoints).toEqual(['ollama', 'agents']);+ expect(config.modelSpecs?.list?.[0]?.preset?.endpoint).toBe('ollama');+ expect(config.endpoints?.agents?.allowedProviders).toEqual(['ollama', 'openAI']);+ }+ });++ it('merges an override `ollama` into the YAML `Ollama` and serves it as one endpoint', async () => {+ const deps = createDeps({+ loadBaseConfig: jest.fn().mockResolvedValue(await ollamaBase()),+ getApplicableConfigs: jest.fn().mockResolvedValue([+ {+ priority: 10,+ isActive: true,+ overrides: {+ endpoints: {+ custom: [+ {+ name: 'ollama',+ baseURL: 'http://override:11434/v1',+ modelDisplayLabel: 'Ollama (override)',+ },+ ],+ agents: { allowedProviders: ['Ollama'] },+ },+ modelSpecs: {+ list: [{ name: 'override', label: 'Override', preset: { endpoint: 'OLLAMA' } }],+ addedEndpoints: ['Ollama'],+ },+ },+ },+ ]),+ });+ const { getAppConfig } = createAppConfigService(deps);++ const config = await getAppConfig({ role: 'USER' });++ expect(config.endpoints?.custom).toHaveLength(1);+ expect(config.endpoints?.custom?.[0]?.name).toBe('Ollama');+ const served = loadCustomEndpointsConfig(config.endpoints?.custom);+ expect(Object.keys(served ?? {})).toEqual(['ollama']);+ expect(served?.ollama?.modelDisplayLabel).toBe('Ollama (override)');+ const provider = getProviderConfig({ provider: 'ollama', appConfig: config });+ expect(provider.customEndpointConfig?.baseURL).toBe('http://override:11434/v1');+ expect(provider.customEndpointConfig?.apiKey).toBe('ollama');+ expect(config.endpoints?.agents?.allowedProviders).toEqual(['ollama']);+ expect(config.modelSpecs?.list?.[0]?.preset?.endpoint).toBe('ollama');+ expect(config.modelSpecs?.addedEndpoints).toEqual(['ollama']);+ });+ });+/*** Admin-panel specs arrive through DB override documents the base config* never saw, so materialization must also run on the merged result.diff --git a/packages/api/src/app/service.ts b/packages/api/src/app/service.tsindex 7503f989eb..55aaac7e0a 100644--- a/packages/api/src/app/service.ts+++ b/packages/api/src/app/service.ts@@ -18,6 +18,7 @@ import {import type { AppConfig, ConfigOverrideLayer } from '@librechat/data-schemas';import type { Types } from 'mongoose';import type { CustomConfigLoadMode } from './loader';+import { normalizeEndpointReferences } from './references';import { checkAppConfigTheme } from './theme';const BASE_CONFIG_KEY = '_BASE_';@@ -189,8 +190,6 @@ function checkOverrideTheme(baseConfig: AppConfig, merged: AppConfig): AppConfig/*** Materializes inferable model-spec fields (an omitted `preset.endpoint` for* agent specs) so every consumer of the effective config reads complete specs.- * Runs at both assembly points — YAML base load and DB-override merge — because- * override documents contribute specs the base config never saw.*/function materializeConfigModelSpecs(config: AppConfig): AppConfig {const modelSpecs = materializeModelSpecEndpoints(config.modelSpecs);@@ -200,6 +199,15 @@ function materializeConfigModelSpecs(config: AppConfig): AppConfig {return { ...config, modelSpecs };}+/**+ * Completes the effective config: inferred spec endpoints, and endpoint references in the+ * names the runtime serves. Runs at both assembly points — YAML base load and DB-override+ * merge — because override documents contribute specs and references the base never saw.+ */+function completeEffectiveConfig(config: AppConfig): AppConfig {+ return normalizeEndpointReferences(materializeConfigModelSpecs(config));+}+export const DEFAULT_OVERRIDE_CACHE_TTL = 60_000;// ── Types ────────────────────────────────────────────────────────────@@ -479,7 +487,7 @@ export function createAppConfigService(deps: AppConfigServiceDeps): {throw new Error('Failed to initialize app configuration through AppService.');}- const baseConfig = materializeConfigModelSpecs(loaded);+ const baseConfig = completeEffectiveConfig(loaded);if (generation !== baseGeneration) {return baseConfig;}@@ -662,7 +670,7 @@ export function createAppConfigService(deps: AppConfigServiceDeps): {merged = scopeCustomEndpoints(checkOverrideTheme(scopedBaseConfig,- materializeConfigModelSpecs(mergeConfigOverrides(scopedBaseConfig, configs)),+ completeEffectiveConfig(mergeConfigOverrides(scopedBaseConfig, configs)),),effectiveTenantId,hiddenEndpoints,diff --git a/packages/api/src/endpoints/config/providers.spec.ts b/packages/api/src/endpoints/config/providers.spec.tsindex ecd3bfa76a..a80fffcc49 100644--- a/packages/api/src/endpoints/config/providers.spec.ts+++ b/packages/api/src/endpoints/config/providers.spec.ts@@ -1,7 +1,12 @@import { Providers } from '@librechat/agents';import { EModelEndpoint } from 'librechat-data-provider';import type { AppConfig } from '@librechat/data-schemas';-import { getProviderConfig, providerConfigMap, resolveTitleTiming } from './providers';+import {+ getProviderConfig,+ providerConfigMap,+ resolveTitleConfig,+ resolveTitleTiming,+} from './providers';const buildAppConfig = (customEndpoints: Array<{ name: string; baseURL?: string; apiKey?: string; provider?: string }>,@@ -233,3 +238,136 @@ describe('resolveTitleTiming', () => {expect(resolveTitleTiming({ appConfig, endpoint: 'openrouter' })).toBe('final');});});++describe('resolveTitleConfig', () => {+ const withEndpoints = (endpoints: Record<string, unknown>): AppConfig =>+ ({ endpoints }) as unknown as AppConfig;++ const openAITitles = {+ titleConvo: true,+ titleModel: 'gpt-4o-mini',+ titleMethod: 'structured',+ titlePrompt: 'OpenAI prompt',+ titlePromptTemplate: 'OpenAI template: {convo}',+ } as const;++ it('returns no settings when nothing is configured', () => {+ expect(resolveTitleConfig({ endpoint: EModelEndpoint.openAI })).toEqual({});+ expect(+ resolveTitleConfig({ appConfig: {} as AppConfig, endpoint: EModelEndpoint.openAI }),+ ).toEqual({});+ });++ it('keeps the endpoint title settings when `all` sets only other keys', () => {+ const appConfig = withEndpoints({+ all: { streamRate: 1, headers: { 'x-gateway': 'a' }, activityLabel: true },+ [EModelEndpoint.openAI]: openAITitles,+ });++ expect(resolveTitleConfig({ appConfig, endpoint: EModelEndpoint.openAI })).toEqual(+ openAITitles,+ );+ });++ it('lets each `all` field win on its own, keeping the endpoint value for the rest', () => {+ const appConfig = withEndpoints({+ all: { titlePrompt: 'Global prompt', titleMethod: 'completion' },+ [EModelEndpoint.openAI]: openAITitles,+ });++ expect(resolveTitleConfig({ appConfig, endpoint: EModelEndpoint.openAI })).toEqual({+ ...openAITitles,+ titlePrompt: 'Global prompt',+ titleMethod: 'completion',+ });+ });++ it('takes titleEndpoint and titleModel together from the first layer that sets either', () => {+ const allSetsEndpoint = withEndpoints({+ all: { titleEndpoint: EModelEndpoint.anthropic },+ [EModelEndpoint.openAI]: openAITitles,+ });+ const allSetsModel = withEndpoints({+ all: { titleModel: 'claude-haiku' },+ [EModelEndpoint.openAI]: { titleEndpoint: EModelEndpoint.anthropic, titleModel: 'gpt-4o' },+ });++ expect(+ resolveTitleConfig({ appConfig: allSetsEndpoint, endpoint: EModelEndpoint.openAI }),+ ).toMatchObject({ titleEndpoint: EModelEndpoint.anthropic, titleModel: undefined });+ expect(+ resolveTitleConfig({ appConfig: allSetsModel, endpoint: EModelEndpoint.openAI }),+ ).toMatchObject({ titleEndpoint: undefined, titleModel: 'claude-haiku' });+ });++ it('treats an explicit current_model in `all` as setting the model choice', () => {+ const appConfig = withEndpoints({+ all: { titleModel: 'current_model' },+ [EModelEndpoint.openAI]: { titleEndpoint: EModelEndpoint.anthropic, titleModel: 'x' },+ });++ expect(resolveTitleConfig({ appConfig, endpoint: EModelEndpoint.openAI })).toMatchObject({+ titleEndpoint: undefined,+ titleModel: 'current_model',+ });+ });++ it('disables titles everywhere through `all.titleConvo: false`', () => {+ const appConfig = withEndpoints({+ all: { titleConvo: false },+ [EModelEndpoint.openAI]: openAITitles,+ });++ expect(resolveTitleConfig({ appConfig, endpoint: EModelEndpoint.openAI }).titleConvo).toBe(+ false,+ );+ });++ it('honors an endpoint `titleConvo: false` next to an unrelated `all` block', () => {+ const appConfig = withEndpoints({+ all: { streamRate: 1 },+ [EModelEndpoint.openAI]: { titleConvo: false },+ });++ expect(resolveTitleConfig({ appConfig, endpoint: EModelEndpoint.openAI }).titleConvo).toBe(+ false,+ );+ });++ it('falls back to the custom endpoint config, still behind `all`', () => {+ const appConfig = withEndpoints({+ all: { titlePrompt: 'Global prompt' },+ [EModelEndpoint.custom]: [+ {+ name: 'Gateway',+ baseURL: 'https://gateway.example/v1',+ apiKey: 'gateway-key',+ titleModel: 'gateway-small',+ titleMethod: 'completion',+ titlePrompt: 'Gateway prompt',+ },+ ],+ });+ const { customEndpointConfig } = getProviderConfig({ provider: 'Gateway', appConfig });++ expect(resolveTitleConfig({ appConfig, endpoint: 'Gateway', customEndpointConfig })).toEqual({+ titleModel: 'gateway-small',+ titleMethod: 'completion',+ titlePrompt: 'Global prompt',+ });+ });++ it('prefers the named endpoint block over the custom config field by field', () => {+ const appConfig = withEndpoints({+ [EModelEndpoint.openAI]: { titlePrompt: 'Named prompt' },+ });++ expect(+ resolveTitleConfig({+ appConfig,+ endpoint: EModelEndpoint.openAI,+ customEndpointConfig: { titlePrompt: 'Custom prompt', titleMethod: 'functions' },+ }),+ ).toEqual({ titlePrompt: 'Named prompt', titleMethod: 'functions' });+ });+});diff --git a/packages/api/src/endpoints/config/providers.ts b/packages/api/src/endpoints/config/providers.tsindex 9ab6239f00..972988c42e 100644--- a/packages/api/src/endpoints/config/providers.ts+++ b/packages/api/src/endpoints/config/providers.ts@@ -124,6 +124,53 @@ export function resolveTitleTiming({return 'immediate';}+/** The settings conversation title generation reads for one endpoint. */+export type TitleConfig = Pick<+ Partial<TEndpoint>,+ | 'titleConvo'+ | 'titleEndpoint'+ | 'titleModel'+ | 'titleMethod'+ | 'titlePrompt'+ | 'titlePromptTemplate'+>;++/**+ * Resolves an endpoint's title settings field by field: `endpoints.all` wins, then the named+ * endpoint block, then the custom endpoint's own config. An `all` block that sets only other+ * keys (`headers`, `streamRate`, activity labels) therefore leaves the endpoint's title+ * settings in effect. `titleEndpoint` and `titleModel` are one choice: both come from the+ * first layer that sets either, so a model named for one endpoint never runs on another.+ */+export function resolveTitleConfig({+ appConfig,+ endpoint,+ customEndpointConfig,+}: {+ appConfig?: AppConfig;+ endpoint: string;+ customEndpointConfig?: Partial<TEndpoint>;+}): TitleConfig {+ const endpoints = appConfig?.endpoints;+ const named = endpoints?.[endpoint as keyof NonNullable<typeof endpoints>] as+ | Partial<TEndpoint>+ | undefined;+ const layers = [endpoints?.all, named, customEndpointConfig].filter(+ (layer): layer is Partial<TEndpoint> => layer != null,+ );+ const pick = <K extends keyof TitleConfig>(field: K): TitleConfig[K] =>+ layers.find((layer) => layer[field] != null)?.[field];+ const routing = layers.find((layer) => layer.titleEndpoint != null || layer.titleModel != null);+ return {+ titleConvo: pick('titleConvo'),+ titleEndpoint: routing?.titleEndpoint,+ titleModel: routing?.titleModel,+ titleMethod: pick('titleMethod'),+ titlePrompt: pick('titlePrompt'),+ titlePromptTemplate: pick('titlePromptTemplate'),+ };+}+/*** Result from getProviderConfig*/diff --git a/packages/data-provider/specs/providers.spec.ts b/packages/data-provider/specs/providers.spec.tsindex b7b44d16be..504f278010 100644--- a/packages/data-provider/specs/providers.spec.ts+++ b/packages/data-provider/specs/providers.spec.ts@@ -91,4 +91,16 @@ describe('resolveModelCatalogKey', () => {expect(resolveModelCatalogKey(EModelEndpoint.google)).toBe(EModelEndpoint.google);expect(resolveModelCatalogKey('custom-provider')).toBe('custom-provider');});++ it.each(['Ollama', 'OLLAMA'])(+ 'reads the served ollama catalog for a provider saved as %s',+ (provider) => {+ expect(resolveModelCatalogKey(provider, { ollama: ['llama3.2'] })).toBe('ollama');+ },+ );++ it('keeps an exact catalog and other names case-sensitive', () => {+ expect(resolveModelCatalogKey('Ollama', { Ollama: ['a'], ollama: ['b'] })).toBe('Ollama');+ expect(resolveModelCatalogKey('OpenRouter', { openrouter: ['a'] })).toBe('OpenRouter');+ });});diff --git a/packages/data-provider/src/providers.ts b/packages/data-provider/src/providers.tsindex d0e5f718de..dbd8c44290 100644--- a/packages/data-provider/src/providers.ts+++ b/packages/data-provider/src/providers.ts@@ -1,4 +1,5 @@import { EModelEndpoint, Providers } from './schemas';+import { normalizeEndpointName } from './utils';/** Canonical provider identity used for branding across client and server. */export enum ProviderId {@@ -81,11 +82,15 @@ export function resolveProviderId(input?: string | null): ProviderId | null {return providerByNormalizedId[key] ?? providerAliases[key] ?? null;}-/** Resolves a runtime provider to its model catalog, using a native alias only when needed. */+/**+ * Resolves a runtime provider to its model catalog: its own catalog when one exists, else a+ * native alias, else the name the runtime serves it under (`normalizeEndpointName`), so an+ * agent saved as `Ollama` reads the `ollama` catalog.+ */export function resolveModelCatalogKey<T>(provider?: string | null,catalogs?: Partial<Record<string, T>>,): string {const key = provider ?? '';- return catalogs?.[key] != null ? key : (modelCatalogAliases[key] ?? key);+ return catalogs?.[key] != null ? key : (modelCatalogAliases[key] ?? normalizeEndpointName(key));}diff --git a/packages/data-schemas/src/app/changes.spec.ts b/packages/data-schemas/src/app/changes.spec.tsindex 57321d6fe0..b422500cdc 100644--- a/packages/data-schemas/src/app/changes.spec.ts+++ b/packages/data-schemas/src/app/changes.spec.ts@@ -435,6 +435,120 @@ describe('applyConfigChange: rename', () => {});});+describe('entry changes: keys match as the runtime merge folds them', () => {+ const stored = (custom: unknown[]): ConfigOverrideState =>+ deepFreeze(state({ endpoints: { custom } }));++ it('upserts `ollama` onto a stored `Ollama` in place, under the submitted name', () => {+ const before = stored([+ endpoint('a'),+ endpoint('Ollama', { apiKey: 'v3:cipher' }),+ endpoint('c'),+ ]);+ const entry = endpoint('ollama', { apiKey: 'v3:cipher', modelDisplayLabel: 'Local' });++ const next = applyConfigChange(before, { op: 'upsertEntry', segments: CUSTOM, entry });++ expect(next.overrides).toEqual({+ endpoints: { custom: [endpoint('a'), entry, endpoint('c')] },+ });+ expect(+ getConfigChangeWrittenPaths({ op: 'upsertEntry', segments: CUSTOM, entry }, next),+ ).toEqual([['endpoints', 'custom', '1']]);+ });++ it('replaces every stored spelling of the entry an upsert names, at the first one', () => {+ const before = stored([+ endpoint('Ollama', { apiKey: 'v3:cipher' }),+ endpoint('a'),+ endpoint('OLLAMA', { modelDisplayLabel: 'Old' }),+ ]);+ const entry = endpoint('ollama');++ expect(+ applyConfigChange(before, { op: 'upsertEntry', segments: CUSTOM, entry }).overrides,+ ).toEqual({ endpoints: { custom: [entry, endpoint('a')] } });+ });++ it('removes every stored spelling of the entry a removeEntry names', () => {+ const before = stored([endpoint('Ollama'), endpoint('a'), endpoint('OLLAMA')]);++ expect(+ applyConfigChange(before, { op: 'removeEntry', segments: CUSTOM, key: 'ollama' }).overrides,+ ).toEqual({ endpoints: { custom: [endpoint('a')] } });+ expect(+ applyConfigChange(stored([endpoint('Ollama')]), {+ op: 'removeEntry',+ segments: CUSTOM,+ key: 'ollama',+ }).overrides,+ ).toEqual({});+ });++ it('refuses a rename onto another spelling of a stored entry, and renames by any spelling', () => {+ const ollama = endpoint('Ollama', { apiKey: 'v3:cipher' });+ const before = stored([ollama, endpoint('foo')]);++ const taken = errorOf(() =>+ applyConfigChange(before, { op: 'rename', segments: CUSTOM, from: 'foo', to: 'ollama' }),+ );+ expect(isConfigEntryError(taken) && taken.reason).toBe('entry_exists');++ expect(+ applyConfigChange(before, { op: 'rename', segments: CUSTOM, from: 'ollama', to: 'local' })+ .overrides,+ ).toEqual({ endpoints: { custom: [{ ...ollama, name: 'local' }, endpoint('foo')] } });+ expect(+ applyConfigChange(before, { op: 'rename', segments: CUSTOM, from: 'Ollama', to: 'ollama' })+ .overrides,+ ).toEqual({ endpoints: { custom: [{ ...ollama, name: 'ollama' }, endpoint('foo')] } });+ });++ it('renames an entry stored in two spellings as the one entry the runtime merge combines', () => {+ const before = stored([+ endpoint('Ollama', { baseURL: 'https://first.example.com', apiKey: 'v3:cipher' }),+ endpoint('foo'),+ { name: 'ollama', modelDisplayLabel: 'Later' },+ ]);++ const next = applyConfigChange(before, {+ op: 'rename',+ segments: CUSTOM,+ from: 'ollama',+ to: 'local',+ });++ expect(next.overrides).toEqual({+ endpoints: {+ custom: [+ endpoint('local', {+ baseURL: 'https://first.example.com',+ apiKey: 'v3:cipher',+ modelDisplayLabel: 'Later',+ }),+ endpoint('foo'),+ ],+ },+ });+ });++ it('keeps every other entry name exact', () => {+ const before = stored([endpoint('Foo')]);++ expect(+ applyConfigChange(before, { op: 'upsertEntry', segments: CUSTOM, entry: endpoint('foo') })+ .overrides,+ ).toEqual({ endpoints: { custom: [endpoint('Foo'), endpoint('foo')] } });+ expect(applyConfigChange(before, { op: 'removeEntry', segments: CUSTOM, key: 'foo' })).toBe(+ before,+ );+ const missing = errorOf(() =>+ applyConfigChange(before, { op: 'rename', segments: CUSTOM, from: 'foo', to: 'bar' }),+ );+ expect(isConfigEntryError(missing) && missing.reason).toBe('entry_not_found');+ });+});+describe('getConfigChangeWrittenPaths', () => {it('names a field change by its path and an entry change by the entry it wrote, a removal by nothing', () => {const result = state({ endpoints: { custom: [endpoint('a'), endpoint('b')] } });diff --git a/packages/data-schemas/src/app/changes.ts b/packages/data-schemas/src/app/changes.tsindex 5a5353cfe0..e7d2575680 100644--- a/packages/data-schemas/src/app/changes.ts+++ b/packages/data-schemas/src/app/changes.ts@@ -12,8 +12,12 @@ import {pruneEmptyAncestors,getClearedTombstones,} from './paths';+import {+ getConfigEntryIdentity,+ getConfigArrayMergeKey,+ combineFoldedConfigEntries,+} from './resolution';import { setConfigFields, unsetConfigPaths, tombstoneConfigPaths } from './mutations';-import { getConfigArrayMergeKey } from './resolution';/*** Atomic batches of override changes.@@ -44,15 +48,18 @@ export type ConfigChange =| { op: 'tombstone'; segments: ConfigPathSegments }/*** Replaces the principal's own entry of a merged-by-key array whose key matches the entry's- * (every own entry with that key), or appends it. The array is created when missing.+ * (every own entry with that key), or appends it. The array is created when missing. Entry+ * keys of every entry change match by identity (`getConfigEntryMatcher`): `ollama` addresses+ * a stored `Ollama`.*/| { op: 'upsertEntry'; segments: ConfigPathSegments; entry: Record<string, unknown> }/** Removes the principal's own entries of a merged-by-key array that have this key. */| { op: 'removeEntry'; segments: ConfigPathSegments; key: string }/*** Renames one of the principal's own entries, moving everything stored on it (encrypted- * secrets included): an entry of a merged-by-key array gets a new key value in place, and a- * record key is moved with its value, keeping the record's key order.+ * secrets included): an entry of a merged-by-key array gets a new key value in place (one+ * stored in two spellings of its key is combined first, as the runtime merge combines it),+ * and a record key is moved with its value, keeping the record's key order.*/| { op: 'rename'; segments: ConfigPathSegments; from: string; to: string };@@ -182,8 +189,21 @@ function requireKeyField(segments: ConfigPathSegments): string {return keyField;}-function hasKey(item: unknown, keyField: string, key: string): boolean {- return isPlainRecord(item) && item[keyField] === key;+/**+ * A test for the entries of the merged-by-key array at `segments` that key `key` names. Keys+ * compare by identity (`getConfigEntryIdentity`), so `Ollama` and `ollama` address the one+ * custom endpoint the runtime merge makes of them.+ */+export function getConfigEntryMatcher(+ segments: ConfigPathSegments,+ keyField: string,+ key: string,+): (item: unknown) => boolean {+ const identity = getConfigEntryIdentity(segments, key);+ return (item) => {+ const itemKey = isPlainRecord(item) ? item[keyField] : undefined;+ return typeof itemKey === 'string' && getConfigEntryIdentity(segments, itemKey) === identity;+ };}/** The key of an entry written into a merged-by-key array. */@@ -219,7 +239,8 @@ function applyUpsertEntry(throw new ConfigEntryError([...segments], 'invalid_entry');}const items = readKeyedArray(state, segments);- const index = items.findIndex((item) => hasKey(item, keyField, key));+ const isEntry = getConfigEntryMatcher(segments, keyField, key);+ const index = items.findIndex(isEntry);const next =index === -1? [...items, entry]@@ -227,7 +248,7 @@ function applyUpsertEntry(if (position === index) {return [entry];}- return hasKey(item, keyField, key) ? [] : [item];+ return isEntry(item) ? [] : [item];});return isSameConfigValue(items, next) ? state : writeKeyedArray(state, segments, next);}@@ -239,7 +260,8 @@ function applyRemoveEntry(): ConfigOverrideState {const keyField = requireKeyField(segments);const items = readKeyedArray(state, segments);- const next = items.filter((item) => !hasKey(item, keyField, key));+ const isEntry = getConfigEntryMatcher(segments, keyField, key);+ const next = items.filter((item) => !isEntry(item));return next.length === items.length ? state : writeKeyedArray(state, segments, next);}@@ -251,16 +273,27 @@ function renameKeyedEntry(to: string,): ConfigOverrideState {const items = readKeyedArray(state, segments);- const index = items.findIndex((item) => hasKey(item, keyField, from));+ const isFrom = getConfigEntryMatcher(segments, keyField, from);+ const index = items.findIndex(isFrom);if (index === -1) {throw new ConfigEntryError([...segments], 'entry_not_found');}- if (items.some((item) => hasKey(item, keyField, to))) {+ const isTo = getConfigEntryMatcher(segments, keyField, to);+ if (items.some((item) => isTo(item) && !isFrom(item))) {throw new ConfigEntryError([...segments], 'entry_exists');}- const next = items.map((item) =>- hasKey(item, keyField, from) ? { ...(item as JsonRecord), [keyField]: to } : item,- );+ const renamed = (item: unknown): JsonRecord => ({ ...(item as JsonRecord), [keyField]: to });+ /** One entry stored in two spellings moves as the single entry the runtime merge combines. */+ const combined = combineFoldedConfigEntries(segments, items.filter(isFrom));+ const next = items.flatMap((item, position) => {+ if (!isFrom(item)) {+ return [item];+ }+ if (combined.length > 1) {+ return [renamed(item)];+ }+ return position === index ? [renamed(combined[0])] : [];+ });return writeKeyedArray(state, segments, next);}@@ -404,7 +437,7 @@ export function getConfigChangeWrittenPaths(const items = getAtPath(result.overrides, segments);const index =Array.isArray(items) && keyField && key- ? items.findIndex((item) => hasKey(item, keyField, key))+ ? items.findIndex(getConfigEntryMatcher(change.segments, keyField, key)): -1;return index === -1 ? [] : [[...segments, String(index)]];}@@ -429,7 +462,7 @@ function getStoredCounterpart(const key = keyField ? getConfigEntryKey(next, keyField) : undefined;if (keyField && key !== undefined) {counterpart = Array.isArray(counterpart)- ? counterpart.find((item) => hasKey(item, keyField, key))+ ? counterpart.find(getConfigEntryMatcher(segments.slice(0, index), keyField, key)): undefined;} else {counterpart = getAtPath(counterpart, [segment]);diff --git a/packages/data-schemas/src/app/resolution.spec.ts b/packages/data-schemas/src/app/resolution.spec.tsindex 071bcb660f..66b1538123 100644--- a/packages/data-schemas/src/app/resolution.spec.ts+++ b/packages/data-schemas/src/app/resolution.spec.ts@@ -6,6 +6,7 @@ import {import type { TCustomConfig, TWebSearchConfigInput } from 'librechat-data-provider';import type { AppConfig, IConfig } from '~/types';import {+ foldConfigMergeKey,isConfigRecordPath,getConfigMergeRules,mergeConfigOverrides,@@ -17,6 +18,7 @@ import {getConfigArrayMergeKey,getDottedSectionIssues,getConfigOverrideIssues,+ combineFoldedConfigItems,getIndexedMergeKeyIssues,} from './resolution';import { BASE_CONFIG_PRINCIPAL_ID } from '~/admin/capabilities';@@ -1808,6 +1810,250 @@ describe('getConfigOverrideIssues', () => {});});+describe('endpoints.custom: names the runtime folds together', () => {+ type CustomItem = Record<string, unknown>;+ const customOf = (config: AppConfig): CustomItem[] =>+ (config as unknown as { endpoints: { custom: CustomItem[] } }).endpoints.custom;+ const yamlOllama = {+ name: 'Ollama',+ apiKey: 'ollama',+ baseURL: 'http://yaml-host:11434/v1',+ models: { default: ['llama3'], fetch: true },+ modelDisplayLabel: 'Ollama (YAML)',+ };+ const base = { endpoints: { custom: [yamlOllama] } } as unknown as AppConfig;++ it('merges an override `ollama` into the YAML `Ollama`, which keeps its name', () => {+ const merged = mergeConfigOverrides(base, [+ fakeConfig(+ { endpoints: { custom: [{ name: 'ollama', baseURL: 'http://override:11434/v1' }] } },+ 10,+ ),+ ]);++ expect(customOf(merged)).toEqual([{ ...yamlOllama, baseURL: 'http://override:11434/v1' }]);+ });++ it('folds every layer onto one entry, the highest priority winning', () => {+ const merged = mergeConfigOverrides(base, [+ fakeConfig({ endpoints: { custom: [{ name: 'OLLAMA', modelDisplayLabel: 'Low' }] } }, 10),+ fakeConfig({ endpoints: { custom: [{ name: 'ollama', modelDisplayLabel: 'High' }] } }, 20),+ ]);++ expect(customOf(merged)).toEqual([{ ...yamlOllama, modelDisplayLabel: 'High' }]);+ });++ it('folds custom endpoint merge keys only, and only the names the runtime folds', () => {+ expect(foldConfigMergeKey('endpoints.custom', 'OLLAMA')).toBe('ollama');+ expect(foldConfigMergeKey('endpoints.custom', 'Ollama')).toBe('ollama');+ expect(foldConfigMergeKey('endpoints.custom', 'OpenRouter')).toBe('OpenRouter');+ expect(foldConfigMergeKey('endpoints.custom', ' Ollama ')).toBe(' Ollama ');+ expect(foldConfigMergeKey('mcpServers', 'Ollama')).toBe('Ollama');+ });++ it('keeps the spelling of the layer that first defined the entry', () => {+ const merged = mergeConfigOverrides({ endpoints: { custom: [] } } as unknown as AppConfig, [+ fakeConfig({ endpoints: { custom: [{ name: 'OLLAMA', baseURL: 'http://low/v1' }] } }, 10),+ fakeConfig({ endpoints: { custom: [{ name: 'ollama', baseURL: 'http://high/v1' }] } }, 20),+ ]);++ expect(customOf(merged)).toEqual([{ name: 'OLLAMA', baseURL: 'http://high/v1' }]);+ });++ it('applies an override to every YAML spelling when YAML itself holds both', () => {+ const merged = mergeConfigOverrides(+ {+ endpoints: { custom: [yamlOllama, { ...yamlOllama, name: 'ollama', baseURL: 'http://b' }] },+ } as unknown as AppConfig,+ [fakeConfig({ endpoints: { custom: [{ name: 'OLLAMA', modelDisplayLabel: 'Both' }] } }, 10)],+ );++ expect(customOf(merged)).toEqual([+ { ...yamlOllama, modelDisplayLabel: 'Both' },+ { ...yamlOllama, name: 'ollama', baseURL: 'http://b', modelDisplayLabel: 'Both' },+ ]);+ });++ it('keeps every other custom endpoint name case-sensitive', () => {+ const openRouter = { name: 'OpenRouter', baseURL: 'https://openrouter.ai/api/v1' };+ const merged = mergeConfigOverrides(+ { endpoints: { custom: [openRouter] } } as unknown as AppConfig,+ [fakeConfig({ endpoints: { custom: [{ name: 'openrouter', baseURL: 'https://o' }] } }, 10)],+ );++ expect(customOf(merged).map((item) => item.name)).toEqual(['OpenRouter', 'openrouter']);+ });++ it('rejects a write that names one entry in two spellings, reporting the earlier item', () => {+ const custom = [+ { name: 'Ollama', modelDisplayLabel: 'First' },+ { name: 'ollama', modelDisplayLabel: 'Second' },+ ];++ expect(getConfigOverrideIssues({ endpoints: { custom } })).toEqual([+ {+ path: 'endpoints.custom.0',+ segments: ['endpoints', 'custom', '0'],+ code: 'duplicate_merge_key',+ },+ ]);+ });++ describe('a stored document that names one entry in two spellings', () => {+ /** Stored before names were folded: requests used the first item's host and key. */+ const legacy = [+ {+ name: 'Ollama',+ baseURL: 'http://override-first/v1',+ apiKey: 'v3:first-key',+ modelDisplayLabel: 'legacy-first',+ },+ { name: 'ollama', modelDisplayLabel: 'legacy-second' },+ ];+ let warn: jest.SpyInstance;++ beforeEach(() => {+ warn = jest.spyOn(logger, 'warn').mockImplementation(() => logger);+ });++ afterEach(() => {+ warn.mockRestore();+ });++ it('combines the items in document order onto the YAML entry, keeping the first host and key', () => {+ const merged = mergeConfigOverrides(base, [+ fakeConfig({ endpoints: { custom: legacy } }, 10, undefined, 'legacy-doc'),+ ]);++ expect(customOf(merged)).toEqual([+ {+ ...yamlOllama,+ baseURL: 'http://override-first/v1',+ apiKey: 'v3:first-key',+ modelDisplayLabel: 'legacy-second',+ },+ ]);+ const messages = warn.mock.calls.map(([message]) => String(message));+ expect(messages).toEqual([expect.stringContaining('Combining "endpoints.custom" items')]);+ expect(messages[0]).toContain('legacy-doc');+ });++ it('lets the later item win the fields both set', () => {+ const merged = mergeConfigOverrides(base, [+ fakeConfig(+ {+ endpoints: {+ custom: [legacy[0], { name: 'OLLAMA', baseURL: 'http://override-second/v1' }],+ },+ },+ 10,+ ),+ ]);++ expect(customOf(merged)).toEqual([+ {+ ...yamlOllama,+ baseURL: 'http://override-second/v1',+ apiKey: 'v3:first-key',+ modelDisplayLabel: 'legacy-first',+ },+ ]);+ });++ it('appends the combined entry where the first item stood when YAML has no such entry', () => {+ const merged = mergeConfigOverrides({ endpoints: { custom: [] } } as unknown as AppConfig, [+ fakeConfig({ endpoints: { custom: [...legacy, { name: 'Other', apiKey: 'k' }] } }, 10),+ ]);++ expect(customOf(merged)).toEqual([+ {+ name: 'ollama',+ baseURL: 'http://override-first/v1',+ apiKey: 'v3:first-key',+ modelDisplayLabel: 'legacy-second',+ },+ { name: 'Other', apiKey: 'k' },+ ]);+ });+ });++ it('keeps the existing rule for a stored repeat of one spelling: the last item applies', () => {+ const merged = mergeConfigOverrides(base, [+ fakeConfig(+ {+ endpoints: {+ custom: [+ { name: 'ollama', baseURL: 'http://first/v1' },+ { name: 'ollama', modelDisplayLabel: 'Second' },+ ],+ },+ },+ 10,+ ),+ ]);++ expect(customOf(merged)).toEqual([{ ...yamlOllama, modelDisplayLabel: 'Second' }]);+ });++ it('attributes an issue on the merged entry to the override item that folds onto it', () => {+ const yamlBase = { endpoints: { custom: [yamlOllama] } } as Partial<TCustomConfig>;++ expect(+ getConfigOverrideIssues({ endpoints: { custom: [{ name: 'OLLAMA', models: 5 }] } }, yamlBase),+ ).toEqual([+ {+ path: 'endpoints.custom.0.models',+ segments: ['endpoints', 'custom', '0', 'models'],+ code: 'invalid_type',+ },+ ]);+ expect(+ getConfigOverrideIssues(+ { endpoints: { custom: [{ name: 'ollama', modelDisplayLabel: 'Local' }] } },+ yamlBase,+ ),+ ).toEqual([]);+ });++ it('strips an invalid field of a folded override and keeps the YAML value beneath it', () => {+ const merged = mergeConfigOverrides(base, [+ fakeConfig({ endpoints: { custom: [{ name: 'ollama', models: 5, iconURL: 'i.png' }] } }, 10),+ ]);++ expect(customOf(merged)).toEqual([{ ...yamlOllama, iconURL: 'i.png' }]);+ });+});++describe('combineFoldedConfigItems', () => {+ it('returns the same array when no entry is named in two spellings', () => {+ const items = [{ name: 'ollama' }, { name: 'ollama', a: 1 }, { name: 'Other' }, 'loose', {}];++ expect(combineFoldedConfigItems('endpoints.custom', items)).toBe(items);+ });++ it('combines every item of a two-spelling group in order, at the first position', () => {+ const items = [+ { name: 'A' },+ { name: 'Ollama', baseURL: 'one', headers: { x: '1' } },+ { name: 'ollama', headers: { y: '2' } },+ { name: 'B' },+ { name: 'OLLAMA', baseURL: 'three' },+ ];++ expect(combineFoldedConfigItems('endpoints.custom', items)).toEqual([+ { name: 'A' },+ { name: 'OLLAMA', baseURL: 'three', headers: { x: '1', y: '2' } },+ { name: 'B' },+ ]);+ });++ it('leaves arrays whose keys are not folded alone', () => {+ const items = [{ name: 'Ollama' }, { name: 'ollama' }];++ expect(combineFoldedConfigItems('modelSpecs.list', items)).toBe(items);+ });+});+describe('getDottedSectionIssues', () => {it('reports only top-level keys holding a dot', () => {expect(getDottedSectionIssues({ 'filters.x': 1, registration: { 'a.b': 1 } })).toEqual([@@ -2356,6 +2602,35 @@ describe('getConfigChangeIssues', () => {]);});+ it('matches an existing issue of an entry under any spelling of its folded key', () => {+ const stored = {+ overrides: {+ endpoints: {+ custom: [+ { name: 'first', baseURL: 'https://first.example.com/v1' },+ { name: 'Ollama', baseURL: 42 },+ ],+ },+ },+ };+ const respelled = {+ overrides: { endpoints: { custom: [{ name: 'ollama', baseURL: 42 }] } },+ tombstones: [],+ };+ const other = {+ overrides: { endpoints: { custom: [{ name: 'Foo', baseURL: 42 }] } },+ tombstones: [],+ };+ const otherStored = {+ overrides: { endpoints: { custom: [{ name: 'foo', baseURL: 42 }] } },+ };++ expect(getConfigChangeIssues(respelled, {}, stored, [])).toEqual([]);+ expect(paths(getConfigChangeIssues(other, {}, otherStored, []))).toEqual([+ 'endpoints.custom.0.baseURL',+ ]);+ });+it('tells apart record keys that contain dots from the nested path their dots spell', () => {const stored = {overrides: { endpoints: { bedrock: { inferenceProfiles: { 'us.a.b': 5 } } } },diff --git a/packages/data-schemas/src/app/resolution.ts b/packages/data-schemas/src/app/resolution.tsindex bc9d809201..39d98b3907 100644--- a/packages/data-schemas/src/app/resolution.ts+++ b/packages/data-schemas/src/app/resolution.ts@@ -6,6 +6,7 @@ import {RUNTIME_CONFIG_INTERFACE_FIELDS,PERMISSION_SUB_KEYS,isProcessMCPServerConfig,+ normalizeEndpointName,configSchema,} from 'librechat-data-provider';import type { TCustomConfig } from 'librechat-data-provider';@@ -48,6 +49,16 @@ const ARRAY_MERGE_KEYS: Record<string, string> = {'endpoints.custom': 'name',};+/**+ * How a merge key is folded before items are matched, by `ARRAY_MERGE_KEYS` path: two+ * spellings the runtime serves as one item are one item to the merge too. Custom endpoint+ * names fold through `normalizeEndpointName`, so an override `ollama` lands on the YAML+ * `Ollama` instead of serving beside it with a different baseURL and key.+ */+const MERGE_KEY_FOLDS: Record<string, (key: string) => string> = {+ 'endpoints.custom': normalizeEndpointName,+};+/*** Object-valued paths an override replaces whole instead of merging into. A theme* definition is one coherent value: merging two would keep the base theme's modes,@@ -115,11 +126,40 @@ function isSafePath(path: string): boolean {* such as `name` for `endpoints.custom`; `undefined` for any other path.*/export function getConfigArrayMergeKey(segments: readonly string[]): string | undefined {+ const arrayPath = getMergeArrayPath(segments);+ return arrayPath === undefined ? undefined : ARRAY_MERGE_KEYS[arrayPath];+}++/** The `ARRAY_MERGE_KEYS` path of the merged-by-key array at an override (YAML) path. */+function getMergeArrayPath(segments: readonly string[]): string | undefined {if (segments.length === 0 || segments.some((segment) => segment.includes('.'))) {return undefined;}const appConfigPath = remapOverridePath(segments.join('.'));- return hasOwn(ARRAY_MERGE_KEYS, appConfigPath) ? ARRAY_MERGE_KEYS[appConfigPath] : undefined;+ return hasOwn(ARRAY_MERGE_KEYS, appConfigPath) ? appConfigPath : undefined;+}++/**+ * The identity entry key `key` of the merged-by-key array at an override (YAML) path has: the+ * key as the runtime merge folds it (`foldConfigMergeKey`), so `Ollama` and `ollama` name one+ * custom endpoint to entry changes as they do to the merge. A key at any other path is its own+ * identity.+ */+export function getConfigEntryIdentity(segments: readonly string[], key: string): string {+ const arrayPath = getMergeArrayPath(segments);+ return arrayPath === undefined ? key : foldConfigMergeKey(arrayPath, key);+}++/**+ * `combineFoldedConfigItems` for the merged-by-key array at an override (YAML) path: stored+ * items naming one entry in two spellings, combined as the runtime merge combines them.+ */+export function combineFoldedConfigEntries(+ segments: readonly string[],+ items: unknown[],+): unknown[] {+ const arrayPath = getMergeArrayPath(segments);+ return arrayPath === undefined ? items : combineFoldedConfigItems(arrayPath, items);}function remapOverridePath(path: string): string {@@ -182,6 +222,89 @@ function deleteConfigPath<T extends AnyObject>(target: T, path: string): T {return { ...target, mcpConfig: processServers } as T;}+/**+ * Folds a merge key of the merged-by-key array at `arrayPath` into the identity layers match+ * on (`Ollama` and `ollama` are one custom endpoint); other keys come back unchanged. Code that+ * pairs items across writes, such as secret preservation, matches on the same identity.+ */+export function foldConfigMergeKey(arrayPath: string, key: string): string {+ return hasOwn(MERGE_KEY_FOLDS, arrayPath) ? MERGE_KEY_FOLDS[arrayPath](key) : key;+}++/** The identity an item of the merged-by-key array at `arrayPath` matches on. */+function getMergeKey(item: AnyObject, keyField: string, arrayPath: string): unknown {+ const key = item[keyField];+ return typeof key === 'string' ? foldConfigMergeKey(arrayPath, key) : key;+}++/**+ * Combines the items of a stored merged-by-key array that name one item in more than one+ * spelling of its folded key (`Ollama` and `ollama`): merged in document order, later fields+ * winning, at the first one's position. A document stored before names were folded kept such+ * items apart, and the runtime took requests' `baseURL` and key from the first while serving+ * the later one's metadata, so the combined item keeps what each contributed instead of losing+ * the earlier one as a duplicate. A key repeated in only one spelling is left as is (the last+ * item applies). Returns the same array when nothing combines.+ */+export function combineFoldedConfigItems(arrayPath: string, items: unknown[]): unknown[] {+ const keyField = ARRAY_MERGE_KEYS[arrayPath];+ if (!keyField || !hasOwn(MERGE_KEY_FOLDS, arrayPath)) {+ return items;+ }+ const groups = new Map<string, { spellings: Set<string>; indexes: number[] }>();+ items.forEach((item, index) => {+ const key = isPlainObject(item) ? item[keyField] : undefined;+ if (typeof key !== 'string' || key === '') {+ return;+ }+ const identity = MERGE_KEY_FOLDS[arrayPath](key);+ const group = groups.get(identity) ?? { spellings: new Set<string>(), indexes: [] };+ group.spellings.add(key);+ group.indexes.push(index);+ groups.set(identity, group);+ });+ const depth = arrayPath.split('.').length;+ const combined = new Map<number, AnyObject>();+ const absorbed = new Set<number>();+ for (const { spellings, indexes } of groups.values()) {+ if (spellings.size < 2) {+ continue;+ }+ const [first, ...rest] = indexes;+ const merged = rest.reduce<AnyObject>(+ (item, index) => deepMerge(item, items[index] as AnyObject, depth, arrayPath),+ items[first] as AnyObject,+ );+ combined.set(first, merged);+ rest.forEach((index) => absorbed.add(index));+ }+ if (combined.size === 0) {+ return items;+ }+ return items.flatMap((item, index) => (absorbed.has(index) ? [] : [combined.get(index) ?? item]));+}++/** `combineFoldedConfigItems` over every folded array of a stored overrides document. */+function combineStoredFoldedItems(overrides: unknown, principal: string): unknown {+ let result = overrides;+ for (const arrayPath of Object.keys(MERGE_KEY_FOLDS)) {+ const segments = arrayPath.split('.');+ const items = getPath(result, segments);+ if (!Array.isArray(items)) {+ continue;+ }+ const combined = combineFoldedConfigItems(arrayPath, items);+ if (combined === items) {+ continue;+ }+ logger.warn(+ `[mergeConfigOverrides] Combining "${arrayPath}" items that name one entry in different spellings for ${principal}; a write of this list must name each entry once`,+ );+ result = setPath(result, segments, combined);+ }+ return result;+}+function mergeArrayByKey(target: AnyObject[],source: AnyObject[],@@ -192,7 +315,7 @@ function mergeArrayByKey(const sourceByKey = new Map<unknown, AnyObject>();for (const item of source) {if (item != null && typeof item === 'object') {- const key = item[keyField];+ const key = getMergeKey(item, keyField, path);// Source items without a key value are skipped: no stable identity// for matching or appending. (Keyless target items are preserved as-is below.)if (key != null) {@@ -206,13 +329,15 @@ function mergeArrayByKey(// Pass the array container path (not a per-element path) so item// properties build paths like 'endpoints.custom.baseURL' for any- // nested ARRAY_MERGE_KEYS lookups.+ // nested ARRAY_MERGE_KEYS lookups. A matched item keeps the spelling of+ // its key the layer beneath gave it: an override `ollama` modifies the+ // YAML `Ollama`, which stays the entry's name.for (const item of target) {if (item != null && typeof item === 'object') {- const key = item[keyField];+ const key = getMergeKey(item, keyField, path);const override = key != null ? sourceByKey.get(key) : undefined;if (override) {- result.push(deepMerge(item, override, depth + 1, path));+ result.push({ ...deepMerge(item, override, depth + 1, path), [keyField]: item[keyField] });seen.add(key);} else {result.push({ ...item });@@ -348,15 +473,16 @@ function findItemIndex(key: string,keyField: string | undefined,mergedItem: unknown,+ arrayPath: string,): number {if (keyField) {+ if (!isPlainObject(mergedItem)) {+ return -1;+ }+ const mergedKey = getMergeKey(mergedItem, keyField, arrayPath);for (let index = node.length - 1; index >= 0; index--) {const item = node[index];- if (- isPlainObject(item) &&- isPlainObject(mergedItem) &&- item[keyField] === mergedItem[keyField]- ) {+ if (isPlainObject(item) && getMergeKey(item, keyField, arrayPath) === mergedKey) {return index;}}@@ -390,7 +516,7 @@ function attributeIssue(? ARRAY_MERGE_KEYS[arrayPath]: undefined;const mergedItem = Array.isArray(mergedNode) ? mergedNode[Number(key)] : undefined;- const index = findItemIndex(node, key, keyField, mergedItem);+ const index = findItemIndex(node, key, keyField, mergedItem, arrayPath);if (keyField && index < 0) {return undefined;}@@ -448,12 +574,15 @@ function getMergeKeyIssues(overrides: AnyObject): ConfigOverrideIssue[] {return [];}const lastIndex = new Map<unknown, number>();- node.forEach((item, index) => isPlainObject(item) && lastIndex.set(item[keyField], index));+ node.forEach(+ (item, index) =>+ isPlainObject(item) && lastIndex.set(getMergeKey(item, keyField, arrayPath), index),+ );return node.flatMap((item, index) => {if (!isPlainObject(item) || typeof item[keyField] !== 'string' || item[keyField] === '') {return [toIssue([...segments, String(index)], 'missing_merge_key')];}- return lastIndex.get(item[keyField]) === index+ return lastIndex.get(getMergeKey(item, keyField, arrayPath)) === index? []: [toIssue([...segments, String(index)], 'duplicate_merge_key')];});@@ -872,9 +1001,10 @@ function hasMergeKey(item: unknown, keyField: string): boolean {/*** Where an issue sits in `overrides`, in a form that survives entries moving: an item of a- * merged-by-key array is named by its key, or (without one) by its place among the keyless- * items, rather than by its index. Removing one entry shifts the ones after it, and their- * issues must still match the ones the stored document already had.+ * merged-by-key array is named by its key's identity (`getConfigEntryIdentity`), or (without+ * one) by its place among the keyless items, rather than by its index. Removing one entry+ * shifts the ones after it, and their issues must still match the ones the stored document+ * already had.*/function getIssueLocation(segments: readonly string[], overrides: unknown): string {const location: Array<string | { key: unknown } | { keyless: number }> = [];@@ -889,7 +1019,12 @@ function getIssueLocation(segments: readonly string[], overrides: unknown): striconst item: unknown = node[position];location.push(hasMergeKey(item, keyField)- ? { key: (item as AnyObject)[keyField] }+ ? {+ key: getConfigEntryIdentity(+ segments.slice(0, index),+ (item as AnyObject)[keyField] as string,+ ),+ }: {keyless: node.slice(0, position).filter((other) => !hasMergeKey(other, keyField)).length,@@ -1022,7 +1157,7 @@ function stripInvalidOverrides(base: Partial<TCustomConfig>,): AnyObject {const principal = `${config.principalType}/${config.principalId}`;- let stripped: unknown = config.overrides;+ let stripped: unknown = combineStoredFoldedItems(config.overrides, principal);/*** Removing a field can make a related field it supplies fail, so check again while* removals make progress. If they stop, only the sections that still fail are dropped.diff --git a/packages/data-schemas/src/types/admin.ts b/packages/data-schemas/src/types/admin.tsindex 8cd7cc310e..fc84674a68 100644--- a/packages/data-schemas/src/types/admin.ts+++ b/packages/data-schemas/src/types/admin.ts@@ -111,7 +111,8 @@ export type AdminConfigTombstoneRequest = AdminConfigWritePrecondition &* Only sections `configSchema` defines can be written or hidden; `unset` may also remove what* an older server stored outside them. Entries of a merged-by-key array are addressed by key,* never by position: a `set`, `unset` or `rename` whose path runs into one- * (`endpoints.custom.0.headers`) is refused.+ * (`endpoints.custom.0.headers`) is refused. A key names the entry the runtime merge matches it+ * to: a custom endpoint `ollama` in any case is the one entry `Ollama` also names.* - `upsertEntry` replaces the principal's own entry of a merged-by-key array (`endpoints.custom`,* keyed by `name`) with `entry`, or appends it. An entry that omits a stored `apiKey` keeps it.* - `removeEntry` removes the principal's own entry with that key; an inherited entry of the