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: Discover Managed Agents in Marketplace Search (#16324)
lia-by-librechat[bot]5862b3b7d1b4
diff --git a/api/server/controllers/agents/v1.js b/api/server/controllers/agents/v1.jsindex e975d86746..d6137f281b 100644--- a/api/server/controllers/agents/v1.js+++ b/api/server/controllers/agents/v1.js@@ -15,6 +15,11 @@ const {collectEdgeAgentIds,replaceEdgeSourceId,mergeDeploymentSkillIds,+ getAgentListAccess,+ isFullAgentListAvatarCacheEntry,+ getAgentListAvatarRefreshKey,+ refreshAgentListAvatarsBeforePage,+ refreshManagedAgentListPageAvatars,mergeAgentOcrConversion,sanitizeModelParameters,MAX_AVATAR_REFRESH_AGENTS,@@ -84,6 +89,7 @@ const {resolveConfigServers,userCanUseMCPServers,} = require('~/server/services/MCP');+const { hasCapability } = require('~/server/middleware/roles/capabilities');const { attachOwnerContacts } = require('~/server/services/Agents/ownerContact');const { getMCPServersRegistry } = require('~/config');const { getLogStores } = require('~/cache');@@ -1706,7 +1712,7 @@ const deleteAgentHandler = async (req, res) => {};/**- * Lists agents using ACL-aware permissions (ownership + explicit shares).+ * Lists agents using ACL permissions or the manage:agents capability.* @route GET /Agents* @param {object} req - Express Request* @param {object} req.query - Request query@@ -1727,12 +1733,6 @@ const getListAgentsHandler = async (req, res) => {requiredPermission = PermissionBits.VIEW;}const canReturnSkillConfig = hasEditBit(requiredPermission);- /**- * Derived from the same bit as `canReturnSkillConfig` but answering a different question:- * skill-config exposure versus edit-permission reporting. An EDIT-scoped request matches- * only editable agents, so it needs no second lookup to know which ones those are.- */- const needsEditableLookup = !hasEditBit(requiredPermission);// Base filterconst filter = {};@@ -1756,7 +1756,7 @@ const getListAgentsHandler = async (req, res) => {}const cache = getLogStores(CacheKeys.S3_EXPIRY_INTERVAL);- const refreshKey = `${userId}:agents_avatar_refresh`;+ const refreshKey = getAgentListAvatarRefreshKey(req.user);/*** These reads share no inputs, so they resolve together rather than chaining round@@ -1766,8 +1766,8 @@ const getListAgentsHandler = async (req, res) => {** `editableIds` lets a VIEW-scoped response mark which agents the caller may also edit,* so consumers wanting just the editable subset can filter one shared VIEW fetch rather- * than issuing a second full paginated walk under an EDIT-scoped cache key. Requests- * that already ask for EDIT get it for free: everything they match is editable.+ * than issuing a second full paginated walk under an EDIT-scoped cache key. Managers and+ * EDIT-scoped requests need no separate edit lookup: everything they match is editable.** `idOnTheSource` is forwarded so `getUserPrincipals` resolves identity without reading* the user document; the auth strategies already normalize it to a value or null. Each@@ -1775,19 +1775,12 @@ const getListAgentsHandler = async (req, res) => {*/const { idOnTheSource } = req.user;const [- accessibleIds,+ { accessibleIds, editableIds },publiclyAccessibleIds,cachedRefreshEntry,accessibleSkillIds,- editableIds,] = await Promise.all([- findAccessibleResources({- userId,- role: req.user.role,- idOnTheSource,- resourceType: ResourceType.AGENT,- requiredPermissions: requiredPermission,- }),+ getAgentListAccess(req.user, requiredPermission, { hasCapability, findAccessibleResources }),findPubliclyAccessibleResources({resourceType: ResourceType.AGENT,requiredPermissions: PermissionBits.VIEW,@@ -1802,21 +1795,9 @@ const getListAgentsHandler = async (req, res) => {resourceType: ResourceType.SKILL,requiredPermissions: PermissionBits.VIEW,}),- needsEditableLookup- ? findAccessibleResources({- userId,- role: req.user.role,- idOnTheSource,- resourceType: ResourceType.AGENT,- requiredPermissions: PermissionBits.EDIT,- })- : null,]);- const isValidCachedRefresh =- cachedRefreshEntry != null &&- typeof cachedRefreshEntry === 'object' &&- cachedRefreshEntry.urlCache != null;+ const isValidCachedRefresh = isFullAgentListAvatarCacheEntry(cachedRefreshEntry);/*** Refresh all S3 avatars for this user's accessible agent set (not only the current page)@@ -1866,11 +1847,16 @@ const getListAgentsHandler = async (req, res) => {}};- const cachedRefresh = await resolveAvatarRefresh();+ const cachedRefreshBeforePage = await refreshAgentListAvatarsBeforePage(+ accessibleIds,+ cachedRefreshEntry,+ resolveAvatarRefresh,+ );- // Use the new ACL-aware function+ // Use the ACL-scoped or explicitly tenant-scoped list query.const data = await db.getListAgentsByAccess({accessibleIds,+ tenantId: req.user.tenantId ?? null,otherParams: filter,limit,after: cursor,@@ -1883,13 +1869,23 @@ const getListAgentsHandler = async (req, res) => {return res.json(data);}+ const cachedRefresh = await refreshManagedAgentListPageAvatars({+ accessibleIds,+ agents,+ cachedEntry: cachedRefreshBeforePage,+ refreshS3Url,+ cacheSet: cache.set.bind(cache),+ cacheKey: refreshKey,+ ttl: Time.THIRTY_MINUTES,+ });+const accessibleSkillSet = canReturnSkillConfig? null: new Set(mergeDeploymentSkillIds(accessibleSkillIds).map((oid) => oid.toString()));const publicSet = new Set(publiclyAccessibleIds.map((oid) => oid.toString()));/** Null for EDIT-scoped requests, where every matched agent is editable by definition. */- const editableSet = editableIds ? new Set(editableIds.map((oid) => oid.toString())) : null;+ const editableSet = editableIds ? new Set(editableIds) : null;const agentsWithContacts = await attachOwnerContacts(agents);const urlCache = cachedRefresh?.urlCache;@@ -2016,7 +2012,7 @@ const uploadAgentAvatarHandler = async (req, res) => {try {const avatarCache = getLogStores(CacheKeys.S3_EXPIRY_INTERVAL);- await avatarCache.delete(`${req.user.id}:agents_avatar_refresh`);+ await avatarCache.delete(getAgentListAvatarRefreshKey(req.user));} catch (cacheErr) {logger.error('[/:agent_id/avatar] Error invalidating avatar refresh cache', cacheErr);}diff --git a/api/server/controllers/agents/v1.spec.js b/api/server/controllers/agents/v1.spec.jsindex d96af401fc..bf704940ba 100644--- a/api/server/controllers/agents/v1.spec.js+++ b/api/server/controllers/agents/v1.spec.js@@ -3,7 +3,7 @@ const express = require('express');const request = require('supertest');const { nanoid } = require('nanoid');const { v4: uuidv4 } = require('uuid');-const { createModels, tenantStorage } = require('@librechat/data-schemas');+const { createModels, tenantStorage, SystemCapabilities } = require('@librechat/data-schemas');const {Tools,SkillsScope,@@ -111,6 +111,7 @@ const {refreshS3Url,} = require('@librechat/api');const { grantPermission } = require('~/server/services/PermissionService');+const { hasCapability } = require('~/server/middleware/roles/capabilities');const db = require('~/models');/**@@ -3391,6 +3392,81 @@ describe('Agent Controllers - Mass Assignment Protection', () => {});});+ test('lets a manage:agents role discover unshared agents by search', async () => {+ await db.grantCapability({+ principalType: PrincipalType.ROLE,+ principalId: 'LIST_MANAGER_TEST',+ capability: SystemCapabilities.MANAGE_AGENTS,+ });+ mockReq.user = {+ id: userB.toString(),+ role: 'LIST_MANAGER_TEST',+ idOnTheSource: null,+ };+ mockReq.query.search = 'A2';+ findAccessibleResources.mockResolvedValue([]);+ findPubliclyAccessibleResources.mockResolvedValue([]);++ expect(await hasCapability(mockReq.user, SystemCapabilities.MANAGE_AGENTS)).toBe(true);+ await getListAgentsHandler(mockReq, mockRes);++ const response = mockRes.json.mock.calls[0][0];+ expect(response.data.map((agent) => agent.id)).toEqual([agentA2.id]);+ expect(response.data[0].isEditable).toBe(true);+ expect(findAccessibleResources).toHaveBeenCalledWith(+ expect.objectContaining({ resourceType: ResourceType.AGENT }),+ );+ });++ test('restricts a manager to the authenticated tenant even without ambient tenant context', async () => {+ const tenantA = `tenant-a-${uuidv4()}`;+ const tenantB = `tenant-b-${uuidv4()}`;+ const name = 'Tenant-Scoped Discovery';+ const agentInA = await tenantStorage.run({ tenantId: tenantA }, () =>+ Agent.create({+ id: `agent_${nanoid(12)}`,+ name,+ provider: 'openai',+ model: 'gpt-4',+ author: userA,+ }),+ );+ await tenantStorage.run({ tenantId: tenantB }, () =>+ Agent.create({+ id: `agent_${nanoid(12)}`,+ name,+ provider: 'openai',+ model: 'gpt-4',+ author: userB,+ }),+ );+ await db.grantCapability({+ principalType: PrincipalType.ROLE,+ principalId: 'LIST_TENANT_MANAGER',+ capability: SystemCapabilities.MANAGE_AGENTS,+ });+ mockReq.user = {+ id: userB.toString(),+ role: 'LIST_TENANT_MANAGER',+ idOnTheSource: null,+ tenantId: tenantA,+ };+ mockReq.query.search = name;+ findAccessibleResources.mockResolvedValue([]);+ findPubliclyAccessibleResources.mockResolvedValue([]);++ await getListAgentsHandler(mockReq, mockRes);+ expect(mockCache.get).toHaveBeenCalledWith(+ `${userB.toString()}:${tenantA}:agents_avatar_refresh`,+ );+ expect(mockRes.json.mock.calls[0][0].data.map((agent) => agent.id)).toEqual([agentInA.id]);++ mockRes.json.mockClear();+ mockReq.user.tenantId = undefined;+ await getListAgentsHandler(mockReq, mockRes);+ expect(mockRes.json.mock.calls[0][0].data).toHaveLength(0);+ });+test('should return empty list when user has no accessible agents', async () => {// User B has no permissions and no owned agentsmockReq.user.id = userB.toString();@@ -4111,6 +4187,68 @@ describe('Agent Controllers - Mass Assignment Protection', () => {});});+ test('refreshes only manager search results without writing or losing later cursor pages', async () => {+ const db = require('~/models');+ const name = 'Paged Manager Avatar';+ const firstAgent = await Agent.create({+ id: `agent_${nanoid(12)}`,+ name,+ provider: 'openai',+ model: 'gpt-4',+ author: userA,+ avatar: { source: FileSources.s3, filepath: 'first.jpg' },+ });+ const secondAgent = await Agent.create({+ id: `agent_${nanoid(12)}`,+ name,+ provider: 'openai',+ model: 'gpt-4',+ author: userA,+ avatar: { source: FileSources.s3, filepath: 'second.jpg' },+ });+ await db.grantCapability({+ principalType: PrincipalType.ROLE,+ principalId: 'LIST_AVATAR_MANAGER',+ capability: SystemCapabilities.MANAGE_AGENTS,+ });+ const mockReq = {+ user: { id: userB.toString(), role: 'LIST_AVATAR_MANAGER', idOnTheSource: null },+ query: { search: name, limit: '1' },+ };+ const mockRes = { status: jest.fn().mockReturnThis(), json: jest.fn().mockReturnThis() };+ const listSpy = jest.spyOn(db, 'getListAgentsByAccess');+ const updateSpy = jest.spyOn(db, 'updateAgent');+ findAccessibleResources.mockResolvedValue([]);+ findPubliclyAccessibleResources.mockResolvedValue([]);+ refreshS3Url.mockImplementation(async ({ filepath }) => `signed:${filepath}`);++ try {+ await getListAgentsHandler(mockReq, mockRes);+ const pageOne = mockRes.json.mock.calls[0][0];+ expect(pageOne.data).toHaveLength(1);+ expect(pageOne.after).toBeTruthy();+ expect(pageOne.data[0].avatar.filepath).toMatch(/^signed:/);+ expect(listSpy).toHaveBeenCalledTimes(1);+ expect(refreshS3Url).toHaveBeenCalledTimes(1);+ expect(updateSpy).not.toHaveBeenCalled();++ mockRes.json.mockClear();+ mockReq.query.cursor = pageOne.after;+ await getListAgentsHandler(mockReq, mockRes);+ const pageTwo = mockRes.json.mock.calls[0][0];+ expect(pageTwo.data).toHaveLength(1);+ expect([pageOne.data[0].id, pageTwo.data[0].id].sort()).toEqual(+ [firstAgent.id, secondAgent.id].sort(),+ );+ expect(pageTwo.data[0].avatar.filepath).toMatch(/^signed:/);+ expect(refreshS3Url).toHaveBeenCalledTimes(2);+ expect(updateSpy).not.toHaveBeenCalled();+ } finally {+ listSpy.mockRestore();+ updateSpy.mockRestore();+ }+ });+test('should skip avatar refresh if cache hit', async () => {mockCache.get.mockResolvedValue({ urlCache: {} });findAccessibleResources.mockResolvedValue([agentWithS3Avatar._id]);@@ -4131,6 +4269,22 @@ describe('Agent Controllers - Mass Assignment Protection', () => {expect(refreshS3Url).not.toHaveBeenCalled();});+ test('does not treat a manager page cache as an ACL-wide refresh after role downgrade', async () => {+ mockCache.get.mockResolvedValue({ urlCache: {}, scope: 'page' });+ findAccessibleResources.mockResolvedValue([agentWithS3Avatar._id]);+ findPubliclyAccessibleResources.mockResolvedValue([]);+ refreshS3Url.mockResolvedValue('refreshed-after-downgrade.jpg');+ const mockReq = { user: { id: userA.toString(), role: 'USER' }, query: {} };+ const mockRes = { status: jest.fn().mockReturnThis(), json: jest.fn().mockReturnThis() };++ await getListAgentsHandler(mockReq, mockRes);++ expect(refreshS3Url).toHaveBeenCalledTimes(1);+ expect(mockRes.json.mock.calls[0][0].data[0].avatar.filepath).toBe(+ 'refreshed-after-downgrade.jpg',+ );+ });+test('should refresh and persist S3 avatars on cache miss', async () => {mockCache.get.mockResolvedValue(false);findAccessibleResources.mockResolvedValue([agentWithS3Avatar._id]);diff --git a/api/server/controllers/avatar.contentFilter.spec.js b/api/server/controllers/avatar.contentFilter.spec.jsindex f32675d4f2..1e7afc7c0d 100644--- a/api/server/controllers/avatar.contentFilter.spec.js+++ b/api/server/controllers/avatar.contentFilter.spec.js@@ -131,6 +131,30 @@ describe('entity avatar filename content filtering', () => {unlinkSpy.mockRestore();});+ it('invalidates the tenant-scoped list avatar cache after an accepted upload', async () => {+ const { getLogStores } = require('~/cache');+ const { getStrategyFunctions } = require('~/server/services/Files/strategies');+ const { resizeAvatar } = require('~/server/services/Files/images/avatar');+ const avatarCache = { delete: jest.fn().mockResolvedValue(undefined) };+ getLogStores.mockReturnValue(avatarCache);+ getStrategyFunctions.mockReturnValue({+ processAvatar: jest.fn().mockResolvedValue('new-avatar.jpg'),+ });+ resizeAvatar.mockResolvedValue(Buffer.from('resized'));+ db.getAgent.mockResolvedValue({ id: 'agent-1', avatar: null });+ db.updateAgent.mockResolvedValue({ id: 'agent-1', avatar: { filepath: 'new-avatar.jpg' } });+ inspectContent.mockReturnValue(null);++ const req = createRequest({ agent_id: 'agent-1' });+ req.config.fileStrategy = 's3';+ const res = createResponse();+ await uploadAgentAvatar(req, res);++ expect(res.status).toHaveBeenCalledWith(201);+ expect(db.updateAgent).toHaveBeenCalled();+ expect(avatarCache.delete).toHaveBeenCalledWith('user-1:tenant-1:agents_avatar_refresh');+ });+it('blocks an agent avatar filename before database or storage work', async () => {const req = createRequest({ agent_id: 'agent-1' });const res = createResponse();diff --git a/packages/api/src/agents/index.ts b/packages/api/src/agents/index.tsindex 7c0533e006..b1a305fbfa 100644--- a/packages/api/src/agents/index.ts+++ b/packages/api/src/agents/index.ts@@ -29,6 +29,8 @@ export * from './backgroundClaims';export * from './backgroundCompletionWakeup';export * from './initialize';export * from './legacy';+export * from './listing';+export * from './listingAvatars';export * from './lazySubagents';export * from './lazyHistory';export * from './memory';diff --git a/packages/api/src/agents/listing.ts b/packages/api/src/agents/listing.tsnew file mode 100644index 0000000000..6a9680399f--- /dev/null+++ b/packages/api/src/agents/listing.ts@@ -0,0 +1,52 @@+import { PermissionBits, ResourceType } from 'librechat-data-provider';+import type { IUser, SystemCapability } from '@librechat/data-schemas';+import { hasManageAgentsCapability } from './reads';++/** ACL implementations may return either plain IDs or objects with a string representation. */+type ResourceId = string | { toString(): string };++type AgentListAccessDeps = {+ hasCapability: (user: IUser, capability: SystemCapability) => Promise<boolean>;+ findAccessibleResources: (params: {+ userId: string;+ role?: string;+ idOnTheSource?: string;+ resourceType: ResourceType;+ requiredPermissions: PermissionBits;+ }) => Promise<ResourceId[]>;+};++export async function getAgentListAccess(+ user: IUser,+ requiredPermissions: PermissionBits,+ deps: AgentListAccessDeps,+): Promise<{ accessibleIds: string[] | null; editableIds: string[] | null }> {+ if (typeof requiredPermissions !== 'number' || requiredPermissions < 1) {+ throw new Error('requiredPermissions must be a positive number');+ }++ const params = {+ userId: user.id,+ role: user.role,+ idOnTheSource: user.idOnTheSource,+ resourceType: ResourceType.AGENT,+ };+ // The normal startup path must not wait for a capability DB read before issuing ACL reads.+ const aclReads = Promise.all([+ deps.findAccessibleResources({ ...params, requiredPermissions }),+ (requiredPermissions & PermissionBits.EDIT) === PermissionBits.EDIT+ ? null+ : deps.findAccessibleResources({ ...params, requiredPermissions: PermissionBits.EDIT }),+ ]);+ // A manager can proceed even if a speculative ACL read rejects before the capability resolves.+ void aclReads.catch(() => undefined);+ if (await hasManageAgentsCapability(user, deps)) {+ return { accessibleIds: null, editableIds: null };+ }++ const [accessibleIds, editableIds] = await aclReads;+ return {+ accessibleIds: accessibleIds.map(String),+ editableIds: editableIds?.map(String) ?? null,+ };+}diff --git a/packages/api/src/agents/listingAvatars.spec.ts b/packages/api/src/agents/listingAvatars.spec.tsnew file mode 100644index 0000000000..a6735be150--- /dev/null+++ b/packages/api/src/agents/listingAvatars.spec.ts@@ -0,0 +1,172 @@+import { FileSources } from 'librechat-data-provider';+import {+ isFullAgentListAvatarCacheEntry,+ getAgentListAvatarRefreshKey,+ refreshAgentListAvatarsBeforePage,+ refreshManagedAgentListPageAvatars,+} from './listingAvatars';+import { MAX_AVATAR_REFRESH_AGENTS } from './avatars';++const visible = { id: 'agent-visible', avatar: { source: FileSources.s3, filepath: 'old.jpg' } };+const nextPage = { id: 'agent-next', avatar: { source: FileSources.s3, filepath: 'next.jpg' } };+const local = { id: 'agent-local', avatar: { source: FileSources.local, filepath: 'local.jpg' } };++function params() {+ return {+ accessibleIds: null,+ agents: [visible, local],+ cachedEntry: null,+ refreshS3Url: jest.fn().mockResolvedValue('signed-visible.jpg'),+ cacheSet: jest.fn().mockResolvedValue(undefined),+ cacheKey: 'user:tenant:avatars',+ ttl: 1800,+ };+}++describe('Agent listing avatar scope', () => {+ it('uses the same tenant-qualified key for listing and upload, including legacy users', () => {+ expect(getAgentListAvatarRefreshKey({ id: 'alice', tenantId: 'tenant-a' })).toBe(+ 'alice:tenant-a:agents_avatar_refresh',+ );+ expect(getAgentListAvatarRefreshKey({ id: 'alice', tenantId: 'tenant-b' })).not.toBe(+ getAgentListAvatarRefreshKey({ id: 'alice', tenantId: 'tenant-a' }),+ );+ expect(getAgentListAvatarRefreshKey({ id: 'alice' })).toBe('alice::agents_avatar_refresh');+ });++ it('does not load every tenant avatar before a manager list query', async () => {+ const refreshAll = jest.fn().mockResolvedValue({ urlCache: { 'agent-visible': 'signed.jpg' } });+ await expect(refreshAgentListAvatarsBeforePage(null, null, refreshAll)).resolves.toBeNull();+ expect(refreshAll).not.toHaveBeenCalled();++ const previous = { urlCache: { 'agent-visible': 'signed.jpg' } };+ await expect(refreshAgentListAvatarsBeforePage(null, previous, refreshAll)).resolves.toEqual(+ previous,+ );+ expect(refreshAll).not.toHaveBeenCalled();+ await expect(refreshAgentListAvatarsBeforePage([], null, refreshAll)).resolves.toEqual(+ previous,+ );+ expect(refreshAll).toHaveBeenCalledTimes(1);+ expect(isFullAgentListAvatarCacheEntry(previous)).toBe(true);+ expect(isFullAgentListAvatarCacheEntry({ ...previous, scope: 'page' })).toBe(false);+ });++ it('presigns only the manager search page without writing agent documents', async () => {+ const options = params();+ const result = await refreshManagedAgentListPageAvatars(options);++ expect(options.refreshS3Url).toHaveBeenCalledTimes(1);+ expect(options.refreshS3Url).toHaveBeenCalledWith(visible.avatar);+ expect(result?.urlCache).toEqual({ 'agent-visible': 'signed-visible.jpg' });+ expect(options.cacheSet).toHaveBeenCalledWith(options.cacheKey, result, expect.any(Number));+ expect(options.cacheSet.mock.calls[0][2]).toBeLessThanOrEqual(options.ttl);++ await refreshManagedAgentListPageAvatars({+ ...options,+ cachedEntry: result,+ agents: [visible],+ });+ expect(options.refreshS3Url).toHaveBeenCalledTimes(1);++ await refreshManagedAgentListPageAvatars({+ ...options,+ cachedEntry: result,+ agents: [nextPage],+ });+ expect(options.refreshS3Url).toHaveBeenCalledTimes(2);+ });++ it('bounds each manager cache entry while retaining the newest entries', async () => {+ const options = params();+ const all = Array.from({ length: MAX_AVATAR_REFRESH_AGENTS + 1 }, (_, index) => ({+ id: `agent-${index}`,+ avatar: { source: FileSources.s3, filepath: `old-${index}.jpg` },+ }));+ const first = await refreshManagedAgentListPageAvatars({+ ...options,+ agents: all.slice(0, MAX_AVATAR_REFRESH_AGENTS),+ });+ const next = await refreshManagedAgentListPageAvatars({+ ...options,+ cachedEntry: first,+ agents: all.slice(MAX_AVATAR_REFRESH_AGENTS),+ });++ expect(Object.keys(next!.urlCache)).toHaveLength(MAX_AVATAR_REFRESH_AGENTS);+ expect(next!.urlCache['agent-0']).toBeUndefined();+ expect(next!.urlCache[`agent-${MAX_AVATAR_REFRESH_AGENTS}`]).toBe('signed-visible.jpg');+ expect(options.cacheSet).toHaveBeenCalledTimes(2);+ });++ it('re-signs entries after their original TTL even when later pages updated the cache', async () => {+ const options = params();+ const clock = jest.spyOn(Date, 'now').mockReturnValue(1000);+ try {+ const first = await refreshManagedAgentListPageAvatars(options);+ expect(first?.expiresAt).toBe(1000 + options.ttl);+ clock.mockReturnValue(1000 + options.ttl - 1);+ const second = await refreshManagedAgentListPageAvatars({+ ...options,+ cachedEntry: first,+ agents: [nextPage],+ });+ expect(options.cacheSet.mock.calls[1][2]).toBe(1);++ clock.mockReturnValue(1000 + options.ttl);+ const renewed = await refreshManagedAgentListPageAvatars({+ ...options,+ cachedEntry: second,+ agents: [visible],+ });+ expect(renewed?.expiresAt).toBe(1000 + options.ttl * 2);+ expect(options.refreshS3Url).toHaveBeenCalledTimes(3);+ } finally {+ clock.mockRestore();+ }+ });++ it('re-signs when another user replaces a cached avatar', async () => {+ const options = params();+ const previous = await refreshManagedAgentListPageAvatars(options);+ const replacement = {+ id: visible.id,+ avatar: { source: FileSources.s3, filepath: 'replacement.jpg' },+ };+ options.refreshS3Url.mockResolvedValueOnce('signed-replacement.jpg');++ const refreshed = await refreshManagedAgentListPageAvatars({+ ...options,+ cachedEntry: previous,+ agents: [replacement],+ });++ expect(options.refreshS3Url).toHaveBeenCalledTimes(2);+ expect(refreshed?.urlCache[visible.id]).toBe('signed-replacement.jpg');+ expect(refreshed?.avatarPaths?.[visible.id]).toBe('replacement.jpg');+ expect(options.cacheSet).toHaveBeenCalledTimes(2);+ });++ it('leaves an ordinary ACL viewer on the pre-query full-list refresh path', async () => {+ const options = params();+ const previous = { urlCache: { 'agent-visible': 'signed.jpg' } };+ const result = await refreshManagedAgentListPageAvatars({+ ...options,+ accessibleIds: ['507f1f77bcf86cd799439011'],+ cachedEntry: previous,+ });+ expect(result).toBe(previous);+ expect(options.refreshS3Url).not.toHaveBeenCalled();+ expect(options.cacheSet).not.toHaveBeenCalled();+ });++ it('allows retry after an S3 failure without failing the list response', async () => {+ const options = params();+ options.refreshS3Url.mockRejectedValueOnce(new Error('S3 unavailable'));+ const result = await refreshManagedAgentListPageAvatars(options);+ expect(result?.urlCache).toEqual({});+ expect(options.cacheSet).not.toHaveBeenCalled();+ await refreshManagedAgentListPageAvatars({ ...options, cachedEntry: result });+ expect(options.cacheSet).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/api/src/agents/listingAvatars.ts b/packages/api/src/agents/listingAvatars.tsnew file mode 100644index 0000000000..8be8e3bbe0--- /dev/null+++ b/packages/api/src/agents/listingAvatars.ts@@ -0,0 +1,145 @@+import { logger } from '@librechat/data-schemas';+import { FileSources } from 'librechat-data-provider';+import type { AgentAvatar } from 'librechat-data-provider';+import type { RefreshS3UrlFn } from './avatars';+import { AVATAR_REFRESH_BATCH_SIZE, MAX_AVATAR_REFRESH_AGENTS } from './avatars';++type AvatarRefreshEntry = {+ urlCache: Record<string, string>;+ /** Stored pathname corresponding to each signed page URL, used to detect avatar replacements. */+ avatarPaths?: Record<string, string>;+ scope?: 'page';+ expiresAt?: number;+};+type ListedAgent = { id?: string; avatar?: AgentAvatar };++/** The list writer and avatar upload invalidator must always use the same tenant-scoped key. */+export function getAgentListAvatarRefreshKey(user: {+ id: string;+ tenantId?: string | null;+}): string {+ return `${user.id}:${user.tenantId ?? ''}:agents_avatar_refresh`;+}++function validRefreshEntry(entry: unknown): entry is AvatarRefreshEntry {+ return (+ entry != null &&+ typeof entry === 'object' &&+ 'urlCache' in entry &&+ entry.urlCache != null &&+ typeof entry.urlCache === 'object' &&+ !Array.isArray(entry.urlCache)+ );+}++export function isFullAgentListAvatarCacheEntry(entry: unknown): boolean {+ return validRefreshEntry(entry) && entry.scope !== 'page';+}++/** Only ACL-scoped lists use the full-set refresh, which must finish before a cursor snapshot. */+export async function refreshAgentListAvatarsBeforePage(+ accessibleIds: string[] | null,+ cachedEntry: unknown,+ refreshAll: () => Promise<AvatarRefreshEntry | null>,+): Promise<AvatarRefreshEntry | null> {+ if (accessibleIds === null) {+ return validRefreshEntry(cachedEntry) ? cachedEntry : null;+ }+ return refreshAll();+}++/**+ * A manager has access to the whole tenant, but refreshing all of its avatars before each+ * search can presign and write hundreds of unrelated agents. Refresh only the visible page.+ * Do not persist these URL changes: updating `updatedAt` after taking a cursor snapshot would+ * reorder later pages, and legacy users without tenant context cannot safely update by public ID.+ */+export async function refreshManagedAgentListPageAvatars({+ accessibleIds,+ agents,+ cachedEntry,+ refreshS3Url,+ cacheSet,+ cacheKey,+ ttl,+}: {+ accessibleIds: string[] | null;+ agents: ListedAgent[];+ cachedEntry: AvatarRefreshEntry | null;+ refreshS3Url: RefreshS3UrlFn;+ cacheSet: (key: string, entry: AvatarRefreshEntry, ttl: number) => Promise<unknown>;+ cacheKey: string;+ ttl: number;+}): Promise<AvatarRefreshEntry | null> {+ if (accessibleIds !== null || agents.length === 0) {+ return cachedEntry;+ }++ const now = Date.now();+ const cachedExpiresAt = cachedEntry?.scope === 'page' ? cachedEntry.expiresAt : undefined;+ const cachedPageIsFresh = typeof cachedExpiresAt === 'number' && cachedExpiresAt > now;+ const urlCache = cachedPageIsFresh ? { ...cachedEntry?.urlCache } : {};+ const avatarPaths = cachedPageIsFresh ? { ...cachedEntry?.avatarPaths } : {};+ const expiresAt = cachedPageIsFresh ? cachedExpiresAt : now + ttl;+ // A different user can replace an agent's avatar without clearing this viewer's cache.+ // Never overlay a new avatar with a signed URL for an older stored pathname.+ for (const agent of agents) {+ if (+ agent.id &&+ Object.prototype.hasOwnProperty.call(urlCache, agent.id) &&+ (agent.avatar?.source !== FileSources.s3 ||+ !agent.avatar.filepath ||+ avatarPaths[agent.id] !== agent.avatar.filepath)+ ) {+ delete urlCache[agent.id];+ delete avatarPaths[agent.id];+ }+ }+ const pending = agents.filter(+ (agent) =>+ agent.id &&+ agent.avatar?.source === FileSources.s3 &&+ agent.avatar.filepath &&+ !Object.prototype.hasOwnProperty.call(urlCache, agent.id),+ );+ if (pending.length === 0) {+ return cachedPageIsFresh ? { urlCache, avatarPaths, scope: 'page', expiresAt } : null;+ }++ let changed = false;+ for (let index = 0; index < pending.length; index += AVATAR_REFRESH_BATCH_SIZE) {+ await Promise.all(+ pending.slice(index, index + AVATAR_REFRESH_BATCH_SIZE).map(async (agent) => {+ try {+ const url = await refreshS3Url(agent.avatar!);+ if (url && agent.id) {+ urlCache[agent.id] = url;+ avatarPaths[agent.id] = agent.avatar!.filepath!;+ changed = true;+ }+ } catch (error) {+ logger.warn('[AgentList] Failed to refresh visible avatar: %o', error);+ }+ }),+ );+ }++ if (changed) {+ // A manager can visit far more agents than the full-set refresh ever loads.+ // Bound one user's Redis entry to the existing avatar-refresh budget.+ const cacheIds = Object.keys(urlCache);+ for (const id of cacheIds.slice(0, Math.max(0, cacheIds.length - MAX_AVATAR_REFRESH_AGENTS))) {+ delete urlCache[id];+ delete avatarPaths[id];+ }+ }+ const entry: AvatarRefreshEntry = { urlCache, avatarPaths, scope: 'page', expiresAt };+ if (changed) {+ try {+ await cacheSet(cacheKey, entry, Math.max(1, expiresAt - Date.now()));+ } catch (error) {+ logger.warn('[AgentList] Failed to cache refreshed avatars: %o', error);+ }+ }+ return entry;+}diff --git a/packages/api/src/agents/reads.spec.ts b/packages/api/src/agents/reads.spec.tsindex 1783103ccf..cc6e6d4fe7 100644--- a/packages/api/src/agents/reads.spec.ts+++ b/packages/api/src/agents/reads.spec.ts@@ -10,6 +10,7 @@ import type { IRole, IUser } from '@librechat/data-schemas';import type { Request, Response } from 'express';import type { AgentManagementReadDeps } from './reads';import { createAgentManagementReadHandlers } from './reads';+import { getAgentListAccess } from './listing';jest.mock('@librechat/data-schemas', () => {const actual = jest.requireActual('@librechat/data-schemas');@@ -70,6 +71,119 @@ function makeDeps(overrides: Partial<AgentManagementReadDeps> = {}): AgentManage};}+describe('Agent list access', () => {+ it('rejects invalid permission masks before checking the manager bypass', async () => {+ const deps = makeDeps({ hasCapability: jest.fn().mockResolvedValue(true) });++ await expect(getAgentListAccess(user, 0 as PermissionBits, deps)).rejects.toThrow(+ 'requiredPermissions must be a positive number',+ );+ expect(deps.hasCapability).not.toHaveBeenCalled();+ expect(deps.findAccessibleResources).not.toHaveBeenCalled();+ });++ it('does not use speculative ACL results for a manager', async () => {+ const deps = makeDeps({ hasCapability: jest.fn().mockResolvedValue(true) });++ const access = await getAgentListAccess(user, PermissionBits.VIEW, deps);++ expect(deps.hasCapability).toHaveBeenCalledWith(user, SystemCapabilities.MANAGE_AGENTS);+ expect(deps.findAccessibleResources).toHaveBeenCalledTimes(2);+ expect(access).toEqual({ accessibleIds: null, editableIds: null });+ });++ it('uses the ACL for ordinary viewers and marks only editable agents', async () => {+ const editableId = new Types.ObjectId();+ const deps = makeDeps({+ findAccessibleResources: jest+ .fn()+ .mockImplementation(({ requiredPermissions }) =>+ Promise.resolve(+ requiredPermissions === PermissionBits.EDIT ? [editableId] : [objectId, editableId],+ ),+ ),+ });++ const access = await getAgentListAccess(user, PermissionBits.VIEW, deps);++ expect(access).toEqual({+ accessibleIds: [objectId.toString(), editableId.toString()],+ editableIds: [editableId.toString()],+ });+ expect(deps.findAccessibleResources).toHaveBeenCalledWith({+ userId: user.id,+ role: user.role,+ idOnTheSource: user.idOnTheSource,+ resourceType: ResourceType.AGENT,+ requiredPermissions: PermissionBits.VIEW,+ });+ expect(deps.findAccessibleResources).toHaveBeenCalledWith(+ expect.objectContaining({ requiredPermissions: PermissionBits.EDIT }),+ );+ });++ it('falls back to the ACL rather than bypassing on capability-check failure', async () => {+ const deps = makeDeps({+ hasCapability: jest.fn().mockRejectedValue(new Error('lookup failed')),+ });++ const access = await getAgentListAccess(user, PermissionBits.VIEW, deps);++ expect(access).toEqual({+ accessibleIds: [objectId.toString()],+ editableIds: [objectId.toString()],+ });+ expect(deps.findAccessibleResources).toHaveBeenCalledTimes(2);+ });++ it('starts ACL queries while capability lookup is still pending', async () => {+ let resolveCapability!: (value: boolean) => void;+ const capability = new Promise<boolean>((resolve) => {+ resolveCapability = resolve;+ });+ const deps = makeDeps({ hasCapability: jest.fn().mockReturnValue(capability) });++ const accessPromise = getAgentListAccess(user, PermissionBits.VIEW, deps);+ expect(deps.findAccessibleResources).toHaveBeenCalledTimes(2);+ resolveCapability(false);+ await expect(accessPromise).resolves.toEqual({+ accessibleIds: [objectId.toString()],+ editableIds: [objectId.toString()],+ });+ });++ it('does not require the speculative ACL reads to succeed for a manager', async () => {+ const deps = makeDeps({+ hasCapability: jest.fn().mockResolvedValue(true),+ findAccessibleResources: jest.fn().mockRejectedValue(new Error('ACL unavailable')),+ });++ await expect(getAgentListAccess(user, PermissionBits.VIEW, deps)).resolves.toEqual({+ accessibleIds: null,+ editableIds: null,+ });+ });++ it('propagates ACL lookup errors for a user without management capability', async () => {+ const deps = makeDeps({+ findAccessibleResources: jest.fn().mockRejectedValue(new Error('ACL unavailable')),+ });++ await expect(getAgentListAccess(user, PermissionBits.VIEW, deps)).rejects.toThrow(+ 'ACL unavailable',+ );+ });++ it('does not repeat the EDIT lookup for an EDIT-scoped list', async () => {+ const deps = makeDeps();++ const access = await getAgentListAccess(user, PermissionBits.EDIT, deps);++ expect(access).toEqual({ accessibleIds: [objectId.toString()], editableIds: null });+ expect(deps.findAccessibleResources).toHaveBeenCalledTimes(1);+ });+});+describe('Agent Management read handlers', () => {it('lists only ACL-discovered records in the authenticated tenant', async () => {const deps = makeDeps();diff --git a/packages/api/src/agents/reads.ts b/packages/api/src/agents/reads.tsindex 737094ed7c..c1cfa111c2 100644--- a/packages/api/src/agents/reads.ts+++ b/packages/api/src/agents/reads.ts@@ -90,7 +90,10 @@ async function canViewAgent(});}-async function hasManageAgentsCapability(user: IUser, deps: AgentManagementReadDeps) {+export async function hasManageAgentsCapability(+ user: IUser,+ deps: Pick<AgentManagementReadDeps, 'hasCapability'>,+): Promise<boolean> {const capability = ResourceCapabilityMap[ResourceType.AGENT];try {if (capability != null && (await deps.hasCapability(user, capability))) {diff --git a/packages/data-schemas/src/methods/agent.spec.ts b/packages/data-schemas/src/methods/agent.spec.tsindex 0fbe6b0e49..1eecbcdeb5 100644--- a/packages/data-schemas/src/methods/agent.spec.ts+++ b/packages/data-schemas/src/methods/agent.spec.ts@@ -5029,6 +5029,37 @@ describe('Support Contact Field', () => {});});+ test('unrestricted listing still applies filters and paginates without overlap', async () => {+ const first = await getListAgentsByAccess({+ accessibleIds: null,+ otherParams: { name: /^Agent A/ },+ limit: 1,+ });+ expect(first.data).toHaveLength(1);+ expect(first.has_more).toBe(true);+ expect(first.after).toBeTruthy();++ const second = await getListAgentsByAccess({+ accessibleIds: null,+ otherParams: { name: /^Agent A/ },+ limit: 1,+ after: first.after,+ });+ expect(second.data).toHaveLength(1);+ expect(second.has_more).toBe(true);++ const third = await getListAgentsByAccess({+ accessibleIds: null,+ otherParams: { name: /^Agent A/ },+ limit: 1,+ after: second.after,+ });+ expect(third.has_more).toBe(false);+ expect(+ [first, second, third].flatMap((page) => page.data.map((agent) => agent.id)).sort(),+ ).toEqual([agentA1.id, agentA2.id, agentA3.id].sort());+ });+test('should return empty list when user has no accessible agents (empty accessibleIds)', async () => {// User B has no agents and no shared agentsconst result = await getListAgentsByAccess({@@ -5042,6 +5073,90 @@ describe('Support Contact Field', () => {expect(result.last_id).toBeNull();});+ test('unrestricted listing cannot cross tenant boundaries', async () => {+ const tenantA = `tenant-a-${uuidv4()}`;+ const tenantB = `tenant-b-${uuidv4()}`;+ const name = 'Shared Name';+ const agentInA = await tenantStorage.run({ tenantId: tenantA }, () =>+ createAgent({+ id: `agent_${uuidv4()}`,+ name,+ provider: 'openai',+ model: 'gpt-4',+ author: userA,+ }),+ );+ await tenantStorage.run({ tenantId: tenantB }, () =>+ createAgent({+ id: `agent_${uuidv4()}`,+ name,+ provider: 'openai',+ model: 'gpt-4',+ author: userB,+ }),+ );++ const result = await tenantStorage.run({ tenantId: tenantA }, () =>+ getListAgentsByAccess({ accessibleIds: null, tenantId: tenantA, otherParams: { name } }),+ );+ expect(result.data.map((agent) => agent.id)).toEqual([agentInA.id]);+ const denied = await tenantStorage.run({ tenantId: tenantA }, () =>+ getListAgentsByAccess({ accessibleIds: [], otherParams: { name } }),+ );+ expect(denied.data).toHaveLength(0);+ });++ test('unrestricted list uses the supplied tenant even without request context', async () => {+ const tenantA = `tenant-a-${uuidv4()}`;+ const tenantB = `tenant-b-${uuidv4()}`;+ const name = 'Same Agent Name';+ const legacy = await createAgent({+ id: `agent_${uuidv4()}`,+ name,+ provider: 'openai',+ model: 'gpt-4',+ author: userA,+ });+ const agentInA = await tenantStorage.run({ tenantId: tenantA }, () =>+ createAgent({+ id: `agent_${uuidv4()}`,+ name,+ provider: 'openai',+ model: 'gpt-4',+ author: userA,+ }),+ );+ await tenantStorage.run({ tenantId: tenantB }, () =>+ createAgent({+ id: `agent_${uuidv4()}`,+ name,+ provider: 'openai',+ model: 'gpt-4',+ author: userB,+ }),+ );++ const scoped = await getListAgentsByAccess({+ accessibleIds: null,+ tenantId: tenantA,+ otherParams: { name },+ });+ expect(scoped.data.map((agent) => agent.id)).toEqual([agentInA.id]);+ const legacyOnly = await getListAgentsByAccess({+ accessibleIds: null,+ tenantId: null,+ otherParams: { name },+ });+ expect(legacyOnly.data.map((agent) => agent.id)).toEqual([legacy.id]);+ const omitted = await getListAgentsByAccess({ accessibleIds: null, otherParams: { name } });+ expect(omitted.data.map((agent) => agent.id)).toEqual([legacy.id]);+ });++ test('accepts plain string IDs from the API resolver without weakening ACL filtering', async () => {+ const result = await getListAgentsByAccess({ accessibleIds: [agentA2._id.toString()] });+ expect(result.data.map((agent) => agent.id)).toEqual([agentA2.id]);+ });+test('should not return other users agents when accessibleIds is empty', async () => {// User B trying to list agents with empty accessibleIds should not see User A's agentsconst result = await getListAgentsByAccess({diff --git a/packages/data-schemas/src/methods/agent.ts b/packages/data-schemas/src/methods/agent.tsindex 701a505658..4295248995 100644--- a/packages/data-schemas/src/methods/agent.ts+++ b/packages/data-schemas/src/methods/agent.ts@@ -606,13 +606,16 @@ export function createAgentMethods(getListAgentsByAccess: ({accessibleIds,otherParams,+ tenantId,limit,after,includeSkillConfig,includeExecutionConfig,}: {- accessibleIds?: Types.ObjectId[];+ accessibleIds?: Array<Types.ObjectId | string> | null;otherParams?: Record<string, unknown>;+ /** Authenticated tenant for unrestricted listings; null/omitted restricts to legacy agents. */+ tenantId?: string | null;limit?: number | null;after?: string | null;includeSkillConfig?: boolean;@@ -1423,19 +1426,23 @@ export function createAgentMethods(}/**- * Get agents by accessible IDs with cursor pagination. Defaults to a 100-page- * limit (max 1000); pass `limit: null` to opt out entirely.+ * Get agents by accessible IDs with cursor pagination. Pass `accessibleIds: null`+ * only after a management-capability check, with the authenticated tenantId+ * (or null for legacy agents); `[]` and omitted IDs match nothing.+ * Defaults to a 100-page limit (max 1000); pass `limit: null` to opt out entirely.*/async function getListAgentsByAccess({accessibleIds = [],otherParams = {},+ tenantId,limit = 100,after = null,includeSkillConfig = false,includeExecutionConfig = false,}: {- accessibleIds?: Types.ObjectId[];+ accessibleIds?: Array<Types.ObjectId | string> | null;otherParams?: Record<string, unknown>;+ tenantId?: string | null;limit?: number | null;after?: string | null;includeSkillConfig?: boolean;@@ -1456,7 +1463,9 @@ export function createAgentMethods(const baseQuery: Record<string, unknown> = {...otherParams,- _id: { $in: accessibleIds },+ ...(accessibleIds === null+ ? { tenantId: tenantId ?? null }+ : { _id: { $in: accessibleIds } }),};if (after) {